This file is indexed.

/usr/share/perl5/EBook/Tools.pm is in libebook-tools-perl 0.4.9-1.

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
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
package EBook::Tools;
use warnings; use strict; use utf8;
#use 5.010; # Needed for smart-match operator
#v5.10 feature use removed until 5.10 is standard on MacOSX and Debian
use English qw( -no_match_vars );
use version 0.74; our $VERSION = qv("0.4.9");

#use warnings::unused;

# Perl Critic overrides:
## no critic (Package variable)
# RequireBriefOpen seems to be way too brief to be useful
## no critic (RequireBriefOpen)
# Double-sigils are needed for lexical filehandles in clear print statements
## no critic (Double-sigil dereference)
our $debug = 0;



=head1 NAME

EBook::Tools - Object class for manipulating and generating E-books


=head1 DESCRIPTION

This module provides an object interface and a number of related
procedures intended to create or modify documents centered around the
International Digital Publishing Forum (IDPF) standards, currently
both OEBPS v1.2 and OPS/OPF v2.0.

=cut

=head1 SYNOPSIS

 use EBook::Tools qw(split_metadata system_tidy_xml);
 $EBook::Tools::tidysafety = 2;

 my $opffile = split_metadata('ebook.html');
 my $otheropffile = 'alternate.opf';
 my $retval = system_tidy_xml($opffile,'tidy-backup.xml');
 my $ebook = EBook::Tools->new($opffile);
 $ebook->fix_opf20;
 $ebook->fix_misc;
 $ebook->print;
 $ebook->save;

 $ebook->init($otheropffile);
 $ebook->fix_oeb12;
 $ebook->gen_epub;


=head1 DEPENDENCIES

=head2 Perl Modules

=over

=item Archive::Zip

=item Data::UUID (or OSSP::UUID)

=item Date::Manip

Note that Date::Manip will die on MS Windows system unless the
TZ environment variable is set in a specific manner. See:

http://search.cpan.org/perldoc?Date::Manip#TIME_ZONES

=item File::MimeInfo

=item HTML::Parser

=item Tie::IxHash

=item Time::Local

=item XML::Twig

=back

=head2 Other Programs

=over

=item Tidy

The command "tidy" needs to be available, and ideally on the path.  If
it isn't on the path, package variable L</$tidycmd> can be set to its
absolute path.  If tidy cannot be found, L</system_tidy_xml()> and
L</system_tidy_xhtml()> will be nonfunctional.

=back

=cut


require Exporter;
use base qw(Exporter);

our @EXPORT_OK;
@EXPORT_OK = qw (
    &create_epub_container
    &create_epub_mimetype
    &debug
    &excerpt_line
    &fix_datestring
    &find_in_path
    &find_links
    &find_opffile
    &hexstring
    &get_container_rootfile
    &print_memory
    &split_metadata
    &split_pre
    &strip_script
    &system_tidy_xml
    &system_tidy_xhtml
    &trim
    &twigelt_create_uuid
    &twigelt_fix_oeb12_atts
    &twigelt_fix_opf20_atts
    &twigelt_is_author
    &usedir
    &userconfigdir
    &ymd_validate
    );
our %EXPORT_TAGS = ('all' => [@EXPORT_OK]);

# OSSP::UUID will provide Data::UUID on systems such as Debian that do
# not distribute the original Data::UUID.
use Data::UUID;

use Archive::Zip qw( :CONSTANTS :ERROR_CODES );
use Carp;
use Cwd qw(getcwd realpath);
use Date::Manip;
use File::Basename qw(basename dirname fileparse);
# File::MimeInfo::Magic gets *.css right, but detects all html as
# text/html, even if it has an XML header.
use File::MimeInfo::Magic;
# File::MMagic gets text/xml right (though it still doesn't properly
# detect XHTML), but detects CSS as x-system, and has a number of
# other weird bugs.
#use File::MMagic;
use File::Path;     # Exports 'mkpath' and 'rmtree'
use File::Temp;
use HTML::Entities qw(decode_entities _decode_entities %entity2char);
#use HTML::Tidy;
use Tie::IxHash;
use Time::Local;
use XML::Twig;

=head1 CONFIGURABLE PACKAGE VARIABLES

=over

=item C<%dcelements12>

A tied IxHash mapping an all-lowercase list of Dublin Core metadata
element names to the capitalization dictated by the OEB 1.2
specification, used by the fix_oeb12() and fix_oeb12_dcmeta() methods.
Changing the tags in this list will change the tags recognized and
placed inside the <dc-metadata> element.

Order is preserved and significant -- fix_oeb12 will output DC
metadata elements in the same order as in this hash, though order for
tags of the same name is preserved from the input file.

=item C<%dcelements20>

A tied IxHash mapping an all-lowercase list of Dublin Core metadata
element names to the all-lowercase form dictated by the OPF 2.0
specification (which means it maps the all-lowercase tags to
themselves).  It is used by the fix_opf20() and fix_opf20_dcmeta()
methods.  Changing the tags in this list will change the tags
recognized and placed directly under the <metadata> element.

Order is preserved and significant -- fix_opf20 will output DC
metadata elements in the same order as in this hash, though order for
tags of the same name is preserved from the input file.

=item C<%nonxmlentity2char>

This is the %entity2char conversion map from HTML::Entities with the 5
pre-defined XML entities (amp, gt, lt, quot, apos) removed.  This is
used during by L</init()> to sanitize the OPF file data before
parsing.  This hash can be modified to allow and convert other
non-standard entities to unicode characters.  See HTML::Entities for
details.

=item C<%publishermap>

A hash mapping known variants of publisher names to a canonical form,
used by L</fix_publisher()>, and thus also indirectly by
L</fix_misc()>.

Keys should be entered in lowercase.  The hash can also be set empty
to prevent fix_publisher() from taking any action at all.

=item C<%relatorcodes>

A hash mapping the MARC Relator Codes (see:
http://www.loc.gov/marc/relators/relacode.html) to their descriptive
names.

=item C<$tidycmd>

The tidy executable name.  This has to be a fully qualified pathname
if tidy isn't on the path.  Defaults to 'tidy'.

=item C<$tidyxhtmlerrors>

The name of the error output file from system_tidy_xhtml().  Defaults
to 'tidyxhtml-errors.txt'

=item C<$tidyxmlerrors>

The name of the error output file from system_tidy_xml().  Defaults to
'tidyxml-errors.txt'

=item C<$tidysafety>

The safety level to use when running tidy (default is 1).  Potential
values are:

=over

=item C<$tidysafety < 1>:

No checks performed, no error files kept, works like a clean tidy -m

This setting is DANGEROUS!

=item C<$tidysafety == 1>:

Overwrites original file if there were no errors, but even if there
were warnings.  Keeps a log of errors, but not warnings.

=item C<$tidysafety == 2>:

Overwrites original file if there were no errors, but even if there
were warnings.  Keeps a log of both errors and warnings.

=item C<$tidysafety == 3>:

Overwrites original file only if there were no errors or warnings.
Keeps a log of both errors and warnings.

=item C<$tidysafety >= 4>:

Never overwrites original file.  Keeps a log of both errors and
warnings.

=back

=item C<%validspecs>

A hash mapping valid specification strings to themselves, primarily
used to undefine unrecognized values.  Default valid values are 'OEB12'
and 'OPF20'.

=back

=cut

our $mobi2htmlcmd = 'mobi2html';
our $tidycmd = 'tidy'; # Specify full pathname if not on path
our $tidyxhtmlerrors = 'tidyxhtml-errors.txt';
our $tidyxmlerrors = 'tidyxml-errors.txt';
our $tidysafety = 1;


our $utf8xmldec = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
our $oeb12doctype =
    '<!DOCTYPE package' . "\n" .
    '  PUBLIC "+//ISBN 0-9673008-1-9//DTD OEB 1.2 Package//EN"' . "\n" .
    '  "http://openebook.org/dtds/oeb-1.2/oebpkg12.dtd">' . "\n";
our $opf20package =
    '<package version="2.0" xmlns="http://www.idpf.org/2007/opf">' . "\n";

our %dcelements12;
tie %dcelements12, 'Tie::IxHash', (
    "dc:identifier"  => "dc:Identifier",
    "dc:title"       => "dc:Title",
    "dc:creator"     => "dc:Creator",
    "dc:contributor" => "dc:Contributor",
    "dc:subject"     => "dc:Subject",
    "dc:description" => "dc:Description",
    "dc:publisher"   => "dc:Publisher",
    "dc:date"        => "dc:Date",
    "dc:type"        => "dc:Type",
    "dc:format"      => "dc:Format",
    "dc:source"      => "dc:Source",
    "dc:language"    => "dc:Language",
    "dc:relation"    => "dc:Relation",
    "dc:coverage"    => "dc:Coverage",
    "dc:rights"      => "dc:Rights",
    "dc:copyrights"  => "dc:Rights"
    );

our %dcelements20;
tie %dcelements20, 'Tie::IxHash', (
    "dc:identifier"  => "dc:identifier",
    "dc:title"       => "dc:title",
    "dc:creator"     => "dc:creator",
    "dc:contributor" => "dc:contributor",
    "dc:subject"     => "dc:subject",
    "dc:description" => "dc:description",
    "dc:publisher"   => "dc:publisher",
    "dc:date"        => "dc:date",
    "dc:type"        => "dc:type",
    "dc:format"      => "dc:format",
    "dc:source"      => "dc:source",
    "dc:language"    => "dc:language",
    "dc:relation"    => "dc:relation",
    "dc:coverage"    => "dc:coverage",
    "dc:rights"      => "dc:rights",
    "dc:copyrights"  => "dc:rights"
    );

our %mobibooktypes = (
    'Default' => undef,
    'eBook' => 'text/x-oeb1-document',
    'eNews' => 'application/x-mobipocket-subscription',
    'News feed' => 'application/x-mobipocket-subscription-feed',
    'News magazine' => 'application/x-mobipocket-subscription-magazine',
    'Images' => 'image/gif',
    'Microsoft Word document' => 'application/msword',
    'Microsoft Excel sheet' => 'application/vnd.ms-excel',
    'Microsoft Powerpoint presentation' => 'application/vnd.ms-powerpoint',
    'Plain text' => 'text/plain',
    'HTML' => 'text/html',
    'Mobipocket game' => 'application/vnd.mobipocket-game',
    'Franklin game' => 'application/vnd.mobipocket-franklin-ua-game'
    );

our %publishermap = (
    'ace'                   => 'Ace Books',
    'acebooks'              => 'Ace Books',
    'ace books'             => 'Ace Books',
    'baen'                  => 'Baen Publishing Enterprises',
    'baen publishing'       => 'Baen Publishing Enterprises',
    'ballantine'            => 'Ballantine Books',
    'ballantine books'      => 'Ballantine Books',
    'barnes and noble'      => 'Barnes and Noble Publishing',
    'barnesandnoble.com'    => 'Barnes and Noble Publishing',
    'cpan'                  => 'CPAN',
    'delrey'                => 'Del Rey Books',
    'del rey'               => 'Del Rey Books',
    'del rey books'         => 'Del Rey Books',
    'e-reads'               => 'E-Reads',
    'ereads'                => 'E-Reads',
    'ereads.com'            => 'E-Reads',
    'www.ereads.com'        => 'E-Reads',
    'feedbooks'             => 'Feedbooks',
    'feedbooks (www.feedbooks.com)' => 'Feedbooks',
    'www.feedbooks.com'     => 'Feedbooks',
    'fictionwise'           => 'Fictionwise',
    'fictionwise.com'       => 'Fictionwise',
    'www.fictionwise.com'   => 'Fictionwise',
    'harmony'               => 'Harmony Books',
    'harmony books'         => 'Harmony Books',
    'harpercollins'         => 'HarperCollins',
    'harper collins'        => 'HarperCollins',
    'harper-collins'        => 'HarperCollins',
    'manybooks'             => 'ManyBooks',
    'manybooks.net'         => 'ManyBooks',
    'project gutenberg'     => 'Project Gutenberg',
    'gutenberg'             => 'Project Gutenberg',
    'gutenberg.org'         => 'Project Gutenberg',
    'www.gutenberg.org'     => 'Project Gutenberg',
    'randomhouse'           => 'Random House',
    'randomhouse.co.uk'     => 'Random House',
    'www.randomhouse.co.uk' => 'Random House',
    'random-house.com'      => 'Random House',
    'www.random-house.com'  => 'Random House',
    'rosetta'               => 'Rosetta Books',
    'rosettabooks'          => 'Rosetta Books',
    'rosetta books'         => 'Rosetta Books',
    'siren'                 => 'Siren Publishing',
    'siren publishing'      => 'Siren Publishing',
    'wildside'              => 'Wildside Press',
    'wildside press'        => 'Wildside Press',
    );


our %nonxmlentity2char = %entity2char;
delete($nonxmlentity2char{'amp'});
delete($nonxmlentity2char{'gt'});
delete($nonxmlentity2char{'lt'});
delete($nonxmlentity2char{'quot'});
delete($nonxmlentity2char{'apos'});

our %relatorcodes = (
    'act' => 'Actor',
    'adp' => 'Adapter',
    'ann' => 'Annotator',
    'ant' => 'Bibliographic antecedent',
    'app' => 'Applicant',
    'arc' => 'Architect',
    'arr' => 'Arranger',
    'art' => 'Artist',
    'asg' => 'Assignee',
    'asn' => 'Associated name',
    'att' => 'Attributed name',
    'aui' => 'Author of introduction',
    'aus' => 'Author of screenplay',
    'aut' => 'Author',
    'bdd' => 'Binding designer',
    'bjd' => 'Bookjacket designer',
    'bkd' => 'Book designer',
    'bkp' => 'Book producer',
    'bnd' => 'Binder',
    'bpd' => 'Bookplate designer',
    'bsl' => 'Bookseller',
    'chr' => 'Choreographer',
    'cli' => 'Client',
    'cll' => 'Calligrapher',
    'clt' => 'Collotyper',
    'cmm' => 'Commentator',
    'cmp' => 'Composer',
    'cmt' => 'Compositor',
    'cnd' => 'Conductor',
    'cns' => 'Censor',
    'coe' => 'Contestant-appellee',
    'col' => 'Collector',
    'com' => 'Compiler',
    'cos' => 'Contestant',
    'cot' => 'Contestant-appellant',
    'cpe' => 'Complainant-appellee',
    'cph' => 'Copyright holder',
    'cpl' => 'Complainant',
    'cpt' => 'Complainant-appellant',
    'crp' => 'Correspondent',
    'crr' => 'Corrector',
    'cst' => 'Costume designer',
    'cte' => 'Contestee-appellee',
    'ctg' => 'Cartographer',
    'cts' => 'Contestee',
    'ctt' => 'Contestee-appellant',
    'dfd' => 'Defendant',
    'dfe' => 'Defendant-appellee',
    'dft' => 'Defendant-appellant',
    'dln' => 'Delineator',
    'dnc' => 'Dancer',
    'dnr' => 'Donor',
    'dpt' => 'Depositor',
    'drt' => 'Director',
    'dsr' => 'Designer',
    'dst' => 'Distributor',
    'dte' => 'Dedicatee',
    'dto' => 'Dedicator',
    'dub' => 'Dubious author',
    'edt' => 'Editor',
    'egr' => 'Engraver',
    'elt' => 'Electrotyper',
    'eng' => 'Engineer',
    'etr' => 'Etcher',
    'flm' => 'Film editor',
    'fmo' => 'Former owner',
    'fnd' => 'Funder/Sponsor',
    'frg' => 'Forger',
    'grt' => 'Graphic technician (discontinued code)',
    'hnr' => 'Honoree',
    'ill' => 'Illustrator',
    'ilu' => 'Illuminator',
    'ins' => 'Inscriber',
    'inv' => 'Inventor',
    'itr' => 'Instrumentalist',
    'ive' => 'Interviewee',
    'ivr' => 'Interviewer',
    'lbt' => 'Librettist',
    'lee' => 'Libelee-appellee',
    'lel' => 'Libelee',
    'len' => 'Lender',
    'let' => 'Libelee-appellant',
    'lie' => 'Libelant-appellee',
    'lil' => 'Libelant',
    'lit' => 'Libelant-appellant',
    'lse' => 'Licensee',
    'lso' => 'Licensor',
    'ltg' => 'Lithographer',
    'lyr' => 'Lyricist',
    'mon' => 'Monitor/Contractor',
    'mte' => 'Metal-engraver',
    'nrt' => 'Narrator',
    'org' => 'Originator',
    'oth' => 'Other',
    'pbl' => 'Publisher',
    'pfr' => 'Proofreader',
    'pht' => 'Photographer',
    'plt' => 'Platemaker',
    'pop' => 'Printer of plates',
    'ppm' => 'Papermaker',
    'prd' => 'Production personnel',
    'prf' => 'Performer',
    'pro' => 'Producer',
    'prt' => 'Printer',
    'pte' => 'Plaintiff-appellee',
    'ptf' => 'Plaintiff',
    'pth' => 'Patent holder',
    'ptt' => 'Plaintiff-appellant',
    'rbr' => 'Rubricator',
    'rce' => 'Recording engineer',
    'rcp' => 'Recipient',
    'rse' => 'Respondent-appellee',
    'rsp' => 'Respondent',
    'rst' => 'Respondent-appellant',
    'sce' => 'Scenarist',
    'scr' => 'Scribe',
    'scl' => 'Sculptor',
    'sec' => 'Secretary',
    'sgn' => 'Signer',
    'srv' => 'Surveyor',
    'str' => 'Stereotyper',
    'trc' => 'Transcriber',
    'trl' => 'Translator',
    'tyd' => 'Type designer',
    'tyg' => 'Typographer',
    'voc' => 'Vocalist',
    'wam' => 'Writer of accompanying material',
    'wde' => 'Wood-engraver',
    'wit' => 'Witness',
    );

our %validspecs = (
    'OEB12' => 'OEB12',
    'OPF20' => 'OPF20',
    'MOBI12' => 'MOBI12',
    );


#####################################################
########## CONSTRUCTORS AND INITIALIZATION ##########
#####################################################

my %rwfields = (
    'opffile'  => 'string',
    'spec'     => 'string',
    );
my %rofields = (
    'twig'     => 'scalar',
    'twigroot' => 'scalar',
    'errors'   => 'arrayref',
    'warnings' => 'arrayref',
    );
my %privatefields = (
);

# A simple 'use fields' will not work here: use takes place inside
# BEGIN {}, so the @...fields variables won't exist.
require fields;
fields->import(
    keys(%rwfields),keys(%rofields),keys(%privatefields)
    );


=head1 CONSTRUCTORS AND INITIALIZATION

=head2 C<new($filename)>

Instantiates a new EBook::Tools object.  If C<$filename> is specified,
it will also immediately initialize itself via the C<init> method.

=cut

sub new   ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my $class = ref($self) || $self;
    my ($filename) = @_;
    my $subname = (caller(0))[3];
    debug(2,"DEBUG[",$subname,"]");

    $self = fields::new($class);

    if($filename)
    {
	debug(2,"DEBUG: new object from '",$filename,"'");
	$self->init($filename);
    }
    return $self;
}


=head2 C<init($filename)>

Initializes the object from an existing OPF file.  If C<$filename> is
specified and exists, the OEB object will be set to read and write to
that file before attempting to initialize.  Otherwise, if the object
currently points to an OPF file it will use that name.  If there is no
OPF filename data, and C<$filename> was not specified, it will make a
last-ditch attempt to find an OPF file first by looking in
META-INF/container.xml, and if nothing is found there, by looking in
the current directory for a single OPF file.

If no such files or found (or more than one is found), the
initialization croaks.

=cut

sub init :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my ($filename) = @_;
    my $fh_opffile;
    my $opfstring;
    my $subname = (caller(0))[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");

    if($filename) { $self->{opffile} = $filename; }

    if(!$self->{opffile})
    {
        $opfstring = find_opffile();
        $self->{opffile} = $opfstring if($opfstring);
    }

    if(!$self->{opffile})
    {
	croak($subname,"(): Unable to find an OPF file to work with!\n");
    }

    if(! -f $self->{opffile})
    {
	croak($subname,"(): '",$self->{opffile},
              "' does not exist or is not a regular file!")
    }

    if(-z $self->{opffile})
    {
	croak("OPF file '",$self->{opffile},"' has zero size!");
    }

    debug(2,"DEBUG: init using '",$self->{opffile},"'");

    # Initialize the twig before use
    $self->{twig} = XML::Twig->new(
	keep_atts_order => 1,
	output_encoding => 'utf-8',
	pretty_print => 'record'
	);

    # Read and decode entities before parsing to avoid parsing errors
    open($fh_opffile,'<:utf8',$self->{opffile})
        or croak($subname,"(): failed to open '",$self->{opffile},
                 "' for reading!");
    read($fh_opffile,$opfstring,-s $self->opffile)
        or croak($subname,"(): failed to read from '",$self->{opffile},"'!");
    close($fh_opffile)
        or croak($subname,"(): failed to close '",$self->{opffile},"'!");

    # We use _decode_entities and the custom hash to decode, but also
    # see below for the regexp
    _decode_entities($opfstring,\%nonxmlentity2char);

    # This runs decode_entities on the substring containing just the
    # entity for every entity *except* the 5 predefined internal
    # entities.  It seems to be about the same speed as running
    # _decode_entities on a small file, but having the hash map as a
    # package variable has additional utility, so that technique gets
    # used instead.
#    $opfstring =~
#        s/(&
#            (?! (?:lt|gt|quot|apos|amp);
#            )\w+;
#          )
#         / decode_entities($1) /gex;

    $self->{twig}->parse($opfstring);
    $self->{twigroot} = $self->{twig}->root;
    $self->twigcheck;
    debug(2,"DEBUG[/",$subname,"]");
    return $self;
}


=head2 C<init_blank(%args)>

Initializes an object containing nothing more than the basic OPF
framework, suitable for adding new documents when creating an e-book
from scratch.

=head3 Arguments

C<init_blank> takes up to three optional named arguments:

=over

=item C<opffile>

This specifies the OPF filename to use.  If not specified, defaults to
the name of the current working directory with ".opf" appended

=item C<author>

This specifies the content of the initial dc:creator element.  If not
specified, defaults to "Unknown Author".

=item C<title>

This specifies the content of the initial dc:title element. If not
specified, defaults to "Unknown Title".

=back

=head3 Example

 init_blank('opffile' => 'newfile.opf',
            'title' => 'The Great Unknown');

=cut

sub init_blank :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");


    my %valid_args = (
        'opffile' => 1,
        'author' => 1,
        'title' => 1,
        );
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }

    $args{opffile} ||= basename(getcwd) . ".opf";

    my $author = $args{author} || 'Unknown Author';
    my $title = $args{title} || 'Unknown Title';
    my $metadata;
    my $element;

    $self->{opffile} = $args{opffile};
    $self->{twig} = XML::Twig->new(
	keep_atts_order => 1,
	output_encoding => 'utf-8',
	pretty_print => 'record'
        );

    $element = XML::Twig::Elt->new('package');
    $self->{twig}->set_root($element);
    $self->{twigroot} = $self->{twig}->root;
    $metadata = $self->{twigroot}->insert_new_elt('first_child','metadata');

    # dc:identifier
    $self->fix_packageid;

    # dc:title
    $element = $metadata->insert_new_elt('last_child','dc:title');
    $element->set_text($title);

    # dc:creator (author)
    $element = $metadata->insert_new_elt('last_child','dc:creator');
    $element->set_att('opf:role','aut');
    $element->set_text($author);

    $self->fix_opf20;
    return 1;
}


######################################
########## ACCESSOR METHODS ##########
######################################

=head1 ACCESSOR METHODS

The following methods return data deeper in the structure than the
auto-accessors, but still do not modify any object data or files.


=head2 C<adult()>

Returns the text of the Mobipocket-specific <Adult> element, if it
exists.  Expected values are 'yes' and undef.

=cut

sub adult :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck;

    my $twigroot = $self->{twigroot};

    my $element = $twigroot->first_descendant(qr/^adult$/ix);
    return unless($element);

    if($element->text) { return $element->text; }
    else { return; }
}


=head2 C<contributor_list()>

Returns a list containing the text of all dc:contributor elements
(case-insensitive) or undef if none are found.

In scalar context, returns the first contributor, not the last.

=cut

sub contributor_list :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck;

    my @retval = ();
    my $twigroot = $self->{twigroot};

    my @elements = $twigroot->descendants(qr/dc:contributor/ix);
    return unless(@elements);

    foreach my $el (@elements)
    {
        push(@retval,$el->text) if($el->text);
    }
    return unless(@retval);
    if(wantarray) { return @retval; }
    else { return $retval[0]; }
}


=head2 C<date_list(%args)>

Returns the text of all dc:date elements (case-insensitive) matching
the specified attributes.

In scalar context, returns the first match, not the last.

Returns undef if no matches are found.

=head3 Arguments

=over

=item * C<id> - 'id' attribute that must be matched exactly for the
result to be added to the list

=item * C<event> 'opf:event' or 'event' attribute that must be
matched exactly for the result to be added to the list

=back

If both arguments are specified a value is added to the list if it
matches either one (i.e. the logic is OR).

=cut

sub date_list :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my %valid_args = (
        'id' => 1,
        'event' => 1,
        );
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }

    my @elements = $self->{twigroot}->descendants(qr/^ dc:date $/ix);
    my @list = ();
    my $id;
    my $scheme;
    foreach my $el (@elements)
    {
        if($args{id})
        {
            $id = $el->att('id') || '';
            if($id eq $args{id})
            {
                push(@list,$el->text);
                next;
            }
        }
        if($args{event})
        {
            $scheme = $el->att('opf:event') || $el->att('event') || '';
            if($scheme eq $args{event})
            {
                push(@list,$el->text);
                next;
            }
        }
        next if($args{id} || $args{event});
        push(@list,$el->text);
    }
    return unless(@list);
    if(wantarray) { return @list; }
    else { return $list[0]; }
}


=head2 C<description()>

Returns the description of the e-book, if set, or undef otherwise.

=cut

sub description :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck;

    my $twigroot = $self->{twigroot};

    my $element = $twigroot->first_descendant(qr/^dc:description$/ix);
    return unless($element);

    if($element->text) { return $element->text; }
    else { return; }
}


=head2 C<element_list(%args)>

Returns a list containing the text values of all elements matching the
specified criteria.

=head3 Arguments

=over

=item * C<cond>

The L<XML::Twig> search condition used to find the elements.
Typically this is just the GI (tag) of the element you wish to find,
but it can also be a C<qr//> expression, coderef, or anything else
that XML::Twig can work with.  See the XML::Twig documentation for
details.

If this is not specified, an error is added and the method returns
undef.

=item * C<id> (optional)

'id' attribute that must be matched exactly for the
result to be added to the list

=item * C<scheme> (optional)

'opf:scheme' or 'scheme' attribute that must be
matched exactly for the result to be added to the list

=item * C<event> (optional)

'opf:event' or 'event' attribute that must be matched exactly for the
result to be added to the list

=back

If more than one of the arguments C<id>, C<scheme>, or C<event> are
specified a value is added to the list if it matches any one (i.e. the
logic is OR).

=cut

sub element_list :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my %valid_args = (
        'cond' => 1,
        'id' => 1,
        'scheme' => 1,
        );
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }
    unless($args{cond})
    {
        $self->add_error($subname,"(): no search condition specified");
        return;
    }

    my @elements = $self->{twigroot}->descendants($args{cond});
    my @list = ();
    my $id;
    my $scheme;
    foreach my $el (@elements)
    {
        if($args{id})
        {
            $id = $el->att('id') || '';
            if($id eq $args{id})
            {
                push(@list,$el->text);
                next;
            }
        }
        if($args{event})
        {
            $scheme = $el->att('opf:event') || $el->att('event') || '';
            if($scheme eq $args{event})
            {
                push(@list,$el->text);
                next;
            }
        }
        if($args{scheme})
        {
            $scheme = $el->att('opf:scheme') || $el->att('scheme') || '';
            if($scheme eq $args{scheme})
            {
                push(@list,$el->text);
                next;
            }
        }
        next if($args{id} || $args{event} || $args{scheme});
        push(@list,$el->text);
    }
    return unless(@list);
    if(wantarray) { return @list; }
    else { return $list[0]; }
}


=head2 C<errors()>

Returns an arrayref containing any generated error messages.

=cut

sub errors :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    return $self->{errors};
}


=head2 C<identifier()>

Returns the text of the dc:identifier element pointed to by the
'unique-identifier' attribute of the root 'package' element, or undef
if it could not be located.

=cut

sub identifier :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck;

    my $identid = $self->{twigroot}->att('unique-identifier');
    return unless($identid);

    my $identifier = $self->{twig}->first_elt("*[\@id='$identid']");
    return unless($identifier);

    my $idtext = $identifier->text;
    return unless($idtext);

    return($idtext);
}


=head2 C<isbn_list(%args)>

Returns a list of all ISBNs matching the specified attributes.  See
L</twigelt_is_isbn()> for a detailed description of how the ISBN
elements are found.

Returns undef if no matches are found.

In scalar context returns the first match, not the last.

See also L</isbns(%args)>.

=head3 Arguments

=over

=item * C<id> (optional)

'id' attribute that must be matched exactly for the
result to be added to the list

=item * C<scheme> (optional)

'opf:scheme' or 'scheme' attribute that must be
matched exactly for the result to be added to the list

=back

If both arguments are specified a value is added to the list if it
matches either one (i.e. the logic is OR).

=cut

sub isbn_list :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my %valid_args = (
        'id' => 1,
        'scheme' => 1,
        );
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }

    my @list = $self->element_list(cond => \&twigelt_is_isbn,
                                   %args);
    return unless(@list);
    if(wantarray) { return @list; }
    else { return $list[0]; }
}


=head2 C<isbns(%args)>

Returns all of the ISBN identifiers matching the specificied
attributes as a list of hashrefs, with one hash per ISBN identifier
presented in the order that the identifiers are found.  The hash keys
are 'id' (containing the value of the 'id' attribute), 'scheme'
(containing the value of either the 'opf:scheme' or 'scheme'
attribute, whichever is found first), and 'isbn' (containing the text
of the element).

If no entries are found, returns undef.

In scalar context returns the first match, not the last.

See also L</isbn_list(%args)>.

=head3 Arguments

C<isbns()> takes two optional named arguments:

=over

=item * C<id> - 'id' attribute that must be matched exactly for the
result to be added to the list

=item * C<scheme> - 'opf:scheme' or 'scheme' attribute that must be
matched exactly for the result to be added to the list

=back

If both arguments are specified a value is added to the list if it
matches either one (i.e. the logic is OR).

=cut

sub isbns :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my %valid_args = (
        'id' => 1,
        'scheme' => 1,
        );
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }

    my @elements = $self->{twigroot}->descendants(\&twigelt_is_isbn);
    my @list = ();
    my $id;
    my $scheme;
    foreach my $el (@elements)
    {
        if($args{id})
        {
            $id = $el->att('id') || '';
            if($id eq $args{id})
            {
                push(@list,
                     {
                         'isbn' => $el->text,
                         'id'   => $el->att('id'),
                         'scheme'   => $el->att('scheme'),
                     });
                next;
            }
        }
        if($args{scheme})
        {
            $scheme = $el->att('opf:scheme') || $el->att('scheme') || '';
            if($scheme eq $args{scheme})
            {
                push(@list,
                     {
                         'isbn' => $el->text,
                         'id'   => $el->att('id'),
                         'scheme'   => $el->att('scheme'),
                     });
                next;
            }
        }
        next if($args{id} || $args{scheme});
        $scheme = $el->att('opf:scheme') || $el->att('scheme');
        push(@list,
             {
                 'isbn'   => $el->text,
                 'id'     => $el->att('id'),
                 'scheme' => $scheme,
             });
    }
    return unless(@list);
    if(wantarray) { return @list; }
    else { return $list[0]; }
}


=head2 C<languages()>

Returns a list containing the text of all dc:language
(case-insensitive) entries, or undef if none are found.

In scalar context returns the first match, not the last.

=cut

sub languages :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck;

    my @retval = ();
    my @elements = $self->{twigroot}->descendants(qr/^dc:language$/ix);
    foreach my $el (@elements)
    {
        push(@retval,$el->text) if($el->text);
    }
    return unless(@retval);
    if(wantarray) { return @retval; }
    else { return $retval[0]; }
}


=head2 C<manifest(%args)>

Returns all of the items in the manifest as a list of hashrefs, with
one hash per manifest item in the order that they appear, where the
hash keys are 'id', 'href', and 'media-type', each returning the
appropriate attribute, if any.

In scalar context, returns the first match, not the last.

=head3 Arguments

C<manifest()> takes four optional named arguments:

=over

=item * C<id> - 'id' attribute to match

=item * C<href> - 'href' attribute to match

=item * C<mtype> - 'media-type' attribute to match

=item * C<logic> - logic to use (valid values are 'and' or 'or', default: 'and')

=back

If any of the named arguments are specified, C<manifest()> will return
only items matching the specified criteria.  This is an exact
case-sensitive match, but it can (especially in the case of mtype)
still return multiple elements.

=head3 Return values

Returns undef if there is no <manifest> element directly underneath
<package>, or if <manifest> contains no items.

=head3 See also

L</manifest_hrefs()>, L</spine()>

=head3 Example

 @manifest = $ebook->manifest(id => 'ncx',
                              mtype => 'text/xml',
                              logic => 'or');

=cut

sub manifest :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my %valid_args = (
        'id' => 1,
        'href' => 1,
        'mtype' => 1,
        'logic' => 1
        );
    my %valid_logic = (
        'and' => 1,
        'or' => 1
        );
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }
    if($args{logic})
    {
        croak($subname,
              "(): logic must be 'and' or 'or' (got '",$args{logic},"')")
            if(!$valid_logic{$args{logic}});
    }
    else { $args{logic} = 'and'; }

    debug(1,"DEBUG: manifest() called with '",join(" ",keys(%args)),"'");

    my @elements;
    my @retarray;
    my $cond;

    if($args{id})
    {
        debug(1,"DEBUG: manifest searching on id");
        $cond = "item[\@id='$args{id}'";
    }
    if($args{href})
    {
        debug(1,"DEBUG: manifest searching on href");
        if($cond) { $cond .= " $args{logic} \@href='$args{href}'"; }
        else { $cond = "item[\@href='$args{href}'"; }
    }
    if($args{mtype})
    {
        debug(1,"DEBUG: manifest searching on mtype");
        if($cond) { $cond .= " $args{logic} \@media-type='$args{mtype}'"; }
        else { $cond = "item[\@media-type='$args{mtype}'"; }
    }
    if($cond) { $cond .= "]"; }
    else { $cond = "item"; }

    my $manifest = $self->{twigroot}->first_child('manifest');
    return unless($manifest);

    debug(1,"DEBUG: manifest search condition = '",$cond,"'");
    @elements = $manifest->children($cond);
    return unless(@elements);

    foreach my $el (@elements)
    {
        push(@retarray,
             {
                 'id' => $el->id,
                 'href' => $el->att('href'),
                 'media-type' => $el->att('media-type')
             });
    }
    if(wantarray) { return @retarray; }
    else { return $retarray[0]; }
}


=head2 C<manifest_hrefs()>

Returns a list of all of the hrefs in the current OPF manifest, or the
empty list if none are found.

In scalar context returns the first href, not the last.

See also: C<manifest()>, C<spine_idrefs()>

=cut

sub manifest_hrefs :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    my @items;
    my $href;
    my $manifest;
    my @retval = ();

    $manifest = $self->{twigroot}->first_child('manifest');
    if(! $manifest) { return @retval; }

    @items = $manifest->descendants('item');
    foreach my $item (@items)
    {
	$href = $item->att('href');
        debug(3,"DEBUG: '",$href,"' has mime-type '",mimetype($href),"'")
            if($href);
	push(@retval,$href) if($href);
    }
    debug(2,"DEBUG[/",$subname,"]");
    if(wantarray) { return @retval; }
    else { return $retval[0]; }
}


=head2 C<opffile()>

Returns the name of the file where the OPF metadata will be stored or
undef if no value is found..

=cut

sub opffile :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    return unless($self->{opffile});
    return $self->{opffile};
}


=head2 C<primary_author()>

Finds the primary author of the book, defined as the first
'dc:creator' entry (case-insensitive) where either the attribute
opf:role="aut" or role="aut", or the first 'dc:creator' entry if no
entries with either attribute can be found.  Entries must actually
have text to be considered.

In list context, returns a two-item list, the first of which is the
text of the entry (the author name), and the second element of which
is the value of the 'opf:file-as' or 'file-as' attribute (where
'opf:file-as' is given precedence if both are present).

In scalar context, returns the text of the entry (the author name).

If no entries are found, returns undef.

Uses L</twigelt_is_author()> in the first half of the search.

=head3 Example

 my ($fileas, $author) = $ebook->primary_author;
 my $author = $ebook->primary_author;

=cut

sub primary_author :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");

    my $twigroot = $self->{twigroot};
    my $element;
    my $fileas;

    $element = $twigroot->first_descendant(\&twigelt_is_author);
    $element = $twigroot->first_descendant(qr/dc:creator/ix) if(!$element);
    carp("##DEBUG: primary_author not found") unless($element->text);
    return unless($element);
    return unless($element->text);
    $fileas = $element->att('opf:file-as');
    $fileas = $element->att('file-as') unless($fileas);
    if(wantarray) { return ($element->text, $fileas); }
    else { return $element->text; }
}


=head2 C<print_errors()>

Prints the current list of errors to STDERR.

=cut

sub print_errors :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");

    my $errorref = $self->{errors};

    if(!$self->errors)
    {
	debug(1,"DEBUG: no errors found!");
	return 1;
    }


    foreach my $error (@$errorref)
    {
	print "ERROR: ",$error,"\n";
    }
    return 1;
}


=head2 C<print_warnings()>

Prints the current list of warnings to STDERR.

=cut

sub print_warnings :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");

    my $warningref = $self->{warnings};

    if(!$self->warnings)
    {
	debug(2,"DEBUG: no warnings found!");
	return 1;
    }


    foreach my $warning (@$warningref)
    {
	print "WARNING: ",$warning,"\n";
    }
    return 1;
}


=head2 C<print_opf()>

Prints the OPF file to the default filehandle

=cut

sub print_opf :method
{
    my $self = shift;
    my $filehandle = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");

    if(defined $filehandle) { $self->{twig}->print($filehandle); }
    else { $self->{twig}->print; }
    return 1;
}


=head2 C<publishers()>

Returns a list containing the text of all dc:publisher
(case-insensitive) entries, or undef if none are found.

In scalar context returns the first match, not the last.

=cut

sub publishers :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck;

    my @pubs = ();
    my @elements = $self->{twigroot}->descendants(qr/^dc:publisher$/ix);
    foreach my $el (@elements)
    {
        push(@pubs,$el->text) if($el->text);
    }
    return unless(@pubs);
    if(wantarray) { return @pubs; }
    else { return $pubs[0]; }
}


=head2 C<retailprice()>

Returns a two-scalar list, the first scalar being the text of the
Mobipocket-specific <SRP> element, if it exists, and the second being
the 'Currency' attribute of that element, if it exists.

In scalar context, returns just the text (price).

Returns undef if the SRP element is not found.

=cut

sub retailprice :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck;

    my $twigroot = $self->{twigroot};

    my $element = $twigroot->first_descendant(qr/^ SRP $/ix);
    return unless($element);
    if(wantarray) { return ($element->text,$element->att('Currency')); }
    else { return $element->text };
}


=head2 C<review()>

Returns the text of the Mobipocket-specific <Review> element, if it
exists.  Returns undef if one is not found.

=cut

sub review :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck;

    my $twigroot = $self->{twigroot};

    my $element = $twigroot->first_descendant(qr/^review$/ix);
    return unless($element);
    return $element->text;
}


=head2 C<rights('id' => 'identifier')>

Returns a list containing the text of all of dc:rights or
dc:copyrights (case-insensitive) entries in the e-book, or undef if
none are found.

In scalar context returns the first match, not the last.

If the optional named argument 'id' is specified, it will only return
entries where the id attribute matches the specified identifier.
Although this still returns a list, if more than one entry is found, a
warning is logged.

Note that dc:copyrights is not a valid Dublin Core element -- it is
included only because some broken Mobipocket books use it.

=cut

sub rights :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck;

    my %valid_args = (
        'id' => 1,
        );
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }


    my @rights = ();
    my $id = $args{id};
    my @elements = $self->{twigroot}->descendants(qr/^dc:(copy)?rights$/ix);

    foreach my $element (@elements)
    {
        if($id)
        {
            next if($element->att('id') ne $id);
            push @rights,$element->text if($element->text);
        }
        else { push @rights,$element->text if($element->text); }
    }

    if($id)
    {
        add_warning($subname
                     . "(): More than one rights entry found with id '"
                     . $id ."'" )
            if(scalar(@rights) > 1);
    }
    return unless(@rights);
    if(wantarray) { return @rights; }
    else { return $rights[0]; }
}


=head2 C<search_knownuids()>

Searches the OPF twig for the first dc:identifier (case-insensitive)
element with an ID matching known UID IDs.

Returns the ID if a match is found, undef otherwise

=cut

sub search_knownuids :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");

    my @elements;

    @elements = $self->{twigroot}->descendants(\&twigelt_is_knownuid);
    return unless(@elements);
    debug(1,"DEBUG: found known UID '",$elements[0]->id,"'");
    return $elements[0]->id;
}


=head2 C<search_knownuidschemes()>

Searches descendants of the OPF twig element for the first
<dc:identifier> or <dc:Identifier> subelement with the attribute
'scheme' or 'opf:scheme' matching a known list of schemes for unique
IDs

NOTE: this is NOT a case-insensitive search!  If you have to deal with
really bizarre input, make sure that you run L</fix_oeb12()> or
L</fix_opf20()> before calling L</fix_packageid()> or L</fix_misc()>.

Returns the ID if a match is found, undef otherwise.

=cut

sub search_knownuidschemes :method   ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my ($gi) = @_;
    if(!$gi) { $gi = 'dc:identifier'; }
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck;

    my $topelement = $self->{twigroot};

    my @knownuidschemes = (
        'GUID',
	'UUID',
	'FWID',
	);

    # Creating a regexp to search on works, but doesn't let you
    # specify priority.  For that, you really do have to loop.
#    my $schemeregexp = "(" . join('|',@knownuidschemes) . ")";

    my @elems;
    my $id;

    my $retval = undef;

    foreach my $scheme (@knownuidschemes)
    {
	debug(2,"DEBUG: searching for scheme='",$scheme,"'");
	@elems = $topelement->descendants(
            "dc:identifier[\@opf:scheme=~/$scheme/ix or \@scheme=~/$scheme/ix]"
            );
        push @elems, $topelement->descendants(
            "dc:Identifier[\@opf:scheme=~/$scheme/ix or \@scheme=~/$scheme/ix]"
            );
	foreach my $elem (@elems)
	{
	    debug(2,"DEBUG: working on scheme '",$scheme,"'");
	    if(defined $elem)
	    {
		if($scheme eq 'FWID')
		{
		    # Fictionwise has a screwy output that sets the ID
		    # equal to the text.  Fix the ID to just be 'FWID'
		    debug(1,"DEBUG: fixing FWID");
		    $elem->set_id('FWID');
		}

		$id = $elem->id;
                unless(defined $id)
                {
		    debug(1,"DEBUG: assigning ID from scheme '",$scheme,"'");
		    $id = uc($scheme);
		    $elem->set_id($id);
                }
                $retval = $id;
		debug(1,"DEBUG: found Package ID: ",$id);
		last;
	    } # if(defined $elem)
	} # foreach my $elem (@elems)
	last if(defined $retval);
    }
    debug(2,"[/",$subname,"]");
    return $retval;
}


=head2 C<spec()>

Returns the version of the OEB specification currently in use.  Valid
values are C<OEB12> and C<OPF20>.  This value will default to undef
until C<fix_oeb12> or C<fix_opf20> is called, as there is no way for
the object to know what specification is being conformed to (if any)
until it attempts to enforce it.

=cut

sub spec :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    return $self->{spec};
}


=head2 C<spine()>

Returns all of the manifest items referenced in the spine as a list of
hashrefs, with one hash per manifest item in the order that they
appear, where the hash keys are 'id', 'href', and 'media-type', each
returning the appropriate attribute, if any.

In scalar context, returns the first item, not the last.

Returns undef if there is no <spine> element directly underneath
<package>, or if <spine> contains no itemrefs.  If <spine> exists, but
<manifest> does not, or a spine itemref exists but points an ID not
found in the manifest, spine() logs an error and returns undef.

See also: L</spine_idrefs()>, L</manifest()>

=cut

sub spine :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    my $spine = $self->{twigroot}->first_child('spine');
    return unless($spine);
    my @spinerefs;
    my $idref;
    my $element;
    my @retarray;

    my $manifest = $self->{twigroot}->first_child('manifest');
    if(!$manifest)
    {
        $self->add_error(
            $subname . "(): <spine> found without <manifest>"
            );
        debug(1,"DEBUG: <spine> found without <manifest>!");
        return;
    }

    @spinerefs = $spine->children('itemref');
    return unless(@spinerefs);

    foreach my $spineref (@spinerefs)
    {
        $idref = $spineref->att('idref');
        if(!$idref)
        {
            $self->add_warning(
                $subname . "(): <itemref> found with no idref -- skipping"
                );
            debug(1,"DEBUG: <itemref> found with no idref -- skipping");
            next;
        }
        $element = $manifest->first_child("item[\@id='$idref']");
        if(!$element)
        {
            $self->add_error(
                $subname ."(): id '" . $idref . "' not found in manifest!"
                );
            debug(1,"DEBUG: id '",$idref," not found in manifest!");
            return;
        }
        push(@retarray,
             {
                 'id' => $element->id,
                 'href' => $element->att('href'),
                 'media-type' => $element->att('media-type')
             });
    }
    if(wantarray) { return @retarray; }
    else { return $retarray[0]; }
}


=head2 C<spine_idrefs()>

Returns a list of all of the idrefs in the current OPF spine, or the
empty list if none are found.

In scalar context, returns the first idref, not the last.

See also: L</spine()>, L</manifest_hrefs()>

=cut

sub spine_idrefs :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    my $spine = $self->{twigroot}->first_child('spine');;
    my @retval = ();
    my @itemrefs;
    my $idref;

    if(! $spine) { return @retval; }

    @itemrefs = $spine->children('itemref');
    foreach my $item (@itemrefs)
    {
	$idref = $item->att('idref');
	push(@retval,$idref) if($idref);
    }
    if(wantarray) { return @retval; }
    else { return $retval[0]; }
}


=head2 C<subject_list()>

Returns a list containing the text of all dc:subject elements or undef
if none are found.

In scalar context, returns the first subject, not the last.

=cut

sub subject_list :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck;

    my @retval = ();
    my $twigroot = $self->{twigroot};

    my @subjects = $twigroot->descendants(qr/dc:subject/ix);
    return unless(@subjects);

    foreach my $subject (@subjects)
    {
        push(@retval,$subject->text) if($subject->text);
    }
    return unless(@retval);
    if(wantarray) { return @retval; }
    else { return $retval[0]; }
}


=head2 C<title()>

Returns the title of the e-book, or undef if no dc:title element
(case-insensitive) exists.  If a dc:title element exists, but contains
no text, returns an empty string.

=cut

sub title :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck;

    my $twigroot = $self->{twigroot};

    my $element = $twigroot->first_descendant(qr/^dc:title$/ix);
    return unless($element);
    return ($element->text || '');
}


=head2 C<twig()>

Returns the raw L<XML::Twig> object used to store the OPF metadata.

Although this twig can be manipulated via the standard XML::Twig
methods, doing so requires caution and is not recommended.  In
particular, changing the root element from here will cause the
EBook::Tools internal twig and twigroot attributes to become unlinked
and the result of any subsequent action is not defined.

=cut

sub twig :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    return $self->{twig};
}


=head2 C<twigcheck()>

Croaks showing the calling location unless C<$self> has both a twig and a
twigroot, and the twigroot is <package>.  Used as a sanity check for
methods that use twig or twigroot.

=cut

sub twigcheck :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(3,"DEBUG[",$subname,"]");

    my @calledfrom = caller(1);
    croak("twigcheck called from unknown location") if(!@calledfrom);

    croak($calledfrom[3],"(): undefined twig")
        if(!$self->{twig});
    croak($calledfrom[3],"(): twig isn't a XML::Twig")
        if( (ref $self->{twig}) ne 'XML::Twig' );
    croak($calledfrom[3],"(): twig root missing")
        if(!$self->{twigroot});
    croak($calledfrom[3],"(): twig root isn't a XML::Twig::Elt")
        if( (ref $self->{twigroot}) ne 'XML::Twig::Elt' );
    croak($calledfrom[3],"(): twig root is '" . $self->{twigroot}->gi
          . "' (needs to be 'package')")
        if($self->{twigroot}->gi ne 'package');
    debug(3,"DEBUG[/",$subname,"]");
    return 1;
}


=head2 C<twigroot()>

Returns the raw L<XML::Twig> root element used to store the OPF
metadata.

This twig element can be manipulated via the standard XML::Twig::Elt
methods, but care should be taken not to attempt to cut this element
from its twig as doing so will cause the EBook::Tools internal twig
and twigroot attributes to become unlinked and the result of any
subsequent action is not defined.

=cut

sub twigroot :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    return $self->{twigroot};
}


=head2 C<warnings()>

Returns an arrayref containing any generated warning messages.

=cut

sub warnings :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    return $self->{warnings};
}


######################################
########## MODIFIER METHODS ##########
######################################

=head1 MODIFIER METHODS

Unless otherwise specified, all modifier methods return undef if an
error was added to the error list, and true otherwise (even if a
warning was added to the warning list).


=head2 C<add_document($href,$id,$mediatype)>

Adds a document to the OPF manifest and spine, creating <manifest> and
<spine> if necessary.  To add an item only to the OPF manifest, see
add_item().

=head3 Arguments

=over

=item C<$href>

The href to the document in question.  Usually, this is just a
filename (or relative path and filename) of a file in the current
working directory.  If you are planning to eventually generate a .epub
book, all hrefs MUST be in or below the current working directory.

The method returns undef if $href is not defined or empty.

=item C<$id>

The XML ID to use.  If not specified, defaults to the href with
invalid characters removed.

This must be unique not only to the manifest list, but to every
element in the OPF file.  If a duplicate ID exists, the method sets an
error and returns undef.

=item C<$mediatype> (optional)

The mime type of the document.  If not specified, will attempt to
autodetect the mime type, and if that fails, will default to
'application/xhtml+xml'.

=back

=cut

sub add_document :method   ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my ($href,$id,$mediatype) = @_;
    my $subname = (caller(0))[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    $href = trim($href);
    return unless($href);

    my $twig = $self->{twig};
    my $topelement = $self->{twigroot};
    my $element;

    $id = $href unless($id);
    $id =~ s/[^\w.-]//gx; # Delete all nonvalid XML 1.0 namechars
    $id =~ s/^[.\d -]+//gx; # Delete all nonvalid XML 1.0 namestartchars

    $element = $twig->first_elt("*[\@id='$id']");
    if($element)
    {
        $self->add_error(
            $subname . "(): ID '" . $id . "' already exists"
            . " (in a '" . $element->gi ."' tag)"
            );
        return;
    }

    if(!$mediatype)
    {
	my $mimetype = mimetype($href);
	if($mimetype) { $mediatype = $mimetype; }
	else { $mediatype = "application/xhtml+xml"; }
	debug(2,"DEBUG: '",$href,"' has mimetype '",$mimetype,"'");
    }

    my $manifest = $topelement->first_child('manifest');
    $manifest = $topelement->insert_new_elt('last_child','manifest')
        if(!$manifest);
    my $spine = $topelement->first_child('spine');
    $spine = $topelement->insert_new_elt('last_child','spine')
        if(!$spine);

    my $item = $manifest->insert_new_elt('last_child','item');
    $item->set_id($id);
    $item->set_att(
	'href' => $href,
	'media-type' => $mediatype
	);

    my $itemref = $spine->insert_new_elt('last_child','itemref');
    $itemref->set_att('idref' => $id);

    return 1;
}


=head2 C<add_error(@errors)>

Adds @errors to the list of object errors.  Each member of
@errors should be a string containing the entire text of the
error, with no ending newline.

SEE ALSO: L</add_warning()>, L</clear_errors()>, L</clear_warnerr()>

=cut

sub add_error :method   ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (@newerror) = @_;
    my $subname = (caller(0))[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(3,"DEBUG[",$subname,"]");

    my $currenterrors;
    $currenterrors = $self->{errors} if($self->{errors});

    if(@newerror)
    {
        my $error = join('',@newerror);
	debug(1,"ERROR: ",$error);
	push(@$currenterrors,$error);
    }
    $self->{errors} = $currenterrors;
    return 1;
}


=head2 C<add_identifier(%args)>

Creates a new dc:identifier element containing the specified text, id,
and scheme.

If a <dc-metadata> element exists underneath <metadata>, the
identifier element will be created underneath the <dc-metadata> in OEB
1.2 format, otherwise the title element is created underneath
<metadata> in OPF 2.0 format.

Returns the twig element containing the new identifier.

=head3 Arguments

C<add_identifier()> takes three named arguments, one mandatory, two
optional.

=over

=item * C<text> - the text of the identifier.  This is mandatory, and
the method croaks if it is not present.

=item * C<scheme> - 'opf:scheme' or 'scheme' attribute to be added (optional)

=item * C<id> - 'id' attribute to be added.  If this is specified, and
the id is already in use, a warning will be added but the method will
continue, removing the id attribute from the element that previously
contained it.

=back

=cut

sub add_identifier :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my %valid_args = (
        'text' => 1,
        'id' => 1,
        'scheme' => 1,
        );
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }
    croak($subname,"(): identifier text not specified")
        unless($args{text});

    $self->fix_metastructure_basic();
    my $meta = $self->{twigroot}->first_child('metadata');
    my $dcmeta = $meta->first_child('dc-metadata');
    my $element;
    my $idelem;
    my $newid = $args{id};
    $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);

    if($dcmeta)
    {
        $element = $dcmeta->insert_new_elt('last_child','dc:Identifier');
        $element->set_att('scheme' => $args{scheme}) if($args{scheme});
    }
    else
    {
        $element = $meta->insert_new_elt('last_child','dc:identifier');
        $element->set_att('opf:scheme' => $args{scheme}) if($args{scheme});
    }
    $element->set_text($args{text});

    if($idelem && $idelem->cmp($element) )
    {
        $self->add_warning(
            $subname,"(): reassigning id '",$newid,
            "' from a '",$idelem->gi,"' element!"
            );
        $idelem->del_att('id');
    }
    $element->set_att('id' => $newid) if($newid);

    return $element;
}


=head2 C<add_item($href,$id,$mediatype)>

Adds a document to the OPF manifest (but not spine), creating
<manifest> if necessary.  To add an item only to both the OPF manifest
and spine, see add_document().

=head3 Arguments

=over

=item C<$href>

The href to the document in question.  Usually, this is just a
filename (or relative path and filename) of a file in the current
working directory.  If you are planning to eventually generate a .epub
book, all hrefs MUST be in or below the current working directory.

=item C<$id>

The XML ID to use.  If not specified, defaults to the href with all
nonword characters removed.

This must be unique not only to the manifest list, but to every
element in the OPF file.  If a duplicate ID exists, the method sets an
error and returns undef.

=item C<$mediatype> (optional)

The mime type of the document.  If not specified, will attempt to
autodetect the mime type, and if that fails, will set an error and
return undef.

=back

=cut

sub add_item :method   ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my ($href,$id,$mediatype) = @_;
    my $subname = (caller(0))[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    $href = trim($href);
    return unless($href);

    my $twig = $self->{twig};
    my $topelement = $self->{twigroot};
    my $element;

    $id = $href unless($id);
    $id =~ s/[^\w.-]//gx; # Delete all nonvalid XML 1.0 namechars
    $id =~ s/^[.\d -]+//gx; # Delete all nonvalid XML 1.0 namestartchars

    $element = $twig->first_elt("*[\@id='$id']");
    if($element)
    {
        $self->add_error(
            $subname . "(): ID '" . $id . "' already exists"
            . " (in a '" . $element->gi ."' tag)"
            );
        debug(2,"DEBUG[/",$subname,"]");
        return;
    }

    if(!$mediatype)
    {
	my $mimetype = mimetype($href);
	if($mimetype) { $mediatype = $mimetype; }
	else { $mediatype = "application/xhtml+xml"; }
	debug(2,"DEBUG: '",$href,"' has mimetype '",$mediatype,"'");
    }

    my $manifest = $self->{twigroot}->first_child('manifest');
    $manifest = $topelement->insert_new_elt('last_child','manifest')
        if(!$manifest);

    debug(2,"DEBUG: adding item '",$id,"': '",$href,"'");
    my $item = $manifest->insert_new_elt('last_child','item');
    $item->set_id($id);
    $item->set_att(
	'href' => $href,
	'media-type' => $mediatype
	);

    debug(2,"DEBUG[/",$subname,"]");
    return 1;
}


=head2 add_metadata(%args)

Creates a metadata element with the specified text, attributes, and parent.

If a <dc-metadata> element exists underneath <metadata>, the language
element will be created underneath the <dc-metadata> and any standard
attributes will be created in OEB 1.2 format, otherwise the element is
created underneath <metadata> in OPF 2.0 format.

Returns 1 on success, returns undef if no gi or if no text was specified.

=cut

=head3 Arguments

=over

=item C<gi>

The generic identifier (tag) of the metadata element to alter or
create.  If not specified, the method sets an error and returns undef.

=item C<parent>

The generic identifier (tag) of the parent to use for any newly
created element.  If not specified, defaults to 'dc-metadata' if
'dc-metadata' exists underneath 'metadata', and 'metadata' otherwise.

A newly created element will be created under the first element found
with this gi.  A modified element will be moved under the first
element found with this gi.

Newly created elements will use OPF 2.0 attribute names if the parent
is 'metadata' and OEB 1.2 attribute names otherwise.

=item C<text>

This specifies the element text to set.  If not specified, the method
sets an error and returns undef.

=item C<id> (optional)

This specifies the ID to set on the element.  If set and the ID is
already in use, a warning is logged and the ID is removed from the
other location and assigned to the element.

=item C<fileas> (optional)

This specifies the file-as attribute to set on the element.

=item C<role> (optional)

This specifies the role attribute to set on the element.

=item C<scheme> (optional)

This specifies the scheme attribute to set on the element.

=back

=head3 Example

 $retval = $ebook->add_metadata(gi => 'AuthorNonstandard',
                                text => 'Element Text',
                                id => 'customid',
                                fileas => 'Text, Element',
                                role => 'xxx',
                                scheme => 'code');

=cut

sub add_metadata :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(3,"DEBUG[",$subname,"]");
    my %valid_args = (
        'gi' => 1,
        'parent' => 1,
        'text' => 1,
        'id' => 1,
        'fileas' => 1,
        'role' => 1,
        'scheme' => 1,
        );
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }

    my $gi = $args{gi};
    unless($gi)
    {
        $self->add_error($subname,"(): no gi specified");
        return;
    }

    my $text = $args{text};
    unless($text)
    {
        $self->add_error($subname,"(): no text specified");
        return;
    }

    my $newid = $args{id};
    my $idelem;
    my $element;
    my $meta;
    my $dcmeta;
    my $parent;
    my %dcatts;

    $self->fix_metastructure_basic();
    $parent =  $self->{twigroot}->first_descendant(qr/^ $args{parent} $/ix)
        if($args{parent});
    $meta = $self->{twigroot}->first_child('metadata');
    $dcmeta = $meta->first_child('dc-metadata');
    $parent = $parent || $dcmeta || $meta;
    if($parent->gi eq 'metadata')
    {
        %dcatts = (
            'file-as' => 'opf:file-as',
            'role' => 'opf:role',
            'scheme' => 'opf:scheme',
            );
    }
    else
    {
        %dcatts = (
            'file-as' => 'file-as',
            'role' => 'role',
            'scheme' => 'scheme'
        );
    }

    debug(2,"DEBUG: creating '",$gi,"' under <",$parent->gi,">");
    $element = $parent->insert_new_elt('last_child',$gi);
    $element->set_att($dcatts{'file-as'},$args{fileas})
        if($args{fileas});
    $element->set_att($dcatts{'role'},$args{role})
        if($args{role});
    $element->set_att($dcatts{'scheme'},$args{scheme})
        if($args{scheme});
    $element->set_text($text);

    $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);
    if($idelem && $idelem->cmp($element) )
    {
        $self->add_warning(
            $subname,"(): reassigning id '",$newid,
            "' from a '",$idelem->gi,"' to a '",$element->gi,"'!"
            );
        $idelem->del_att('id');
    }
    $element->set_att('id' => $newid) if($newid);
    return 1;
}


=head2 C<add_subject(%args)>

Creates a new dc:subject element containing the specified text, code,
and id.

If a <dc-metadata> element exists underneath <metadata>, the
subject element will be created underneath the <dc-metadata> in OEB
1.2 format, otherwise the title element is created underneath
<metadata> in OPF 2.0 format.

Returns the twig element containing the new subject.

=head3 Arguments

C<add_subject()> takes four named arguments, one mandatory, three
optional.

=over

=item * C<text> - the text of the subject.  This is mandatory, and
the method croaks if it is not present.

=item * C<scheme> (optional) - 'opf:scheme' or 'scheme' attribute to
be added.  Be warned that neither the OEB 1.2 nor the OPF 2.0
specifications allow a scheme to be added to this element, so if this
is specified, the resulting OPF file will fail to validate against
either standard.

=item * C<basiccode> (optional) - 'BASICCode' attribute to be added.
Be warned that this is a Mobipocket-specific attribute that does not
exist in either the OEB 1.2 nor the OPF 2.0 specifications, so if this
is specified, the resulting OPF file will fail to validate against
either standard.

=item * C<id> (optional) - 'id' attribute to be added.  If this is
specified, and the id is already in use, a warning will be added but
the method will continue, removing the id attribute from the element
that previously contained it.

=back

=cut

sub add_subject :method     ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my %valid_args = (
        'text' => 1,
        'id' => 1,
        'scheme' => 1,
        'basiccode' => 1,
        );
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }
    croak($subname,"(): subject text not specified")
        unless($args{text});

    $self->fix_metastructure_basic();
    my $meta = $self->{twigroot}->first_child('metadata');
    my $dcmeta = $meta->first_child('dc-metadata');
    my $element;
    my $idelem;
    my $newid = $args{id};
    $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);

    if($dcmeta)
    {
        $element = $dcmeta->insert_new_elt('last_child','dc:Subject');
        $element->set_att('scheme' => $args{scheme}) if($args{scheme});
    }
    else
    {
        $element = $meta->insert_new_elt('last_child','dc:subject');
        $element->set_att('opf:scheme' => $args{scheme}) if($args{scheme});
    }
    $element->set_text($args{text});
    $element->set_att('BASICCode' => $args{basiccode}) if($args{basiccode});

    if($idelem && $idelem->cmp($element) )
    {
        $self->add_warning(
            $subname,"(): reassigning id '",$newid,
            "' from a '",$idelem->gi,"' element!"
            );
        $idelem->del_att('id');
    }
    $element->set_att('id' => $newid) if($newid);

    return $element;
}


=head2 C<add_warning(@newwarning)>

Joins @newwarning to a single string and adds it to the list of object
warnings.  The warning should not end with a newline newline.

SEE ALSO: L</add_error()>, L</clear_warnings()>, L</clear_warnerr()>

=cut

sub add_warning :method   ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (@newwarning) = @_;
    my $subname = (caller(0))[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(3,"DEBUG[",$subname,"]");

    my @currentwarnings;
    @currentwarnings = @{$self->{warnings}} if($self->{warnings});

    if(@newwarning)
    {
        my $warning = join('',@newwarning);
	debug(1,"WARNING: ",$warning);
	push(@currentwarnings,$warning);
    }
    $self->{warnings} = \@currentwarnings;

    debug(3,"DEBUG[/",$subname,"]");
    return 1;
}


=head2 C<clear_errors()>

Clear the current list of errors

=cut

sub clear_errors :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");

    $self->{errors} = ();
    return 1;
}


=head2 C<clear_warnerr()>

Clear both the error and warning lists

=cut

sub clear_warnerr :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");

    $self->{errors} = ();
    $self->{warnings} = ();
    return 1;
}


=head2 C<clear_warnings()>

Clear the current list of warnings

=cut

sub clear_warnings :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");

    $self->{warnings} = ();
    return 1;
}


=head2 C<delete_meta_filepos()>

Deletes metadata elements with the attribute 'filepos' underneath
the given parent element

These are secondary metadata elements included in the output from
mobi2html may that are not used.

=cut

sub delete_meta_filepos :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    my @elements = $self->{twigroot}->descendants('metadata[@filepos]');
    foreach my $el (@elements)
    {
	$el->delete;
    }
    return 1;
}


=head2 C<fix_dates()>

Standardizes all <dc:date> elements via fix_datestring().  Adds a
warning to the object for each date that could not be fixed.

Called from L</fix_misc()>.

=cut

sub fix_dates :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    my @dates;
    my $newdate;

    @dates = $self->{twigroot}->descendants('dc:date');
    push(@dates,$self->{twigroot}->descendants('dc:Date'));

    foreach my $dcdate (@dates)
    {
	if(!$dcdate->text)
	{
	    $self->add_warning(
                "WARNING: found dc:date with no value -- skipping");
	}
	else
	{
	    $newdate = fix_datestring($dcdate->text);
	    if(!$newdate)
	    {
		$self->add_warning(
		    sprintf("fixmisc(): can't deal with date '%s' -- skipping",
                            $dcdate->text)
		    );
	    }
	    elsif($dcdate->text ne $newdate)
	    {
		debug(2,"DEBUG: setting date from '",$dcdate->text,
                      "' to '",$newdate,"'");
		$dcdate->set_text($newdate);
	    }
	}
    }
    return 1;
}


=head2 C<fix_guide()>

Fixes problems related to the OPF guide elements, specifically:

=over

=item * Deletes empty guide elements

=item * Moves all reference elements directly underneath the guide element

=item * Finds reference elements with a href with only an anchor
portion and assigns them to the first spine href.  This only works if
the spine is in working condition, so it may be wise to run
L</fix_spine()> before C<fix_guide()> if the input is expected to be
very badly broken.

=back

Logs a warning if a reference href is found that does not appear in
the manifest.

=cut

sub fix_guide :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    my $twigroot = $self->{twigroot};
    my $guide = $twigroot->first_descendant('guide');
    my $parent;
    my $href;
    my @spine;
    my @elements = $twigroot->descendants(qr/^reference$/ix);
    if(@elements)
    {
        # If <guide> doesn't exist, create it
        unless($guide)
        {
            debug(1,"DEBUG: creating <guide>");
            $guide = $twigroot->insert_new_elt('last_child','guide');
        }

        # Make sure that the guide is a child of the twigroot,
        $parent = $guide->parent;
        if( $parent->cmp($twigroot) )
        {
            debug(1,"DEBUG: moving <guide>");
            $guide->move('last_child',$twigroot);
        }

        foreach my $el (@elements)
        {
            $href = $el->att('href');
            if(!$href)
            {
                # No href means it is broken.
                # Leave it alone, but log a warning
                $self->add_warning(
                    "fix_guide(): <reference> with no href -- skipping");
                next;
            }
            if($href =~ /^#/)
            {
                # Anchor-only href.  Attempt to fix from the first
                # spine entry
                @spine = $self->spine;
                if(!@spine)
                {
                    $self->add_warning(
                        "fix_guide(): Cannot correct reference href '",$href,
                        "', spine is empty");
                }
                elsif(!$spine[0]->{href})
                {
                    $self->add_warning(
                        "fix_guide(): Cannot correct reference href '",$href,
                        "', cannot find href for first spine entry");
                }
                else
                {
                    debug(1,"DEBUG: correcting reference href from '",$href,
                          "' to '",$spine[0]->{href} . $href,"'");
                    $el->set_att('href',$spine[0]->{href} . $href);
                }
            }
            debug(3,"DEBUG: processing reference '",$href,"')");
            $el->move('last_child',$guide);
        } # foreach my $el (@elements)
    } # if(@elements)
    else # No elements, delete guide if it exists
    {
        $guide->delete if($guide);
    }
    return 1;
}


=head2 C<fix_languages(%args)>

Checks through the <dc:language> elements (case-insensitive) and
removes any duplicates.  If no <dc:language> elements are found, one
is created.

TODO: Also convert language names to IANA language and region codes.

=head3 Arguments

=over

=item * C<default>

The default language string to use when creating a new language
element.  If not specified, defaults to 'en'.

=back

=cut

sub fix_languages :method
{
    my $self = shift;
    my %args = @_;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    my %valid_args = (
        'default' => 1,
        );
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }

    my $twigroot = $self->{twigroot};
    my $defaultlang = $args{default} || 'en';
    my $langel;
    my @elements = $twigroot->descendants(qr/dc:language/ix);
    while($langel = shift(@elements) )
    {
        foreach my $el (@elements)
        {
            $el->delete if(twigelt_detect_duplicate($el,$langel) );
        }
    }

    @elements = $self->languages;
    if(!@elements)
    {
        $self->set_language(text => $defaultlang);
    }
    return 1;
}


=head2 C<fix_links()>

Checks through the links in the manifest and checks them for anything
they might link to, adding anything missing to the manifest.

A warning is added for every manifest item missing a href.

If no <manifest> element exists directly underneath the <package>
root, or <manifest> contains no items, the method logs a warning and
returns undef.  Otherwise, it returns 1.

=cut

sub fix_links :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    my $twigroot = $self->{twigroot};

    my $manifest = $twigroot->first_child('manifest');
    my @unchecked;

    # The %links hash points a href to one of three values:
    # * undef : the link has not been checked at all
    # * 0 : the link has been checked and is not reachable
    # * 1 : the link has been checked and exists
    my %links;
    my @newlinks;
    my $href;
    my $mimetype;

    my %linking_mimetypes = (
        'text/html' => 1,
        'text/xhtml' => 1,
        'text/xml' => 1,
        'text/x-oeb1-document' => 1,
        'application/atom+xml' => 1,
        'application/xhtml+xml' => 1,
        'application/xml' => 1
        );

    if(!$manifest)
    {
        $self->add_warning(
            "fix_links(): no manifest found!"
            );
        return;
    }
    @unchecked = $self->manifest_hrefs;
    if(!@unchecked)
    {
        $self->add_warning(
            "fix_links(): empty manifest found!"
            );
        return;
    }

    # Initialize %links, so we don't try to add something already in
    # the manifest
    foreach my $mhref (@unchecked)
    {
        $links{$mhref} = undef unless(exists $links{$mhref});
    }

    while(@unchecked)
    {
        debug(3,"DEBUG: ",scalar(@unchecked),
              " items left to check at start of loop");
        $href = shift(@unchecked);
        $href = trim($href);
        debug(3,"DEBUG: checking '",$href,"'");
        next if(defined $links{$href});

        # Skip URIs for now
        if($href =~ m#^ \w+://#ix)
        {
            debug(1,"DEBUG: URI '",$href,"' skipped");
            $links{href} = 0;
            next;
        }
        if(! -f $href)
        {
            $self->add_warning(
                "fix_links(): '" . $href . "' not found"
                );
            $links{$href} = 0;
            next;
        }

        $mimetype = mimetype($href);

        if(!$linking_mimetypes{$mimetype})
        {
            debug(2,"DEBUG: '",$href,"' has mimetype '",$mimetype,
                "' -- not checking");
            $links{$href} = 1;
            next;
        }

        debug(1,"DEBUG: finding links in '",$href,"'");
        push(@newlinks,find_links($href));
        trim(@newlinks) if(@newlinks);
        $links{$href} = 1;
        foreach my $newlink (@newlinks)
        {
            # Skip URIs for now
            if($newlink =~ m#^ \w+://#ix)
            {
                debug(1,"DEBUG: URI '",$newlink,"' skipped");
                next;
            }
            elsif(!exists $links{$newlink})
            {
                debug(2,"DEBUG: adding '",$newlink,"' to the list");
                push(@unchecked,$newlink);
                $self->add_item($newlink);
            }
        }
        debug(2,"DEBUG: ",scalar(@unchecked),
            " items left to check at end of loop");
    } # while(@unchecked)
    debug(2,"DEBUG[/",$subname,"]");
    return 1;
}

=head2 C<fix_manifest()>

Finds all <item> elements and moves them underneath <manifest>,
creating <manifest> if necessary.

Logs a warning but continues if it finds an <item> with a missing id
or href attribute.  If both id and href attributes are missing, logs a
warning, skips moving the item entirely (unless it was already
underneath <manifest>, in which case it is moved to preserve its sort
order along all other items under <manifest>), but otherwise
continues.

=cut

sub fix_manifest :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    my $twigroot = $self->{twigroot};

    my $manifest = $twigroot->first_descendant('manifest');
    my @elements;
    my $parent;

    my $href;
    my $id;

    # If <manifest> doesn't exist, create it
    if(! $manifest)
    {
	debug(1,"DEBUG: creating <manifest>");
	$manifest = $twigroot->insert_new_elt('last_child','manifest');
    }

    # Make sure that the manifest is the first child of the twigroot,
    # which should be <package>
    $parent = $manifest->parent;
    if($parent != $twigroot)
    {
	debug(1,"DEBUG: moving <manifest>");
	$manifest->move('last_child',$twigroot);
    }

    @elements = $twigroot->descendants(qr/^item$/ix);
    foreach my $el (@elements)
    {
        $href = $el->att('href');
        $id = $el->id;
        if(!$id)
        {
            if(!$href)
            {
                # No ID, no href, there's something very fishy here,
                # so log a warning.
                # If it is already underneath <manifest>, move it to
                # preserve sort order, but otherwise leave it alone
                $self->add_warning(
                    "fix_manifest(): found item with no id or href"
                    );
                debug(1,"fix_manifest(): found item with no id or href");
                if($el->parent == $manifest)
                {
                    $el->move('last_child',$manifest);
                }
                else
                {
                    print "DEBUG: skipping item with no id or href\n"
                        if($debug);
                }
                next;
            } # if(!$href)
            # We have a href, but no ID.  Log a warning, but move it anyway.
            $self->add_warning(
                'fix_manifest(): handling item with no ID! '
                . sprintf "(href='%s')",$href
                );
            debug(1,"DEBUG: processing item with no id (href='",$href,"')");
            $el->move('last_child',$manifest);
        } # if(!$id)
        if(!$href)
        {
            # We have an ID, but no href.  Log a warning, but move it anyway.
            $self->add_warning(
                "fix_manifest(): item with id '" . $id . "' has no href!"
                );
            debug(1,"fix_manifest(): item with id '",$id,"' has no href!");
            $el->move('last_child',$manifest);
        }
        else
        {
            # We have an ID and a href
            debug(3,"DEBUG: processing item '",$id,"' (href='",$href,"')");
            $el->move('last_child',$manifest);
        }
    }
    return 1;
}

=head2 C<fix_metastructure_basic()>

Verifies that <metadata> exists (creating it if necessary), and moves
it to be the first child of <package>.

Used in L</fix_metastructure_oeb12()>, L</fix_packageid()>, and
L</set_primary_author(%args)>.

=cut

sub fix_metastructure_basic :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(3,"DEBUG[",$subname,"]");
    $self->twigcheck();

    my $twigroot = $self->{twigroot};
    my $metadata = $twigroot->first_descendant('metadata');

    if(! $metadata)
    {
	debug(1,"DEBUG: creating <metadata>");
	$metadata = $twigroot->insert_new_elt('first_child','metadata');
    }
    debug(3,"DEBUG: moving <metadata> to be the first child of <package>");
    $metadata->move('first_child',$twigroot);
    return 1;
}


=head2 C<fix_metastructure_oeb12()>

Verifies the existence of <metadata>, <dc-metadata>, and <x-metadata>,
creating them as needed, and making sure that <metadata> is a child of
<package>, while <dc-metadata> and <x-metadata> are children of
<metadata>.

Used in L</fix_oeb12()> and L</fix_mobi()>.

=cut

sub fix_metastructure_oeb12 :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(3,"DEBUG[",$subname,"]");
    $self->twigcheck();

    my $twigroot = $self->{twigroot};

    my $metadata;
    my $dcmeta;
    my $xmeta;
    my $parent;

    # Start by forcing the basic <package><metadata> structure
    $self->fix_metastructure_basic;
    $metadata = $twigroot->first_child('metadata');

    # If <dc-metadata> doesn't exist, we'll have to create it.
    $dcmeta = $twigroot->first_descendant('dc-metadata');
    if(! $dcmeta)
    {
	debug(2,"DEBUG: creating <dc-metadata>");
	$dcmeta = $metadata->insert_new_elt('first_child','dc-metadata');
    }

    # Make sure that $dcmeta is a child of $metadata
    $parent = $dcmeta->parent;
    if($parent != $metadata)
    {
	debug(2,"DEBUG: moving <dc-metadata>");
	$dcmeta->move('first_child',$metadata);
    }

    # If <x-metadata> doesn't exist, create it
    $xmeta = $metadata->first_descendant('x-metadata');
    if(! $xmeta)
    {
        debug(2,"DEBUG: creating <x-metadata>");
        $xmeta = $metadata->insert_new_elt('last_child','x-metadata');
    }

    # Make sure that x-metadata is a child of metadata
    $parent = $xmeta->parent;
    if($parent != $metadata)
    {
        debug(2,"DEBUG: moving <x-metadata>");
        $xmeta->move('after',$dcmeta);
    }
    return 1;
}


=head2 C<fix_misc()>

Fixes miscellaneous potential problems in OPF data.  Specifically,
this is a shortcut to calling L</delete_meta_filepos()>,
L</fix_packageid()>, L</fix_dates()>, L</fix_languages()>,
L</fix_publisher()>, L</fix_manifest()>, L</fix_spine()>,
L</fix_guide()>, and L</fix_links()>.

The objective here is that you can run either C<fix_misc()> and either
L</fix_oeb12()> or L</fix_opf20()> and a perfectly valid OPF file will
result from only two calls.

=cut

sub fix_misc :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    $self->delete_meta_filepos();
    $self->fix_packageid();
    $self->fix_dates();
    $self->fix_languages();
    $self->fix_publisher();
    $self->fix_manifest();
    $self->fix_spine();
    $self->fix_guide();
    $self->fix_links();

    debug(2,"DEBUG[/",$subname,"]");
    return 1;
}


=head2 C<fix_mobi()>

Manipulates the twig to fix Mobipocket-specific issues

=over

=item * Force the OEB 1.2 structure (although not the namespace, DTD,
or capitalization), so that <dc-metadata> and <x-metadata> are
guaranteed to exist.

=item * Find and move all Mobi-specific elements to <x-metadata>

=item * If no <output> element exists, creates one for a utf-8 ebook

=back

Note that the forced creation of <output> will cause the OPF file to
become noncompliant with IDPF specifications.

=cut

sub fix_mobi :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    my $twigroot = $self->{twigroot};

    my %mobicontenttypes = (
	'text/x-oeb1-document' => 'text/x-oeb1-document',
	'application/x-mobipocket-subscription'
	=> 'application/x-mobipocket-subscription',
	'application/x-mobipocket-subscription-feed'
	=> 'application/x-mobipocket-subscription-feed',
	'application/x-mobipocket-subscription-magazine'
	=> 'application/x-mobipocket-subscription-magazine',
	'image/gif' => 'image/gif',
	'application/msword' => 'application/msword',
	'application/vnd.ms-excel' => 'application/vnd.ms-excel',
	'application/vnd.ms-powerpoint' => 'application/vnd.ms-powerpoint',
	'text/plain' => 'text/plain',
	'text/html' => 'text/html',
	'application/vnd.mobipocket-game' => 'application/vnd.mobipocket-game',
	'application/vnd.mobipocket-franklin-ua-game'
	=> 'application/vnd.mobipocket-franklin-ua-game'
	);

    my %mobiencodings = (
	'Windows-1252' => 'Windows-1252',
	'utf-8' => 'utf-8'
	);

    my @mobitags = (
        'output',
        'Adult',
        'Demo',
        'DefaultLookupIndex',
        'DictionaryInLanguage',
        'DictionaryOutLanguage',
        'DictionaryVeryShortName',
        'DatabaseName',
        'EmbeddedCover',
        'Review',
        'SRP',
        'Territory'
        );

    my $dcmeta;
    my $xmeta;
    my @elements;
    my $output;


    # Mobipocket currently requires that its custom elements be found
    # underneath <x-metadata>.  Since the presence of <x-metadata>
    # requires that the Dublin Core tags be under <dc-metadata>, we
    # have to use at least the OEB1.2 structure (deprecated, but still
    # allowed in OPF2.0), though we don't have to convert everything.
    $self->fix_metastructure_oeb12();
    $dcmeta = $twigroot->first_descendant('dc-metadata');
    $xmeta = $twigroot->first_descendant('x-metadata');

    # If <x-metadata> doesn't exist, create it.  Even if there are no
    # mobi-specific tags, this method will create at least one
    # (<output>) which will need it.
    if(!$xmeta)
    {
        debug(2,"DEBUG: creating <x-metadata>");
        $xmeta = $dcmeta->insert_new_elt('after','x-metadata')
    }

    foreach my $tag (@mobitags)
    {
        @elements = $twigroot->descendants($tag);
        next unless (@elements);

        # In theory, only one Mobipocket-specific element should ever
        # be present in a document.  We'll deal with multiples anyway,
        # but send a warning.
        if(scalar(@elements) > 1)
        {
            $self->add_warning(
                'fix_mobi(): Found ' . scalar(@elements) . " '" . $tag .
                "' elements, but only one should exist."
                );
        }

        foreach my $el (@elements)
        {
            $el->move('last_child',$xmeta);
        }
    }

    $output = $xmeta->first_child('output');
    if($output)
    {
	my $encoding = $mobiencodings{$output->att('encoding')};
	my $contenttype = $mobicontenttypes{$output->att('content-type')};

	if($contenttype)
	{
	    $output->set_att('encoding','utf-8') if(!$encoding);
	    debug(2,"DEBUG: setting encoding only and returning");
	    return 1;
	}
    }
    else
    {
        debug(1,"DEBUG: creating <output> under <x-metadata>");
        $output = $xmeta->insert_new_elt('last_child','output');
    }


    # At this stage, we definitely have <output> in the right place.
    # Set the attributes and return.
    $output->set_att('encoding' => 'utf-8',
		     'content-type' => 'text/x-oeb1-document');
    debug(2,"DEBUG[/",$subname,"]");
    return 1;
}


=head2 C<fix_oeb12()>

Modifies the OPF data to conform to the OEB 1.2 standard

Specifically, this involves:

=over

=item * adding the OEB 1.2 doctype

=item * removing OPF 2.0 version and namespace attributes

=item * setting the OEB 1.2 namespace on <package>

=item * moving all of the dc-metadata elements underneath an element
with tag <dc-metadata>, which itself is forced to be underneath
<metadata>, which is created if it doesn't exist.

=item * moving any remaining tags underneath <x-metadata>, again
forced to be under <metadata>

=item * making the dc-metadata tags conform to the OEB v1.2 capitalization

=back

=cut

sub fix_oeb12 :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    my $twigroot = $self->{twigroot};
    my $metadata;
    my $dcmeta;
    my $xmeta;
    my @elements;

    # Verify and correct locations for <metadata>, <dc-metadata>, and
    # <x-metadata>, creating them as needed.
    $self->fix_metastructure_oeb12;
    $metadata = $twigroot->first_descendant('metadata');
    $dcmeta = $metadata->first_descendant('dc-metadata');
    $xmeta = $metadata->first_descendant('x-metadata');

    # Clobber metadata attributes 'xmlns:dc' and 'xmlns:opf'
    # used only in OPF2.0
    $metadata->del_atts('xmlns:dc','xmlns:opf');

    # Assign the DC namespace attribute to dc-metadata for OEB 1.2
    $dcmeta->set_att('xmlns:dc',"http://purl.org/dc/elements/1.1/");

    # Set the correct tag name and move it into <dc-metadata> in the
    # right order
    foreach my $dcel (keys %dcelements12)
    {
        @elements = $twigroot->descendants(qr/^$dcel$/ix);
        foreach my $el (@elements)
        {
            debug(3,"DEBUG: processing '",$el->gi,"'");
            croak("Found invalid DC element '",$el->gi,"'!")
                if(!$dcelements12{lc $el->gi});
            $el->set_gi($dcelements12{lc $el->gi});
            $el = twigelt_fix_oeb12_atts($el);
            $el->move('last_child',$dcmeta);
        }
    }

    # Handle non-DC metadata, deleting <x-metadata> if it isn't
    # needed.
    @elements = $metadata->children(qr/^(?!(?s:.*)-metadata)/x);
    if(@elements)
    {
	if($debug)
	{
	    print {*STDERR} "DEBUG: extra metadata elements found: ";
	    foreach my $el (@elements) { print {*STDERR} $el->gi," "; }
	    print {*STDERR} "\n";
	}
	foreach my $el (@elements)
	{
	    $el->move('last_child',$xmeta);
	}
    }
    @elements = $twigroot->children(qr/^meta$/ix);
    foreach my $el (@elements)
    {
        $el->set_gi(lc $el->gi);
        $el->move('last_child',$xmeta);
    }
    @elements = $xmeta->children;
    $xmeta->delete unless(@elements);

    # Fix <manifest> and <spine>
    $self->fix_manifest;
    $self->fix_spine;

    # Set the OEB 1.2 doctype
    $self->{twig}->set_doctype('package',
                              "http://openebook.org/dtds/oeb-1.2/oebpkg12.dtd",
                              "+//ISBN 0-9673008-1-9//DTD OEB 1.2 Package//EN");

    # Clean up <package>
    $twigroot->del_att('version');
    $twigroot->set_att(
        'xmlns' => 'http://openebook.org/namespaces/oeb-package/1.0/');
    $self->fix_packageid;

    $self->{spec} = $validspecs{'OEB12'};
    debug(2,"DEBUG[/",$subname,"]");
    return 1;
}


=head2 C<fix_oeb12_dcmetatags()>

Makes a case-insensitive search for tags matching a known list of DC
metadata elements and corrects the capitalization to the OEB 1.2
standard.  Also corrects 'dc:Copyrights' to 'dc:Rights'.  See global
variable $dcelements12.

The L</fix_oeb12()> method does this also, but fix_oeb12_dcmetatags()
is usable separately for the case where you want DC metadata elements
with consistent tag names, but don't want them moved from wherever
they are.

=cut

sub fix_oeb12_dcmetatags :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    my $topelement = $self->{twigroot};

    my @elements;

    foreach my $dcmetatag (keys %dcelements12)
    {
	@elements = $topelement->descendants(qr/^$dcmetatag$/ix);
	foreach my $el (@elements)
	{
	    $el->set_tag($dcelements12{lc $el->tag})
		if($dcelements12{lc $el->tag});
	}
    }
    return 1;
}


=head2 C<fix_opf20()>

Modifies the OPF data to conform to the OPF 2.0 standard

Specifically, this involves:

=over

=item * moving all of the dc-metadata and x-metadata elements directly
underneath <metadata>

=item * removing the <dc-metadata> and <x-metadata> elements themselves

=item * lowercasing the dc-metadata tags (and fixing dc:copyrights to
dc:rights)

=item * setting namespaces on dc-metata OPF attributes

=item * setting version and xmlns attributes on <package>

=item * setting xmlns:dc and xmlns:opf on <metadata>

=back

=cut

sub fix_opf20 :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    # Ensure a sane structure
    $self->fix_metastructure_basic();

    my $twigroot = $self->{twigroot};
    my $metadata = $twigroot->first_descendant('metadata');
    my @elements;

    # If <dc-metadata> exists, make sure that it is directly
    # underneath <metadata> so that its children will collapse to the
    # correct position, then erase it.
    @elements = $twigroot->descendants('dc-metadata');
    if(@elements)
    {
	foreach my $dcmeta (@elements)
	{
	    debug(1,"DEBUG: moving <dc-metadata>");
	    $dcmeta->move('first_child',$metadata);
	    $dcmeta->erase;
	}
    }

    # If <x-metadata> exists, make sure that it is directly underneath
    # <metadata> so that its children will collapse to the correct
    # position, then erase it.
    @elements = $twigroot->descendants('x-metadata');
    if(@elements)
    {
	foreach my $xmeta (@elements)
	{
	    debug(1,"DEBUG: moving <x-metadata>");
	    $xmeta->move('last_child',$metadata);
	    $xmeta->erase;
	}
    }

    # For all DC elements at any location, set the correct tag name
    # and attribute namespace and move it directly under <metadata>
    foreach my $dcmetatag (keys %dcelements20)
    {
	@elements = $twigroot->descendants(qr/$dcmetatag/ix);
	foreach my $el (@elements)
	{
	    debug(1,"DEBUG: checking element '",$el->gi,"'");
	    $el->set_gi($dcelements20{$dcmetatag});
            $el = twigelt_fix_opf20_atts($el);
	    $el->move('last_child',$metadata);
	}
    }

    # Find any <meta> elements anywhere in the package and move them
    # under <x-metadata>.  Force the tag to lowercase.

    @elements = $twigroot->children(qr/^meta$/ix);
    foreach my $el (@elements)
    {
        $el->set_gi(lc $el->gi);
        $el->move('last_child',$metadata);
    }

    # Fix the <package> attributes
    $twigroot->set_att('version' => '2.0',
                       'xmlns' => 'http://www.idpf.org/2007/opf');
    $self->fix_packageid;

    # Fix the <metadata> attributes
    $metadata->set_att('xmlns:dc' => "http://purl.org/dc/elements/1.1/",
                       'xmlns:opf' => "http://www.idpf.org/2007/opf");

    # Fix <manifest> and <spine>
    $self->fix_manifest;
    $self->fix_spine;

    # Clobber the doctype, if present
    $self->{twig}->set_doctype(0,0,0,0);

    # Set the specification
    $self->{spec} = $validspecs{'OPF20'};

    debug(2,"DEBUG[/",$subname,"]");
    return 1;
}


=head2 C<fix_opf20_dcmetatags()>

Makes a case-insensitive search for tags matching a known list of DC
metadata elements and corrects the capitalization to the OPF 2.0
standard.  Also corrects 'dc:copyrights' to 'dc:rights'.  See package
variable %dcelements20.

The L</fix_opf20()> method does this also, but
C<fix_opf20_dcmetatags()> is usable separately for the case where you
want DC metadata elements with consistent tag names, but don't want
them moved from wherever they are.

=cut

sub fix_opf20_dcmetatags :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    my $topelement = $self->{twigroot};
    my @elements;

    foreach my $dcmetatag (keys %dcelements20)
    {
	@elements = $topelement->descendants(qr/^$dcmetatag$/ix);
	foreach my $el (@elements)
	{
	    $el->set_tag($dcelements20{lc $el->tag})
		if($dcelements20{lc $el->tag});
	}
    }
    return;
}


=head2 C<fix_packageid()>

Checks the <package> element for the attribute 'unique-identifier',
makes sure that it is mapped to a valid dc:identifier subelement, and
if not, searches those subelements for an identifier to assign, or
creates one if nothing can be found.

Requires that <metadata> exist.  Croaks if it doesn't.  Run
L</fix_oeb12()> or L</fix_opf20()> before calling this if the input
might be very broken.

=cut

sub fix_packageid :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    # Start by enforcing the basic structure needed
    $self->fix_metastructure_basic();
    my $twigroot = $self->{twigroot};
    my $packageid = $twigroot->att('unique-identifier');

    my $meta = $twigroot->first_child('metadata')
        or croak($subname,"(): metadata not found");
    my $element;

    if($packageid)
    {
        # Check that the ID maps to a valid identifier
	# If not, undefine it
	debug(2,"DEBUG: checking existing packageid '",$packageid,"'");

	# The twig ID handling system is unreliable, especially when
	# multiple twigs may be existing simultaneously.  Use
	# XML::Twig->first_elt instead of XML::Twig->elt_id, even
	# though it is slower.
        #
        # As of Twig 3.32, this will cause 'uninitialized value'
        # warnings to be spewed for each time no descendants are
        # found.
	#$element = $self->{twig}->elt_id($packageid);
	$element = $self->{twig}->first_elt("*[\@id='$packageid']");

	if($element)
	{
	    if(lc($element->tag) ne 'dc:identifier')
	    {
		debug(1,"DEBUG: packageid '",$packageid,
                      "' points to a non-identifier element ('",
                      $element->tag,"')");
                debug(1,"DEBUG: undefining existing packageid '",
                      $packageid,"'");
		undef($packageid);
	    }
	    elsif(!$element->text)
	    {
		debug(1,"DEBUG: packageid '",$packageid,
                      "' points to an empty identifier.");
		debug(1,"DEBUG: undefining existing packageid '",
                      $packageid,"'");
		undef($packageid);
	    }
	}
	else { undef($packageid); };
    }

    if(!$packageid)
    {
	# Search known IDs for a unique Package ID
	$packageid = $self->search_knownuids;
    }

    # If no unique ID found so far, start searching known schemes
    if(!$packageid)
    {
	$packageid = $self->search_knownuidschemes;
    }

    # And if we still don't have anything, we have to make one from
    # scratch using Data::UUID
    if(!$packageid)
    {
	debug(1,"DEBUG: creating new UUID");
	$element = twigelt_create_uuid();
	$element->paste('first_child',$meta);
	$packageid = 'UUID';
    }

    # At this point, we have a unique ID.  Assign it to package
    $twigroot->set_att('unique-identifier',$packageid);
    debug(2,"[/",$subname,"]");
    return 1;
}


=head2 C<fix_publisher()>

Standardizes publisher names in all dc:publisher entities, mapping
known variants of a publisher's name to a canonical form via package
variable %publishermap.

Publisher entries with no text are deleted.

=cut

sub fix_publisher :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    my @publishers = $self->twigroot->descendants(qr/^dc:publisher$/ix);
    foreach my $pub (@publishers)
    {
        debug(3,"Examining publisher entry in element '",$pub->gi,"'");
        if(!$pub->text)
        {
            debug(1,'Deleting empty publisher entry');
            $pub->delete;
            next;
        }
        elsif( $publishermap{lc $pub->text} &&
               ($publishermap{lc $pub->text} ne $pub->text) )
        {
            debug(1,"DEBUG: Changing publisher from '",$pub->text,"' to '",
                  $publishermap{lc $pub->text},"'");
            $pub->set_text($publishermap{lc $pub->text});
        }
    }
    return 1;
}


=head2 C<fix_spine()>

Fixes problems with the OPF spine, specifically:

=over

=item Moves all <itemref> elements underneath <spine>, creating
<spine> if necessary.

=back

=cut

sub fix_spine :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck();

    my $twigroot = $self->{twigroot};
    my $spine = $twigroot->first_descendant('spine');
    my @elements;
    my $parent;

    @elements = $twigroot->descendants(qr/^itemref$/ix);
    if(@elements)
    {
        # If <spine> doesn't exist, create it
        if(! $spine)
        {
            debug(1,"DEBUG: creating <spine>");
            $spine = $twigroot->insert_new_elt('last_child','spine');
        }

        # Make sure that the spine is a child of the twigroot,
        $parent = $spine->parent;
        if($parent != $twigroot)
        {
            debug(1,"DEBUG: moving <spine>");
            $spine->move('last_child',$twigroot);
        }

        foreach my $el (@elements)
        {
            if(!$el->att('idref'))
            {
                # No idref means it is broken.
                # Leave it alone, but log a warning
                $self->add_warning(
                    "fix_spine(): <itemref> with no idref -- skipping");
                next;
            }
            debug(3,"DEBUG: processing itemref '",$el->att('idref'),"')");
            $el->move('last_child',$spine);
        }
    }
    else # No elements, delete spine if it exists
    {
        $spine->delete if($spine);
    }

    return 1;
}


=head2 C<gen_epub(%args)>

Creates a .epub format e-book.  This will create (or overwrite) the
files 'mimetype' and 'META-INF/container.xml' in the current
directory, creating the subdirectory META-INF as needed.

=head3 Arguments

This method can take two optional named arguments.

=over

=item C<filename>

The filename of the .epub output file.  If not specified, takes the
base name of the opf file and adds a .epub extension.

=item C<dir>

The directory to output the .epub file.  If not specified, uses the
current working directory.  If a specified directory does not exist,
it will be created, or the method will croak.

=back

=head3 Example

 gen_epub(filename => 'mybook.epub',
          dir => '../epub_books');

=cut

sub gen_epub :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");

    my %valid_args = (
        'filename' => 1,
        'dir' => 1,
        );
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }

    my $filename = $args{filename};
    my $dir = $args{dir};
    my $zip = Archive::Zip->new();
    my $member;

    $self->gen_epub_files();
    if(! $self->{opffile} )
    {
	$self->add_error(
	    "Cannot create epub without an OPF (did you forget to init?)");
        debug(1,"Cannot create epub without an OPF");
	return;
    }
    if(! -f $self->{opffile} )
    {
	$self->add_error(
	    sprintf("OPF '%s' does not exist (did you forget to save?)",
		    $self->{opffile})
	    );
        debug(1,"OPF '",$self->{opffile},"' does not exist");
	return;
    }

    $member = $zip->addFile('mimetype');
    $member->desiredCompressionMethod(COMPRESSION_STORED);

    $member = $zip->addFile('META-INF/container.xml');
    $member->desiredCompressionLevel(9);

    $member = $zip->addFile($self->{opffile});
    $member->desiredCompressionLevel(9);

    foreach my $file ($self->manifest_hrefs())
    {
	if(! $file)
	{
	    error("No items found in manifest!");
            debug(1,"No items found in manifest!");
	    return;
	}
	if(-f $file)
	{
	    $member = $zip->addFile($file);
	    $member->desiredCompressionLevel(9);
	}
	else { print STDERR "WARNING: ",$file," not found, skipping.\n"; }
    }

    if(! $filename)
    {
	($filename) = fileparse($self->{opffile},'\.\w+$');
	$filename .= ".epub";
    }

    if($dir)
    {
        unless(-d $dir)
        {
            mkpath($dir)
                or croak("Unable to create working directory '",$dir,"'!");
        }
        $filename = "$dir/$filename";
    }

    unless ( $zip->writeToFileNamed($filename) == AZ_OK )
    {
	$self->add_error(
            sprintf("Failed to create epub as '%s'",$filename));
        debug(1,"Failed to create epub as '",$filename,"'");
	return;
    }
    return 1;
}


=head2 C<gen_epub_files()>

Generates the C<mimetype> and C<META-INF/container.xml> files expected
by a .epub container, but does not actually generate the .epub file
itself.  This will be called automatically by C<gen_epub>.

=cut

sub gen_epub_files :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");

    create_epub_mimetype();
    create_epub_container($self->{opffile});
    return 1;
}


=head2 C<gen_ncx($filename)>

Creates a NCX-format table of contents from the package
unique-identifier, the dc:title, dc:creator, and spine elements, and
then add the NCX entry to the manifest if it is not already
referenced.

Adds an error and fails if any of those cannot be found.  The first
available dc:title is taken, but will prioritize dc:creator elements
with opf:role="aut" over those with no role attribute (see
twigelt_is_author() for details).

WARNING: This method REQUIRES that the e-book be in OPF 2.0 format to
function correctly.  Call fix_opf20() before calling gen_ncx().
gen_ncx() will log an error and fail if $self{spec} is not set to
OPF20.

=head3 Arguments

=over

=item $filename : The filename to save to.  If not specified, will use
'toc.ncx'.

=back

This method will overwrite any existing file.

Returns a twig containing the NCX XML, or undef on failure.

=cut

sub gen_ncx :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my ($filename) = @_;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck;

    $filename = 'toc.ncx' if(!$filename);

    my $twigroot = $self->{twigroot};
    my $identifier = $self->identifier;
    my $element;            # Generic element container
    my $parent;             # Generic parent element container
    my $ncx;                # NCX twig
    my $ncxroot;            # NCX twig root <ncx>
    my $ncxitem;            # manifest item pointing to the NCX document
    my $navmap;             # NCX element <navMap>
    my $navpoint;           # NCX element <navPoint>
    my %navpointorder;      # Hash mapping playOrder to id
    my $navpointindex = 1;  # playOrder number starting at 1
    my $title;              # E-book title
    my $author;             # E-book primary author
    my @spinelist;          # List of hashrefs containing spine data
    my $manifest;           # OPF manifest element

    if($self->{spec} ne 'OPF20')
    {
        $self->add_error(
            $subname . "(): specification is currently set to '"
            . $self->{spec} . "' -- need 'OPF20'"
            );
        debug(1,"DEBUG: gen_ncx() FAILED: wrong specification ('",
              $self->{spec},"')!");
        return;
    }

    if(!$identifier)
    {
        $self->add_error( $subname . "(): no unique-identifier found" );
        debug(1,"DEBUG: gen_ncx() FAILED: no unique-identifier!");
        return;
    }

    # Get the title
    $title = $self->title();
    if(!$title)
    {
        $self->add_error( $subname . "(): no title found" );
        debug(1,"DEBUG: gen_ncx() FAILED: no title!");
        return;
    }

    # Get the author
    $author = $self->primary_author();
    if(!$author)
    {
        $self->add_error( $subname . "(): no title found" );
        debug(1,"DEBUG: gen_ncx() FAILED: no title!");
        return;
    }

    # Get the spine list
    @spinelist = $self->spine();
    if(!@spinelist)
    {
        $self->add_error( $subname . "(): no spine found" );
        debug(1,"DEBUG: gen_ncx() FAILED: no spine!");
        return;
    }

    # Make sure the manifest element exists
    # (This should in theory never fail, since it is also checked by
    # spine() above)
    $manifest = $twigroot->first_descendant('manifest');
    if(!$manifest)
    {
        $self->add_error( $subname . "(): no manifest found" );
        debug(1,"DEBUG: gen_ncx() FAILED: no manifest!");
        return;
    }

    $ncx = XML::Twig->new(
	output_encoding => 'utf-8',
	pretty_print => 'record'
	);

    # <ncx>
    $element = XML::Twig::Elt->new('ncx');
    $element->set_att('xmlns' => 'http://www.daisy.org/z3986/2005/ncx/');
    $ncx->set_root($element);
    $ncxroot = $ncx->root;

    # <head>
    $parent = $ncxroot->insert_new_elt('first_child','head');
    $element = $parent->insert_new_elt('last_child','meta');
    $element->set_att(
        'name' => 'dtb:uid',
        'content' => $identifier
        );

    $element = $parent->insert_new_elt('last_child','meta');
    $element->set_att(
        'name'    => 'dtb:depth',
        'content' => '1'
        );
    $element = $parent->insert_new_elt('last_child','meta');
    $element->set_att(
        'name' => 'dtb:totalPageCount',
        'content' => '0'
        );

    $element = $parent->insert_new_elt('last_child','meta');
    $element->set_att(
        'name' => 'dtb:maxPageNumber',
        'content' => '0'
        );

    # <docTitle>
    $parent = $parent->insert_new_elt('after','docTitle');
    $element = $parent->insert_new_elt('first_child','text');
    $element->set_text($title);

    # <navMap>
    $navmap = $parent->insert_new_elt('after','navMap');

    foreach my $spineitem (@spinelist)
    {
        # <navPoint>
        $navpoint = $navmap->insert_new_elt('last_child','navPoint');
        $navpoint->set_att('id' => $$spineitem{'id'},
                           'playOrder' => $navpointindex);
        $navpointindex++;

        # <navLabel>
        $parent = $navpoint->insert_new_elt('last_child','navLabel');
        $element = $parent->insert_new_elt('last_child','text');
        $element->set_text($$spineitem{'id'});

        # <content>
        $element = $navpoint->insert_new_elt('last_child','content');
        $element->set_att('src' => $$spineitem{'href'});
    }

    # Backup existing file
    if(-e $filename)
    {
        rename($filename,"$filename.backup")
            or croak($subname,"(): could not backup ",$filename,"!");
    }

    # Twig handles utf-8 on its own.  Setting binmode :utf8 here will
    # cause double-conversion.
    open(my $fh_ncx,'>',$filename)
        or croak($subname,"(): failed to open '",$filename,"' for writing!");
    $ncx->print(\*$fh_ncx);
    close($fh_ncx)
        or croak($subname,"(): failed to close '",$filename,"'!");

    # Search for existing NCX entries and modify the first one found,
    # creating a new one if there are no matches.
    $ncxitem = $manifest->first_child('item[@id="ncx"]');
    $ncxitem = $manifest->first_child("item[\@href='$filename']")
        if(!$ncxitem);
    $ncxitem = $manifest->first_child('item[@media-type="application/x-dtbncx+xml"]')
        if(!$ncxitem);
    $ncxitem = $manifest->insert_new_elt('first_child','item')
        if(!$ncxitem);

    $ncxitem->set_att(
        'id' => 'ncx',
        'href' => $filename,
        'media-type' => 'application/x-dtbncx+xml'
        );

    # Move the NCX item to the top of the manifest
    $ncxitem->move('first_child',$manifest);

    return $ncx;
}


=head2 C<save()>

Saves the OPF file to disk.  Existing files are backed up to
filename.backup.

=cut

sub save :method
{
    my $self = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");

    croak($subname,"(): no opffile specified (did you forget to init?)")
        if(!$self->{opffile});

    my $fh_opf;
    my $filename = $self->{opffile};

    # Backup existing file
    if(-e $filename)
    {
        rename($filename,"$filename.backup")
            or croak($subname,"(): could not backup ",$filename,"!");
    }


    # Twig handles utf8 on its own.  If you open this file with
    # binmode :utf8, it will double-convert.
    if(!open($fh_opf,">",$self->{opffile}))
    {
	add_error(sprintf("Could not open '%s' to save to!",$self->{opffile}));
	return;
    }
    $self->{twig}->print(\*$fh_opf);

    if(!close($fh_opf))
    {
	add_error(sprintf("Failure while closing '%s'!",$self->{opffile}));
	return;
    }
    return 1;
}


=head2 C<set_adult($bool)>

Sets the Mobipocket-specific <Adult> element, creating or deleting it
as necessary.  If C<$bool> is true, the text is set to 'yes'.  If it
is defined but false, any existing elements are deleted.  If it is
undefined, the method immediately returns.

If a new element has to be created, L</fix_metastructure_oeb12> is
called to ensure that <x-metadata> exists and the element is created
under <x-metadata>, as Mobipocket elements are not recognized by
Mobipocket's software when placed directly under <metadata>

=cut

sub set_adult :method
{
    my $self = shift;
    my $adult = shift;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck;

    return 1 unless(defined $adult);

    my $xmeta;
    my $element;
    my @elements;

    if($adult)
    {
        $element = $self->{twigroot}->first_descendant(qr/^adult$/ix);
        unless($element)
        {
            $self->fix_metastructure_oeb12();
            $xmeta = $self->{twigroot}->first_descendant('x-metadata');
            $element = $xmeta->insert_new_elt('last_child','Adult');
        }
        $element->set_text('yes');
    }
    else
    {
        @elements = $self->{twigroot}->descendants(qr/^adult$/ix);
        foreach my $el (@elements)
        {
            debug(2,"DEBUG: deleting <Adult> flag");
            $el->delete;
        }
    }
    return 1;
}


=head2 C<set_date(%args)>

Sets the date metadata for a given event.  If more than one dc:date or
dc:Date element is present with the specified event attribute, sets
the first.  If no dc:date element is present with the specified event
attribute, a new element is created.

If a <dc-metadata> element exists underneath <metadata>, the date
element will be created underneath the <dc-metadata> in OEB 1.2
format, otherwise the title element is created underneath <metadata>
in OPF 2.0 format.

Returns 1 on success, logs an error and returns undef if no text or
event was specified.

=head3 Arguments

=over

=item C<text>

This specifies the description to use as the text of the element.  If
not specified, the method sets an error and returns undef.

=item C<event>

This specifies the event attribute for the date.  If not specified,
the method sets an error and returns undef.

=item C<id> (optional)

This specifies the ID to set on the element.  If set and the ID is
already in use, a warning is logged and the ID is removed from the
other location and assigned to the element.

=back

=cut

sub set_date :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    my %valid_args = (
        'text' => 1,
        'event' => 1,
        'id' => 1,
        );
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }

    my $text = $args{text};
    my $event = $args{event};
    my $newid = $args{id};
    unless($text)
    {
        $self->add_error($subname,"(): no text specified");
        return;
    }
    unless($event)
    {
        $self->add_error($subname,"(): no event specified");
        return;
    }

    my $meta = $self->{twigroot}->first_child('metadata');
    my $dcmeta = $meta->first_child('dc-metadata');
    my $idelem;
    $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);

    $self->fix_metastructure_basic();

    my $element = $self->{twigroot}->first_descendant(
        "dc:date[\@opf:event=~/$event/ix or \@event=~/$event/ix]");
    $element = $self->{twigroot}->first_descendant(
        "dc:Date[\@opf:event=~/$event/ix or \@event=~/$event/ix]")
        unless($element);

    if($element)
    {
        $element->set_text($text);
    }
    elsif($dcmeta)
    {
        $element = $dcmeta->insert_new_elt('last_child','dc:Date');
        $element->set_att('event',$event);
        $element->set_text($text);
    }
    else
    {
        $element = $meta->insert_new_elt('last_child','dc:date');
        $element->set_att('opf:event',$event);
        $element->set_text($text);
    }

    if($idelem && $idelem->cmp($element) )
    {
        $self->add_warning(
            $subname,"(): reassigning id '",$newid,
            "' from a '",$idelem->gi,"' element!"
            );
        $idelem->del_att('id');
    }
    $element->set_att('id' => $newid) if($newid);
    return 1;
}


=head2 set_description(%args)

Sets the text and optionally ID of the first dc:description element
found (case-insensitive).  Creates the element if one did not exist.
If a <dc-metadata> element exists underneath <metadata>, the
description element will be created underneath the <dc-metadata> in
OEB 1.2 format, otherwise the title element is created underneath
<metadata> in OPF 2.0 format.

Returns 1 on success, returns undef if no publisher was specified.

=head3 Arguments

C<set_description()> takes one required and one optional named argument

=over

=item C<text>

This specifies the description to use as the text of the element.  If
not specified, the method returns undef.

=item C<id> (optional)

This specifies the ID to set on the element.  If set and the ID is
already in use, a warning is logged and the ID is removed from the
other location and assigned to the element.

=back

=head3 Example

 $retval = $ebook->set_description('text' => 'A really good book',
                                   'id' => 'mydescid');

=cut

sub set_description :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    my %valid_args = (
        'text' => 1,
        'id' => 1,
        );
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }

    my $text = $args{text};
    unless($text)
    {
        $self->add_error($subname,"(): no text specified");
        return;
    }

    $self->fix_metastructure_basic();
    my $element = $self->{twigroot}->first_descendant(qr/^dc:description$/ix);
    my $meta = $self->{twigroot}->first_child('metadata');
    my $dcmeta = $meta->first_child('dc-metadata');

    my $gi = ($dcmeta) ? 'dc:Description' : 'dc:description';
    $self->set_metadata(gi => $gi,
                        text => $text,
                        id => $args{id});

    return 1;
}


=head2 C<set_language(%args)>

Sets the text and optionally the ID of the first dc:language element
found (case-insensitive).  Creates the element if one did not exist.
If a <dc-metadata> element exists underneath <metadata>, the language
element will be created underneath the <dc-metadata> in OEB 1.2
format, otherwise the title element is created underneath <metadata>
in OPF 2.0 format.

Returns 1 on success, returns undef if no text was specified.

=head3 Arguments

=over

=item C<text>

This specifies the language set as the text of the element.  If not
specified, the method sets an error and returns undef.  This should be
an IANA language code, and it will be lowercased before it is set.

=item C<id> (optional)

This specifies the ID to set on the element.  If set and the ID is
already in use, a warning is logged and the ID is removed from the
other location and assigned to the element.

=back

=head3 Example

 $retval = $ebook->set_language('text' => 'en-us',
                                'id' => 'langid');

=cut

sub set_language :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    my %valid_args = (
        'text' => 1,
        'id' => 1,
        );
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }

    my $text = lc($args{text});
    unless($text)
    {
        $self->add_error($subname,"(): no text specified");
        return;
    }

    $self->fix_metastructure_basic();
    my $element = $self->{twigroot}->first_descendant(qr/^dc:language$/ix);
    my $meta = $self->{twigroot}->first_child('metadata');
    my $dcmeta = $meta->first_child('dc-metadata');

    my $gi = ($dcmeta) ? 'dc:Language' : 'dc:language';
    $self->set_metadata(gi => $gi,
                        text => $text,
                        id => $args{id});
    return 1;
}


=head2 set_metadata(%args)

Sets the text and optionally the ID of the first specified element
type found (case-insensitive).  Creates the element if one did not
exist (with the exact capitalization specified).

If a <dc-metadata> element exists underneath <metadata>, the language
element will be created underneath the <dc-metadata> and any standard
attributes will be created in OEB 1.2 format, otherwise the element is
created underneath <metadata> in OPF 2.0 format.

Returns 1 on success, returns undef if no gi or if no text was specified.

=cut

=head3 Arguments

=over

=item C<gi>

The generic identifier (tag) of the metadata element to alter or
create.  If not specified, the method sets an error and returns undef.

=item C<parent>

The generic identifier (tag) of the parent to use for any newly
created element.  If not specified, defaults to 'dc-metadata' if
'dc-metadata' exists underneath 'metadata', and 'metadata' otherwise.

A newly created element will be created under the first element found
with this gi.  A modified element will be moved under the first
element found with this gi.

Newly created elements will use OPF 2.0 attribute names if the parent
is 'metadata' and OEB 1.2 attribute names otherwise.

=item C<text>

This specifies the element text to set.  If not specified, the method
sets an error and returns undef.

=item C<id> (optional)

This specifies the ID to set on the element.  If set and the ID is
already in use, a warning is logged and the ID is removed from the
other location and assigned to the element.

=item C<fileas> (optional)

This specifies the file-as attribute to set on the element.

=item C<role> (optional)

This specifies the role attribute to set on the element.

=item C<scheme> (optional)

This specifies the scheme attribute to set on the element.

=back

=head3 Example

 $retval = $ebook->set_metadata(gi => 'AuthorNonstandard',
                                text => 'Element Text',
                                id => 'customid',
                                fileas => 'Text, Element',
                                role => 'xxx',
                                scheme => 'code');

=cut

sub set_metadata :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(3,"DEBUG[",$subname,"]");
    my %valid_args = (
        'gi' => 1,
        'parent' => 1,
        'text' => 1,
        'id' => 1,
        'fileas' => 1,
        'role' => 1,
        'scheme' => 1,
        );
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }

    my $gi = $args{gi};
    unless($gi)
    {
        $self->add_error($subname,"(): no gi specified");
        return;
    }

    my $text = $args{text};
    unless($text)
    {
        $self->add_error($subname,"(): no text specified");
        return;
    }

    my $newid = $args{id};
    my $idelem;
    $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);

    my $element = $self->{twigroot}->first_descendant(qr/^ $gi $/ix);
    my $meta;
    my $dcmeta;
    my $parent;
    my %dcatts;

    $self->fix_metastructure_basic();
    $parent =  $self->{twigroot}->first_descendant(qr/^ $args{parent} $/ix)
        if($args{parent});
    $meta = $self->{twigroot}->first_child('metadata');
    $dcmeta = $meta->first_child('dc-metadata');
    $parent = $parent || $dcmeta || $meta;
    if($parent->gi eq 'metadata')
    {
        %dcatts = (
            'file-as' => 'opf:file-as',
            'role' => 'opf:role',
            'scheme' => 'opf:scheme',
            );
    }
    else
    {
        %dcatts = (
            'file-as' => 'file-as',
            'role' => 'role',
            'scheme' => 'scheme'
        );
    }


    if($element)
    {
        debug(2,"DEBUG: updating '",$gi,"'");
        if($element->att('opf:file-as') && $args{fileas})
        {
            debug(3,"DEBUG:   setting opf:file-as '",$args{fileas},"'");
            $element->set_att('opf:file-as',$args{fileas});
        }
        elsif($args{fileas})
        {
            debug(3,"DEBUG:   setting file-as '",$args{fileas},"'");
            $element->set_att('file-as',$args{fileas});
        }
        if($element->att('opf:role') && $args{role})
        {
            debug(3,"DEBUG:   setting opf:role '",$args{role},"'");
            $element->set_att('opf:role',$args{role});
        }
        elsif($args{role})
        {
            debug(3,"DEBUG:   setting role '",$args{role},"'");
            $element->set_att('role',$args{role});
        }
        if($element->att('opf:scheme') && $args{scheme})
        {
            debug(3,"DEBUG:   setting opf:scheme '",$args{scheme},"'");
            $element->set_att('opf:scheme',$args{scheme});
        }
        elsif($args{scheme})
        {
            debug(3,"DEBUG:   setting scheme '",$args{scheme},"'");
            $element->set_att('scheme',$args{scheme});
        }
        debug(3,"DEBUG:   setting text");
        $element->set_text($text);

        unless($element->parent->gi eq $parent->gi)
        {
            debug(2,"DEBUG: moving <",$element->gi,"> under <",
                  $parent->gi,">");
            $element->move('last_child',$parent);
        }
    }
    else
    {
        debug(2,"DEBUG: creating '",$gi,"' under <",$parent->gi,">");
        $element = $parent->insert_new_elt('last_child',$gi);
        $element->set_att($dcatts{'file-as'},$args{fileas})
            if($args{fileas});
        $element->set_att($dcatts{'role'},$args{role})
            if($args{role});
        $element->set_att($dcatts{'scheme'},$args{scheme})
            if($args{scheme});
        $element->set_text($text);
    }

    if($idelem && $idelem->cmp($element) )
    {
        $self->add_warning(
            $subname,"(): reassigning id '",$newid,
            "' from a '",$idelem->gi,"' to a '",$element->gi,"'!"
            );
        $idelem->del_att('id');
    }
    $element->set_att('id' => $newid) if($newid);
    return 1;
}


=head2 set_opffile($filename)

Sets the filename used to store the OPF metadata.

Returns 1 on success; sets an error message and returns undef if no
filename was specified.

=cut

sub set_opffile :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my ($filename) = @_;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");

    unless($filename)
    {
        debug(1,$subname,"(): no filename specified!");
        $self->add_warning($subname,"(): no filename specified!");
        return;
    }
    $self->{opffile} = $filename;
    return 1;
}


=head2 set_retailprice(%args)

Sets the Mobipocket-specific <SRP> element (Suggested Retail Price),
creating or deleting it as necessary.

If a new element has to be created, L</fix_metastructure_oeb12> is
called to ensure that <x-metadata> exists and the element is created
under <x-metadata>, as Mobipocket elements are not recognized by
Mobipocket's software when placed directly under <metadata>

=head3 Arguments

=over

=item * C<text>

The price to set as the text of the element.  If this is undefined,
the method sets an error and returns undef.  If it is set but false,
any existing <SRP> element is deleted.

=item * C<currency> (optional)

The value to set on the 'Currency' attribute.  If not provided,
defaults to 'USD' (US Dollars)

=back

=cut

sub set_retailprice :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my %args = @_;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    $self->twigcheck;

    my %valid_args = (
        'text' => 1,
        'currency' => 1,
        );

    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }
    unless(defined $args{text})
    {
        $self->add_error($subname,"(): text not defined");
        return;
    }

    my $xmeta;
    my $element;
    my @elements;

    if($args{text})
    {
        $element = $self->{twigroot}->first_descendant(qr/^ SRP $/ix);
        unless($element)
        {
            $self->fix_metastructure_oeb12();
            $xmeta = $self->{twigroot}->first_descendant('x-metadata');
            $element = $xmeta->insert_new_elt('last_child','SRP');
        }
        $element->set_text($args{text});
        $element->set_att('Currency',$args{currency}) if($args{currency});
    }
    else
    {
        @elements = $self->{twigroot}->descendants(qr/^ SRP $/ix);
        foreach my $el (@elements)
        {
            debug(2,"DEBUG: deleting <SRP>");
            $el->delete;
        }
    }
    return 1;
}


=head2 set_primary_author(%args)

Sets the text, id, file-as, and role attributes of the primary author
element (see L</primary_author()> for details on how this is found),
or if no primary author exists, creates a new element containing the
information.

This method calls L</fix_metastructure_basic()> to enforce the
presence of the <metadata> element.  When creating a new element, the
method will use the OEB 1.2 element name and create the element
underneath <dc-metadata> if an existing <dc-metadata> element is found
underneath <metadata>.  If no existing <dc-metadata> element is found,
the new element will be created with the OPF 2.0 element name directly
underneath <metadata>.  Regardless, it is probably a good idea to call
L</fix_oeb12()> or L</fix_opf20()> after calling this method to ensure
a consistent scheme.

=head3 Arguments

Three optional named arguments can be passed:

=over

=item * C<text>

Specifies the author text to set.  If omitted and a primary author
element exists, the text will be left as is; if omitted and a primary
author element cannot be found, an error message will be generated and
the method will return undef.

=item * C<fileas>

Specifies the 'file-as' attribute to set.  If omitted and a primary
author element exists, any existing attribute will be left untouched;
if omitted and a primary author element cannot be found, the newly
created element will not have this attribute.

=item * C<id>

Specifies the 'id' attribute to set.  If this is specified, and the id
is already in use, a warning will be added but the method will
continue, removing the id attribute from the element that previously
contained it.

If this is omitted and a primary author element exists, any existing
id will be left untouched; if omitted and a primary author element
cannot be found, the newly created element will not have an id set.

=back

If called with no arguments, the only effect this method has is to
enforce that either an 'opf:role' or 'role' attribute is set to 'aut'
on the primary author element.

=head3 Return values

Returns 1 if successful, returns undef and sets an error message if
the author argument is missing and no primary author element was
found.

=cut

sub set_primary_author :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    my %valid_args = (
        'text' => 1,
        'fileas' => 1,
        'id' => 1,
        );
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }

    my $twigroot = $self->{twigroot};
    $self->fix_metastructure_basic();
    my $meta = $twigroot->first_child('metadata');
    my $dcmeta = $meta->first_child('dc-metadata');
    my $element;
    my $newauthor = $args{text};
    my $newfileas = $args{fileas};
    my $newid = $args{id};
    my $idelem;
    $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);

    $element = $twigroot->first_descendant(\&twigelt_is_author);
    $element = $twigroot->first_descendant(qr/dc:creator/ix) if(!$element);

    unless($element)
    {
        unless($newauthor)
        {
            add_error(
                $subname,
                "(): cannot create a new author element when the author is not specified");
            return;
        }
        if($dcmeta)
        {
            $element = $dcmeta->insert_new_elt('last_child','dc:Creator');
            $element->set_att('role' => 'aut');
            $element->set_att('file-as' => $newfileas) if($newfileas);
        }
        else
        {
            $element = $meta->insert_new_elt('last_child','dc:creator');
            $element->set_att('opf:role' => 'aut');
            $element->set_att('opf:file-as' => $newfileas) if($newfileas);
        }
    } # unless($element)
    $element->set_text($newauthor);

    if($idelem && $idelem->cmp($element) )
    {
        $self->add_warning(
            $subname,"(): reassigning id '",$newid,
            "' from a '",$idelem->gi,"' element!"
            );
        $idelem->del_att('id');
    }
    $element->set_att('id' => $newid) if($newid);
    return 1;
}


=head2 C<set_publisher(%args)>

Sets the text and optionally the ID of the first dc:publisher element
found (case-insensitive).  Creates the element if one did not exist.
If a <dc-metadata> element exists underneath <metadata>, the publisher
element will be created underneath the <dc-metadata> in OEB 1.2
format, otherwise the title element is created underneath <metadata>
in OPF 2.0 format.

Returns 1 on success, returns undef if no publisher was specified.

=head3 Arguments

C<set_publisher()> takes one required and one optional named argument

=over

=item C<text>

This specifies the publisher name to set as the text of the element.
If not specified, the method returns undef.

=item C<id> (optional)

This specifies the ID to set on the element.  If set and the ID is
already in use, a warning is logged and the ID is removed from the
other location and assigned to the element.

=back

=head3 Example

 $retval = $ebook->set_publisher('text' => 'My Publishing House',
                                 'id' => 'mypubid');

=cut

sub set_publisher :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    my %valid_args = (
        'text' => 1,
        'id' => 1,
        );
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }

    my $publisher = $args{text};
    return unless($publisher);

    my $newid = $args{id};
    my $idelem;
    $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);

    $self->fix_metastructure_basic();
    my $element = $self->{twigroot}->first_descendant(qr/^dc:publisher$/ix);
    my $meta = $self->{twigroot}->first_child('metadata');
    my $dcmeta = $meta->first_child('dc-metadata');

    if(!$element && $dcmeta)
    {
        $element = $dcmeta->insert_new_elt('last_child','dc:Publisher');
    }
    elsif(!$element)
    {
        $element = $meta->insert_new_elt('last_child','dc:publisher');
    }
    $element->set_text($publisher);
    if($idelem && $idelem->cmp($element) )
    {
        $self->add_warning(
            $subname,"(): reassigning id '",$newid,
            "' from a '",$idelem->gi,"' element!"
            );
        $idelem->del_att('id');
    }
    $element->set_att('id' => $newid) if($newid);
    return 1;
}


=head2 set_review(%args)

Sets the text and optionally ID of the first <Review> element found
(case-insensitive), creating the element if one did not exist.

This is a Mobipocket-specific element and if it needs to be created it
will always be created under <x-metadata> with
L</fix_metastructure_oeb12()> called to ensure that <x-metadata>
exists.

Returns 1 on success, returns undef if no review text was specified

=head3 Arguments

=over

=item C<text>

This specifies the description to use as the text of the element.  If
not specified, the method returns undef.

=item C<id> (optional)

This specifies the ID to set on the element.  If set and the ID is
already in use, a warning is logged and the ID is removed from the
other location and assigned to the element.

=back

=head3 Example

 $retval = $ebook->set_review('text' => 'This book is perfect!',
                              'id' => 'revid');

=cut

sub set_review :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    my %valid_args = (
        'text' => 1,
        'id' => 1,
        );
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }

    my $text = $args{text};
    unless($text)
    {
        $self->add_error($subname,"(): no text specified");
        return;
    }

    $self->fix_metastructure_oeb12();
    $self->set_metadata(gi => 'Review',
                        parent => 'x-metadata',
                        text => $args{text},
                        id => $args{id});

    return 1;
}


=head2 C<set_rights(%args)>

Sets the text of the first dc:rights or dc:copyrights element found
(case-insensitive).  If the element found has the gi of dc:copyrights,
it will be changed to dc:rights.  This is to correct certain
noncompliant Mobipocket files.

Creates the element if one did not exist.  If a <dc-metadata> element
exists underneath <metadata>, the title element will be created
underneath the <dc-metadata> in OEB 1.2 format, otherwise the title
element is created underneath <metadata> in OPF 2.0 format.

Returns 1 on success, returns undef if no rights string was specified.

=head3 Arguments

=over

=item * C<text>

This specifies the text of the element.  If not specified, the method
returns undef.

=item * C<id> (optional)

This specifies the ID to set on the element.  If set and the ID is
already in use, a warning is logged but the method continues anyway.

=back

=cut

sub set_rights :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    my %valid_args = (
        'text' => 1,
        'id' => 1,
        );
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }
    my $rights = $args{text};
    return unless($rights);
    my $newid = $args{id};
    my $idelem;
    $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);

    $self->fix_metastructure_basic();
    my $element = $self->{twigroot}->first_descendant(qr/^dc:(copy)?rights$/ix);
    my $meta = $self->{twigroot}->first_child('metadata');
    my $dcmeta = $meta->first_child('dc-metadata');
    my $parent = $dcmeta || $meta;

    $element ||= $parent->insert_new_elt('last_child','dc:rights');
    $element->set_text($rights);
    $element->set_gi('dc:Rights') if($element->gi eq 'dc:Copyrights');
    $element->set_gi('dc:rights') if($element->gi eq 'dc:copyrights');
    if($idelem && $idelem->cmp($element) )
    {
        $self->add_warning(
            $subname,"(): reassigning id '",$newid,
            "' from a '",$idelem->gi,"' element!"
            );
        $idelem->del_att('id');
    }
    $element->set_att('id' => $newid) if($newid);
    return 1;
}


=head2 C<set_spec($spec)>

Sets the OEB specification to match when modifying OPF data.
Allowable values are 'OEB12', 'OPF20', and 'MOBI12'.

Returns 1 if successful; returns undef and sets an error message if an
unknown specification was set.

=cut

sub set_spec :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my ($spec) = @_;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");

    unless($validspecs{$spec})
    {
        $self->add_error($subname,"(): invalid specification '",$spec,"'");
        return;
    }
    $self->{spec} = $validspecs{$spec};
    return 1;
}


=head2 C<set_title(%args)>

Sets the text or id of the first dc:title element found
(case-insensitive).  Creates the element if one did not exist.  If a
<dc-metadata> element exists underneath <metadata>, the title element
will be created underneath the <dc-metadata> in OEB 1.2 format,
otherwise the title element is created underneath <metadata> in OPF
2.0 format.

=head3 Arguments

set_title() takes two optional named arguments.  If neither is
specified, the method will do nothing.

=over

=item * C<text>

This specifies the text of the element.  If not specified, and no
title element is found, an error will be set and the method will
return undef -- set_title() will refuse to create a dc:title element
with no text.

=item * C<id>

This specifies the ID to set on the element.  If set and the ID is
already in use, a warning is logged but the method continues anyway.

=back

=cut

sub set_title :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");

    my %valid_args = (
        'text' => 1,
        'id' => 1,
        );
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }
    my $title = $args{text};
    my $newid = $args{id};
    my $idelem;
    $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);

    $self->fix_metastructure_basic();
    my $element = $self->{twigroot}->first_descendant(qr/^dc:title$/ix);
    my $meta = $self->{twigroot}->first_child('metadata');
    my $dcmeta = $meta->first_child('dc-metadata');
    my $parent = $dcmeta || $meta;
    unless($element)
    {
        unless($title)
        {
            add_error($subname,
                      "(): no title specified, but no existing title found");
            return;
        }
        $element = $parent->insert_new_elt('last_child','dc:title');
    }
    $element->set_text($title) if($title);

    if($idelem && $idelem->cmp($element) )
    {
        $self->add_warning(
            $subname,"(): reassigning id '",$newid,
            "' from a '",$idelem->gi,"' element!"
            );
        $idelem->del_att('id');
    }
    $element->set_att('id' => $newid) if($newid);
    return 1;
}


=head2 C<set_type(%args)>

Sets the text and optionally the ID of the first dc:type element
found (case-insensitive).  Creates the element if one did not exist.
If a <dc-metadata> element exists underneath <metadata>, the publisher
element will be created underneath the <dc-metadata> in OEB 1.2
format, otherwise the title element is created underneath <metadata>
in OPF 2.0 format.

Returns 1 on success, returns undef if no publisher was specified.

=head3 Arguments

C<set_type()> takes one required and one optional named argument

=over

=item C<text>

This specifies the publisher name to set as the text of the element.
If not specified, the method returns undef.

=item C<id> (optional)

This specifies the ID to set on the element.  If set and the ID is
already in use, a warning is logged and the ID is removed from the
other location and assigned to the element.

=back

=head3 Example

 $retval = $ebook->set_type('text' => 'Short Story',
                            'id' => 'mytypeid');

=cut

sub set_type :method    ## no critic (Always unpack @_ first)
{
    my $self = shift;
    my (%args) = @_;
    my $subname = ( caller(0) )[3];
    croak($subname . "() called as a procedure") unless(ref $self);
    debug(2,"DEBUG[",$subname,"]");
    my %valid_args = (
        'text' => 1,
        'id' => 1,
        );
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }

    my $text = $args{text};
    return unless($text);

    my $newid = $args{id};
    my $idelem;
    $idelem = $self->{twig}->first_elt("*[\@id='$newid']") if($newid);

    $self->fix_metastructure_basic();
    my $element = $self->{twigroot}->first_descendant(qr/^dc:type$/ix);
    my $meta = $self->{twigroot}->first_child('metadata');
    my $dcmeta = $meta->first_child('dc-metadata');

    if(!$element && $dcmeta)
    {
        $element = $dcmeta->insert_new_elt('last_child','dc:Type');
    }
    elsif(!$element)
    {
        $element = $meta->insert_new_elt('last_child','dc:type');
    }
    $element->set_text($text);
    if($idelem && $idelem->cmp($element) )
    {
        $self->add_warning(
            $subname,"(): reassigning id '",$newid,
            "' from a '",$idelem->gi,"' element!"
            );
        $idelem->del_att('id');
    }
    $element->set_att('id' => $newid) if($newid);
    return 1;
}


################################
########## PROCEDURES ##########
################################

=head1 PROCEDURES

All procedures are exportable, but none are exported by default.  All
procedures can be exported by using the ":all" tag.


=head2 C<create_epub_container($opffile)>

Creates the XML file META-INF/container.xml pointing to the
specified OPF file.

Creates the META-INF directory if necessary.  Will destroy any
non-directory file named 'META-INF' in the current directory.  If
META-INF/container.xml already exists, it will rename that file to
META-INF/container.xml.backup.

=head3 Arguments

=over

=item $opffile

The OPF filename (and path, if necessary) to use in the container.  If
not specified, looks for a sole OPF file in the current working
directory.  Fails if more than one is found.

=back

=head3 Return values

=over

=item Returns a twig representing the container data if successful, undef
otherwise

=back

=cut

sub create_epub_container
{
    my ($opffile) = @_;
    my $subname = ( caller(0) )[3];
    debug(2,"DEBUG[",$subname,"]");

    my $twig;
    my $twigroot;
    my $rootfiles;
    my $element;
    my $fh_container;

    if($opffile eq '') { return; }

    if(-e 'META-INF')
    {
	if(! -d 'META-INF')
	{
	    unlink('META-INF') or return;
	    mkdir('META-INF') or return;
	}
    }
    else { mkdir('META-INF') or return; }

    $twig = XML::Twig->new(
	output_encoding => 'utf-8',
	pretty_print => 'record'
	);

    $element = XML::Twig::Elt->new('container');
    $element->set_att('version' => '1.0',
		      'xmlns' => 'urn:oasis:names:tc:opendocument:xmlns:container');
    $twig->set_root($element);
    $twigroot = $twig->root;

    $rootfiles = $twigroot->insert_new_elt('first_child','rootfiles');
    $element = $rootfiles->insert_new_elt('first_child','rootfile');
    $element->set_att('full-path',$opffile);
    $element->set_att('media-type','application/oebps-package+xml');


    # Backup existing file
    if(-e 'META-INF/container.xml')
    {
        rename('META-INF/container.xml','META-INF/container.xml.backup')
            or croak($subname,"(): could not backup container.xml!");
    }

    # Twig handles utf-8 on its own.  Setting binmode :utf8 here will
    # cause a double-conversion.
    open($fh_container,'>','META-INF/container.xml')
        or croak($subname,"(): could not write to 'META-INF/container.xml'\n");
    $twig->print(\*$fh_container);
    close($fh_container)
        or croak($subname,"(): could not close 'META-INF/container.xml'\n");
    return $twig;
}


=head2 C<create_epub_mimetype()>

Creates a file named 'mimetype' in the current working directory
containing 'application/epub+zip' (no trailing newline)

Destroys and overwrites that file if it exists.

Returns the mimetype string if successful, undef otherwise.

=cut

sub create_epub_mimetype
{
    my $subname = ( caller(0) )[3];
    debug(2,"DEBUG[",$subname,"]");

    my $mimetype = "application/epub+zip";
    my $fh_mimetype;

    open($fh_mimetype,">",'mimetype') or return;
    print {*$fh_mimetype} $mimetype;
    close($fh_mimetype) or croak($subname,"(): failed to close filehandle [$!]");

    return $mimetype;
}


=head2 C<debug($level,@message)>

Prints a debugging message to C<STDERR> if package variable C<$debug>
is greater than or equal to C<$level>.  A trailing newline is
appended, and should not be part of @message.

Returns true or dies.

=cut

sub debug
{
    my ($level,@message) = @_;
    my $subname = ( caller(0) )[3];
    croak($subname,"(): no debugging level specified") unless($level);
    croak($subname,"(): invalid debugging level '",$level,"'")
        unless( $level =~ /^\d$/ );
    croak($subname,"(): no message specified") unless(@message);
    print {*STDERR} @message,"\n" if($debug >= $level);
    return 1;
}


=head2 C<excerpt_line($text)>

Takes as an argument a list of text pieces that will be joined.  If
the joined length is less than 70, all of the joined text is returned.

If the joined length is greater than 70, the return string is the
first 30 characters followed by C<' [...] '> followed by the last 30
characters.

=cut

sub excerpt_line
{
    my @parts = @_;
    my $subname = ( caller(0) )[3];
    my $text = join('',@parts);
    if(length($text) > 70)
    {
        $text =~ /^ (.{30}) .*? (.{30}) $/sx;
        return ($1 . ' [...] ' . $2);
    }
    else { return $text; }
}


=head2 C<find_in_path($pattern,@extradirs)>

Searches through C<$ENV{PATH}> (and optionally any additional
directories specified in C<@extradirs>) for the first regular file
matching C<$pattern>.  C<$pattern> itself can take two forms: if
passed a C<qr//> regular expression, that expression is used directly.
If passed any other string, that string will be used for a
case-insensitive exact match where the extension '.bat', '.com', or
'.exe' is optional (i.e. the final pattern will be
C<qr/^ $pattern (\.bat|\.com|\.exe)? $/ix>).

Returns the first match found, or undef if there were no matches or if
no pattern was specified.

=cut

sub find_in_path
{
    my ($pattern,@extradirs) = @_;
    return unless($pattern);
    my $subname = ( caller(0) )[3];
    debug(3,"DEBUG[",$subname,"]");

    my $regexp;
    my @dirs;
    my $fh_dir;
    my @filelist;
    my $envsep = ':';
    my $filesep = '/';
    if($OSNAME eq 'MSWin32')
    {
        $envsep = ';';
        $filesep = "\\";
    }

    if(ref($pattern) eq 'Regexp') { $regexp = $pattern; }
    else { $regexp = qr/^ $pattern (\.bat|\.com|\.exe)? $/ix; }

    @dirs = split(/$envsep/,$ENV{PATH});
    unshift(@dirs,@extradirs) if(@extradirs);
    foreach my $dir (@dirs)
    {
        if(-d $dir)
        {
            if(opendir($fh_dir,$dir))
            {
                @filelist = grep { /$regexp/ } readdir($fh_dir);
                @filelist = grep { -f "$dir/$_" } @filelist;
                closedir($fh_dir);

                if(@filelist) { return $dir . $filesep . $filelist[0]; }
            }
        }
    }
    return;
}

=head2 C<find_links($filename)>

Searches through a file for href and src attributes, and returns a
list of unique links with any named anchors removed
(e.g. 'myfile.html#part7' returns as just 'myfile.html').  If no links
are found, or the file does not exist, returns undef.

Does not check to see if the links are local.  Requires that links be
surrounded by double quotes, not single or left bare.  Assumes that
any link will not be broken across multiple lines, so it will (for
example) fail to find:

 <img src=
 "myfile.jpg">

though it can find:

 <img
  src="myfile.jpg">

This also does not distinguish between local files and remote links.

=cut

sub find_links
{
    my ($filename) = @_;
    return unless(-f $filename);
    my $subname = ( caller(0) )[3];
    debug(3,"DEBUG[",$subname,"]");

    my $fh;
    my %linkhash;
    my @links;

    open($fh,'<:raw',$filename)
        or croak($subname,"(): unable to open '",$filename,"'\n");

    while(<$fh>)
    {
        @links = /(?:href|src) \s* = \s* "
                  ([^">]+)/gix;
        foreach my $link (@links)
        {
            # Strip off any named anchors
            $link =~ s/#.*$//;
            next unless($link);
            debug(2, "DEBUG: found link '",$link,"'");
            $linkhash{$link}++;
        }
    }
    if(%linkhash) { return keys(%linkhash); }
    else { return; }
}


=head2 C<find_opffile()>

Attempts to locate an OPF file, first by calling
L</get_container_rootfile()> to check the contents of
C<META-INF/container.xml>, and then by looking for a single file with
the extension C<.opf> in the current working directory.

Returns the filename of the OPF file, or undef if nothing was found.

=cut

sub find_opffile
{
    my $subname = ( caller(0) )[3];
    my $opffile = get_container_rootfile();

    if(!$opffile)
    {
	my @candidates = glob("*.opf");
        if(scalar(@candidates) > 1)
        {
            debug(1,"DEBUG: Multiple OPF files found, but no container",
                  " to specify which one to choose!");
            return;
        }
        if(scalar(@candidates) < 1)
        {
            debug(1,"DEBUG: No OPF files found!");
            return;
        }
        $opffile = $candidates[0];
    }
    return $opffile;
}


=head2 C<fix_datestring($datestring)>

Takes a date string and attempts to convert it to the limited subset
of ISO8601 allowed by the OPF standard (YYYY, YYYY-MM, or YYYY-MM-DD).

In the special case of finding MM/DD/YYYY, it assumes that it was a
Mobipocket-mangled date, and not only converts it, but will strip the
day information if the day is '01', and both the month and day
information if both month and day are '01'.  This is because
Mobipocket Creator enforces a complete MM/DD/YYYY even if the month
and day aren't known, and it is common practice to use 01 for an
unknown value.

=head3 Arguments

=over

=item $datestring

A date string in a format recognizable by Date::Manip

=back

=head3 Returns $fixeddate

=over

=item $fixeddate : the corrected string, or undef on failure

=back

=cut

sub fix_datestring
{
    my ($datestring) = @_;
    return unless($datestring);
    my $subname = ( caller(0) )[3];
    debug(2,"DEBUG[",$subname,"]");

    my $date;
    my ($year,$month,$day);
    my $fixeddate;

    $_ = $datestring;

    debug(3,"DEBUG: checking M(M)/D(D)/YYYY");
    if(( ($month,$day,$year) = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/x ) == 3)
    {
	# We have a XX/XX/XXXX datestring
	debug(3,"DEBUG: found '",$month,"/",$day,"/",$year,"'");
	($year,$month,$day) = ymd_validate($year,$month,$day);
	if($year)
	{
	    $fixeddate = $year;
	    $fixeddate .= sprintf("-%02u",$month)
		unless( ($month == 1) && ($day == 1) );
	    $fixeddate .= sprintf("-%02u",$day) unless($day == 1);
	    debug(3,"DEBUG: returning '",$fixeddate,"'");
	    return $fixeddate;
	}
    }

    debug(3,"DEBUG: checking M(M)/YYYY");
    if(( ($month,$year) = /^(\d{1,2})\/(\d{4})$/x ) == 2)
    {
	# We have a XX/XXXX datestring
	debug(3,"DEBUG: found '",$month,"/",$year,"'");
	if($month <= 12)
	{
	    # We probably have MM/YYYY
	    $fixeddate = sprintf("%04u-%02u",$year,$month);
	    debug(3,"DEBUG: returning '",$fixeddate,"'");
	    return $fixeddate;
	}
    }

    # These regexps will reduce '2009-xx-01' to just 2009
    # We don't want this, so don't use them.
#    ($year,$month,$day) = /(\d{4})-?(\d{2})?-?(\d{2})?/;
#    ($year,$month,$day) = /(\d{4})(?:-?(\d{2})-?(\d{2}))?/;

    # Force exact match)
    debug(3,"DEBUG: checking YYYY-MM-DD");
    ($year,$month,$day) = /^(\d{4})-(\d{2})-(\d{2})$/x;
    ($year,$month,$day) = ymd_validate($year,$month,$day);

    if(!$year)
    {
	debug(3,"DEBUG: checking YYYYMMDD");
	($year,$month,$day) = /^(\d{4})(\d{2})(\d{2})$/x;
	($year,$month,$day) = ymd_validate($year,$month,$day);
    }

    if(!$year)
    {
	debug(3,"DEBUG: checking YYYY-M(M)");
	($year,$month) = /^(\d{4})-(\d{1,2})$/x;
	($year,$month) = ymd_validate($year,$month,undef);
    }

    if(!$year)
    {
	debug(3,"DEBUG: checking YYYY");
	($year) = /^(\d{4})$/x;
    }

    # At this point, we've exhausted all of the common cases.  We use
    # Date::Manip to hit all of the unlikely ones as well.  This comes
    # with a drawback: Date::Manip doesn't distinguish between 2008
    # and 2008-01-01, but we should have covered that above.
    #
    # Note that Date::Manip will die on MS Windows system unless the
    # TZ environment variable is set in a specific manner.
    # See:
    # http://search.cpan.org/perldoc?Date::Manip#TIME_ZONES

    if(!$year)
    {
	$date = ParseDate($datestring);
	$year = UnixDate($date,"%Y");
	$month = UnixDate($date,"%m");
	$day = UnixDate($date,"%d");
	debug(2,"DEBUG: Date::Manip found '",UnixDate($date,"%Y-%m-%d"),"'");
    }

    if($year)
    {
	# If we still have a $year, $month and $day either don't exist
	# or are plausibly valid.
	print {*STDERR} "DEBUG: found year=",$year," " if($debug >= 2);
	$fixeddate = sprintf("%04u",$year);
	if($month)
	{
	    print {*STDERR} "month=",$month," " if($debug >= 2);
	    $fixeddate .= sprintf("-%02u",$month);
	    if($day)
	    {
		print {*STDERR} "day=",$day if($debug >= 2);
		$fixeddate .= sprintf("-%02u",$day);
	    }
	}
	print {*STDERR} "\n" if($debug >= 2);
	debug(2,"DEBUG: returning '",$fixeddate,"'");
	return $fixeddate if($fixeddate);
    }

    if(!$year)
    {
	debug(3,"fix_date: didn't find a valid date in '",$datestring,"'!");
	return;
    }
    elsif($debug)
    {
	print {*STDERR} "DEBUG: found ",sprintf("04u",$year);
	print {*STDERR} sprintf("-02u",$month) if($month);
	print {*STDERR} sprintf("-02u",$day),"\n" if($day);
    }

    $fixeddate = sprintf("%04u",$year);
    $fixeddate .= sprintf("-%02u-%02u",$month,$day);
    return $fixeddate;
}


=head2 C<get_container_rootfile($container)>

Opens and parses an OPS/epub container, extracting the 'full-path'
attribute of element 'rootfile'

=head3 Arguments

=over

=item $container

The OPS container to parse.  Defaults to 'META-INF/container.xml'

=back

=head3 Return values

=over

=item Returns a string containing the rootfile on success, undef on failure.

=back

=cut

sub get_container_rootfile
{
    my ($container) = @_;
    my $subname = ( caller(0) )[3];
    debug(2,"DEBUG[",$subname,"]");

    my $twig = XML::Twig->new();
    my $rootfile;
    my $retval = undef;

    $container = 'META-INF/container.xml' if(! $container);

    if(-f $container)
    {
	$twig->parsefile($container) or return;
	$rootfile = $twig->root->first_descendant('rootfile');
	return unless($rootfile);
	$retval = $rootfile->att('full-path');
    }
    return $retval;
}


=head2 C<hexstring($bindata)>

Takes as an argument a scalar containing a sequence of binary bytes.
Returns a string converting each octet of the data to its two-digit
hexadecimal equivalent.  There is no leading "0x" on the string.

=cut

sub hexstring
{
    my $data = shift;
    my $subname = ( caller(0) )[3];
    debug(4,"DEBUG[",$subname,"]");

    croak($subname,"(): no data provided")
        unless($data);

    my $byte;
    my $retval = '';
    my $pos = 0;

    while($pos < length($data))
    {
        $byte = unpack("C",substr($data,$pos,1));
        $retval .= sprintf("%02x",$byte);
        $pos++;
    }
    return $retval;
}


=head2 C<print_memory($label)>

Checks /proc/$PID/statm and prints out a line to STDERR showing the
current memory usage.  This is a debugging tool that will likely fail
to do anything useful on a system without a /proc system compatible
with Linux.

=head3 Arguments

=over

=item $label

If defined, will be output along with the memory usage.

=back

Returns 1 on success, undef otherwise.

=cut

sub print_memory
{
    my ($label) = @_;
    my $subname = ( caller(0) )[3];
    debug(2,"DEBUG[",$subname,"]");

    my @mem;
    my $fh_procstatm;

    if(!open($fh_procstatm,"<","/proc/$$/statm"))
    {
	print "[",$label,"]: " if(defined $label);
	print "Couldn't open /proc/$$/statm [$!]\n";
        return;
    }

    @mem = split(/\s+/,<$fh_procstatm>);
    close($fh_procstatm);

    # @mem[0]*4 = size (kb)
    # @mem[1]*4 = resident (kb)
    # @mem[2]*4 = shared (kb)
    # @mem[3] = trs
    # @mem[4] = lrs
    # @mem[5] = drs
    # @mem[6] = dt

    print "Current memory usage";
    print " [".$label."]" if(defined $label);
    print ":  size=",$mem[0]*4,"k";
    print "  resident=",$mem[1]*4,"k";
    print "  shared=",$mem[2]*4,"k\n";
    return 1;
}



=head2 C<split_metadata($metahtmlfile, $metafile)>

Takes a psuedo-HTML containing one or more <metadata>...</metadata>
blocks and splits out the metadata blocks into an XML file ready to be
used as an OPF document.  The input HTML file is rewritten without the
metadata.

If $metafile (or the temporary HTML-only file created during the
split) already exists, it will be moved to filename.backup.

=head3 Arguments

=over

=item C<$metahtmlfile>

The filename of the pseudo-HTML file

=item C<$metafile> (optional)

The filename to write out any extracted metadata.  If not specified,
will default to the basename of $metahtmlfile with '.opf' appended.

=back

Returns the filename the metadata was written to, or undef if no
metadata was found.

=cut

sub split_metadata
{
    my ($metahtmlfile,$metafile) = @_;
    my $subname = ( caller(0) )[3];
    debug(2,"DEBUG[",$subname,"]");

    croak($subname,"(): no input file specified")
        if(!$metahtmlfile);

    croak($subname,"(): input file has zero size")
        if(-z $metahtmlfile);

    my @metablocks;
    my @guideblocks;
    my $htmlfile;

    my ($filebase,$filedir,$fileext);
    my ($fh_metahtml,$fh_meta,$fh_html);

    ($filebase,$filedir,$fileext) = fileparse($metahtmlfile,'\.\w+$');
    $metafile = $filedir . $filebase . ".opf" if(!$metafile);
    $htmlfile = $filedir . $filebase . "-html.html";

    debug(2,"DEBUG: metahtml='",$metahtmlfile,"'  meta='",$metafile,
          "  html='",$htmlfile,"'");

    # Move existing output files to avoid overwriting them
    if(-f $metafile)
    {
        debug(3, "DEBUG: moving metafile '",$metafile,"'");
        croak ($subname,"(): output file '",$metafile,
               "' exists and could not be moved!")
            if(! rename($metafile,"$metafile.backup") );
    }
    if(-f $htmlfile)
    {
        debug(3, "DEBUG: moving htmlfile '",$htmlfile,"'");
        croak ($subname,"(): output file '",$htmlfile,
               "' exists and could not be moved!")
            if(! rename($htmlfile,"$metafile.backup") );
    }

    debug(2,"  splitting '",$metahtmlfile,"'");
    open($fh_metahtml,"<:raw",$metahtmlfile)
	or croak($subname,"(): Failed to open '",$metahtmlfile,"' for reading!");
    open($fh_meta,">:raw",$metafile)
	or croak($subname,"(): Failed to open '",$metafile,"' for writing!");
    open($fh_html,">:raw",$htmlfile)
	or croak($subname,"(): Failed to open '",$htmlfile,"' for writing!");


    # Preload the return value with the OPF headers
    print $fh_meta $utf8xmldec,$oeb12doctype,"<package>\n";
    #print $fh_meta $utf8xmldec,$opf20package;

    # Finding and removing all of the metadata requires that the
    # entire thing be handled as one slurped string, so temporarily
    # undefine the perl delimiter
    #
    # Since multiple <metadata> sections may be present, cannot use
    # </metadata> as a delimiter.
    local $/;
    while(<$fh_metahtml>)
    {
        s/\sfilepos=\d+//gix;
	(@metablocks) = m#(<metadata>.*</metadata>)#gisx;
	(@guideblocks) = m#(<guide>.*</guide>)#gisx;
	last unless(@metablocks || @guideblocks);
	print {*$fh_meta} @metablocks,"\n" if(@metablocks);
	print {*$fh_meta} @guideblocks,"\n" if(@guideblocks);
	s#<metadata>.*</metadata>##gisx;
	s#<guide>.*</guide>##gisx;
	print {*$fh_html} $_,"\n";
    }
    print $fh_meta "</package>\n";

    close($fh_html)
        or croak($subname,"(): Failed to close '",$htmlfile,"'!");
    close($fh_meta)
        or croak($subname,"(): Failed to close '",$metafile,"'!");
    close($fh_metahtml)
        or croak($subname,"(): Failed to close '",$metahtmlfile,"'!");

    if( (-z $htmlfile) && (-z $metafile) )
    {
        croak($subname,"(): ended up with no text in any output file",
              " -- bailing out!");
    }

    # It is very unlikely that split_metadata will be called twice
    # from the same program, so undef all capture variables reclaim
    # the memory.  Just going out of scope will not necessarily do
    # this.
    undef(@metablocks);
    undef(@guideblocks);
    undef($_);

    if(-z $htmlfile)
    {
        debug(1,"split_metadata(): HTML has zero size.",
             "  Not replacing original.");
        unlink($htmlfile);
    }
    else
    {
        rename($htmlfile,$metahtmlfile)
            or croak("split_metadata(): Failed to rename ",$htmlfile,
                     " to ",$metahtmlfile,"!\n");
    }

    if(-z $metafile)
    {
        croak($subname,
              "(): unable to remove empty output file '",$metafile,"'!")
            if(! unlink($metafile) );
        return;
    }
    return $metafile;
}


=head2 C<split_pre($htmlfile,$outfilebase)>

Splits <pre>...</pre> blocks out of a source HTML file into their own
separate HTML files including required headers.  Each block will be
written to its own file following the naming format
C<$outfilebase-###.html>, where ### is a three-digit number beginning
at 001 and incrementing for each block found.  If C<$outfilebase> is
not specified, it defaults to the basename of C<$htmlfile> with
"-pre-###.html" appended.  The

Returns a list containing all filenames created.

=cut

sub split_pre
{
    my ($htmlfile,$outfilebase) = @_;
    my $subname = ( caller(0) )[3];
    debug(2,"DEBUG[",$subname,"]");

    croak($subname,"(): no input file specified")
        if(!$htmlfile);

    my ($filebase,$filedir,$fileext);
    my ($fh_html,$fh_htmlout,$fh_pre);
    my $htmloutfile;
    my @preblocks;
    my @prefiles = ();
    my $prefile;
    my $count = 0;

    my $htmlheader = <<'END';
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title></title>
</head>
<body>
END

    ($filebase,$filedir,$fileext) = fileparse($htmlfile,'\.\w+$');
    $outfilebase = "$filebase-pre" if(!$outfilebase);
    $htmloutfile = "$filebase-nopre.html";

    open($fh_html,"<:raw",$htmlfile)
	or croak($subname,"(): Failed to open '",$htmlfile,"' for reading!");
    open($fh_htmlout,">:raw",$htmloutfile)
        or croak($subname,"(): Failed to open '",$htmloutfile,"' for writing!");

    local $/;
    while(<$fh_html>)
    {
	(@preblocks) = /(<pre>.*?<\/pre>)/gisx;
	last unless(@preblocks);

        foreach my $pre (@preblocks)
        {
            $count++;
            debug(1,"DEBUG: split_pre() splitting block ",
                  sprintf("%03d",$count));
            $prefile = sprintf("%s-%03d.html",$outfilebase,$count);
            if(-f $prefile)
            {
                rename($prefile,"$prefile.backup")
                    or croak("Unable to rename '",$prefile,
                             "' to '",$prefile,".backup'");
            }
            open($fh_pre,">:raw",$prefile)
                or croak("Unable to open '",$prefile,"' for writing!");
            print {*$fh_pre} $utf8xmldec;
            print {*$fh_pre} $htmlheader,"\n";
            print {*$fh_pre} $pre,"\n";
            print {*$fh_pre} "</body>\n</html>\n";
            close($fh_pre) or croak("Unable to close '",$prefile,"'!");
            push @prefiles,$prefile;
        }
	s/(<pre>.*?<\/pre>)//gisx;
	print {*$fh_htmlout} $_,"\n";
        close($fh_htmlout)
            or croak($subname,"(): Failed to close '",$htmloutfile,"'!");
        rename($htmloutfile,$htmlfile)
            or croak($subname,"(): Failed to rename '",$htmloutfile,"' to '",
                     $htmlfile,"'!");
    }
    return @prefiles;
}


=head2 C<strip_script(%args)>

Strips any <script>...</script> blocks out of a HTML file.

=head3 Arguments

=over

=item C<infile>

Specifies the input file.  If not specified, the sub croaks.

=item C<outfile>

Specifies the output file.  If not specified, it defaults to C<infile>
(i.e. the input file is overwritten).

=item C<noscript>

If set to true, the sub will strip <noscript>...</noscript> blocks as
well.

=back

=cut

sub strip_script
{
    my %args = @_;
    my $subname = ( caller(0) )[3];
    debug(2,"DEBUG[",$subname,"]");

    croak($subname,"(): no input file specified")
        if(!$args{infile});

    my %valid_args = (
        'infile'  => 1,
        'outfile' => 1,
        'noscript' => 1,
        );
    foreach my $arg (keys %args)
    {
        croak($subname,"(): invalid argument '",$arg,"'")
            if(!$valid_args{$arg});
    }

    my $infile = $args{infile};
    my $outfile = $args{outfile};
    $outfile = $infile unless($outfile);

    my ($fh_in,$fh_out);
    my $html;
    local $/;

    open($fh_in,"<:raw",$infile)
	or croak($subname,"(): Failed to open '",$infile,"' for reading!\n");
    $html = <$fh_in>;
    close($fh_in)
	or croak($subname,"(): Failed to close '",$infile,"'!\n");

    $html =~ s#<script>.*?</script>\n?##gix;
    $html =~ s#<noscript>.*?</noscript>\n?##gix
        if($args{noscript});

    open($fh_out,">:raw",$outfile)
	or croak($subname,"(): Failed to open '",$outfile,"' for writing!\n");
    print {*$fh_out} $html;
    close($fh_out)
	or croak($subname,"(): Failed to close '",$outfile,"'!\n");

    return 1;
}


=head2 C<system_tidy_xhtml($infile,$outfile)>

Runs tidy on a XHTML file semi-safely (using a secondary file)

Converts HTML to XHTML if necessary

=head3 Arguments

=over

=item $infile

The filename to tidy

=item $outfile

The filename to use for tidy output if the safety condition to
overwrite the input file isn't met.

Defaults to C<infile-tidy.ext> if not specified.

=back

=head3 Global variables used

=over

=item $tidycmd

the location of the tidy executable

=item $tidyxhtmlerrors

the filename to use to output errors

=item $tidysafety

the safety factor to use (see CONFIGURABLE GLOBAL VARIABLES, above)

=back

=head3 Return Values

Returns the return value from tidy

=over

=item 0 - no errors

=item 1 - warnings only

=item 2 - errors

=item Dies horribly if the return value is unexpected

=back

=cut

sub system_tidy_xhtml
{
    my ($infile,$outfile) = @_;
    my $retval;

    croak("system_tidy_xhtml called with no input file") if(!$infile);
    if(!$outfile)
    {
        my ($filebase,$filedir,$fileext) = fileparse($infile,'\.\w+$');
        $outfile = $filebase . "-tidy" . $fileext;
    }
    croak("system_tidy_xhtml called with no output file") if(!$outfile);

    $retval = system($tidycmd,
		     '-q','-utf8','--tidy-mark','no',
                     '--wrap','0',
                     '--clean','yes',
		     '-asxhtml',
                     '--output-xhtml','yes',
                     '--add-xml-decl','yes',
		     '--doctype','transitional',
		     '-f',$tidyxhtmlerrors,
		     '-o',$outfile,
		     $infile);

    # Some systems may return a two-byte code, so deal with that first
    if($retval >= 256) { $retval = $retval >> 8 };
    if($retval == 0)
    {
	rename($outfile,$infile) if($tidysafety < 4);
	unlink($tidyxhtmlerrors);
    }
    elsif($retval == 1)
    {
	rename($outfile,$infile) if($tidysafety < 3);
	unlink($tidyxhtmlerrors) if($tidysafety < 2);
    }
    elsif($retval == 2)
    {
	print {*STDERR} "WARNING: Tidy errors encountered.  Check ",$tidyxhtmlerrors,"\n"
	    if($tidysafety > 0);
	unlink($tidyxhtmlerrors) if($tidysafety < 1);
    }
    else
    {
	# Something unexpected happened (program crash, sigint, other)
	croak("Tidy did something unexpected (return value=",$retval,
              ").  Check all output.");
    }
    return $retval;
}


=head2 C<system_tidy_xml($infile,$outfile)>

Runs tidy on an XML file semi-safely (using a secondary file)

=head3 Arguments

=over

=item C<$infile>

The filename to tidy

=item C<$outfile> (optional)

The filename to use for tidy output if the safety condition to
overwrite the input file isn't met.

Defaults to C<infile-tidy.ext> if not specified.

=back

=head3 Global variables used

=over

=item C<$tidycmd>

the name of the tidy executable

=item C<$tidyxmlerrors>

the filename to use to output errors

=item C<$tidysafety>

the safety factor to use (see CONFIGURABLE GLOBAL VARIABLES, above)

=back

=head3 Return values

Returns the return value from tidy

=over

=item 0 - no errors

=item 1 - warnings only

=item 2 - errors

=item Dies horribly if the return value is unexpected

=back

=cut

sub system_tidy_xml
{
    my ($infile,$outfile) = @_;
    my $retval;

    croak("system_tidy_xml called with no input file") if(!$infile);

    if(!$outfile)
    {
        my ($filebase,$filedir,$fileext) = fileparse($infile,'\.\w+$');
        $outfile = $filebase . "-tidy" . $fileext;
    }
    croak("system_tidy_xml called with no output file") if(!$outfile);

    $retval = system($tidycmd,
		     '-q','-utf8','--tidy-mark','no',
                     '--wrap','0',
		     '-xml',
                     '--add-xml-decl','yes',
		     '-f',$tidyxmlerrors,
		     '-o',$outfile,
		     $infile);

    # Some systems may return a two-byte code, so deal with that first
    if($retval >= 256) { $retval = $retval >> 8 };
    if($retval == 0)
    {
	rename($outfile,$infile) if($tidysafety < 4);
	unlink($tidyxmlerrors);
    }
    elsif($retval == 1)
    {
	rename($outfile,$infile) if($tidysafety < 3);
	unlink($tidyxmlerrors) if($tidysafety < 2);
    }
    elsif($retval == 2)
    {
	print STDERR "WARNING: Tidy errors encountered.  Check ",$tidyxmlerrors,"\n"
	    if($tidysafety > 0);
	unlink($tidyxmlerrors) if($tidysafety < 1);
    }
    else
    {
	# Something unexpected happened (program crash, sigint, other)
	croak("Tidy did something unexpected (return value=",$retval,
              ").  Check all output.");
    }
    return $retval;
}


=head2 C<trim>

Removes any whitespace characters from the beginning or end of every
string in @list (also works on scalars).

 trim;               # trims $_ inplace
 $new = trim;        # trims (and returns) a copy of $_
 trim $str;          # trims $str inplace
 $new = trim $str;   # trims (and returns) a copy of $str
 trim @list;         # trims @list inplace
 @new = trim @list;  # trims (and returns) a copy of @list

This was shamelessly copied from japhy's example at perlmonks.org:

http://www.perlmonks.org/?node_id=36684

If needed for large lists, it would probably be better to use
String::Strip.

=cut

sub trim   ## no critic (Always unpack @_ first)
{
    ## no critic (Comma used to separate statements)
    @_ = $_ if not @_ and defined wantarray;
    @_ = @_ if defined wantarray;
    for ( @_ ? @_ : $_ ) { s/^\s+//, s/\s+$// }
    return wantarray ? @_ : $_[ 0 ] if defined wantarray;
}


=head2 C<twigelt_create_uuid($gi)>

Creates an unlinked element with the specified gi (tag), and then
assigns it the id and scheme attributes 'UUID'.

=head3 Arguments

=over

=item  $gi : The gi (tag) to use for the element

Default: 'dc:identifier'

=back

Returns the element.

=cut

sub twigelt_create_uuid
{
    my ($gi) = @_;
    my $subname = ( caller(0) )[3];
    debug(2,"DEBUG[",$subname,"]");
    my $element;

    if(!$gi) { $gi = 'dc:identifier'; }

    my $uuidgen = Data::UUID->new();
    $element = XML::Twig::Elt->new($gi);
    $element->set_id('UUID');
    $element->set_att('scheme' => 'UUID');
    $element->set_text($uuidgen->create_str());
    return $element;
}


=head2 C<twigelt_detect_duplicate($element1, $element2)>

Takes two twig elements and returns 1 if they have the same GI (tag),
text, and attributes, but are not actually the same element.  The GI
comparison is case-insensitive.  The others are case-sensitive.

Returns 0 otherwise.

Croaks if passed anything but twig elements.

=cut

sub twigelt_detect_duplicate
{
    my ($element1,$element2) = @_;
    my $subname = ( caller(0) )[3];
    debug(3,"DEBUG[",$subname,"]");

    croak($subname,"(): arguments must be XML::Twig::Elt objects")
        unless( $element1->isa('XML::Twig::Elt')
                && $element2->isa('XML::Twig::Elt') );

    my (%atts1, %atts2);

    unless($element1->cmp($element2))
    {
        debug(3,"  both elements have the same position");
        return 0;
    }

    unless( lc($element1->gi) eq lc($element2->gi) )
    {
        debug(3,"  elements have different GIs");
        return 0;
    }

    unless($element1->text eq $element2->text)
    {
        debug(3,"  elements have different text");
        return 0;
    }

    %atts1 = %{$element1->atts};
    %atts2 = %{$element2->atts};

    my $attkeys1 = join('',sort keys %atts1);
    my $attkeys2 = join('',sort keys %atts2);

    # This is much simpler with the ~~ operator, but Perl 5.10
    # features are being avoided until 5.10 is standard both on MacOSX
    # and Debian
    # Note that the ~~ operator only checks keys of hashes, not values
#    unless(%atts1 ~~ %atts2)
    unless($attkeys1 eq $attkeys2)
    {
        debug(3,"  elements have different attributes");
        return 0;
    }

    foreach my $att (keys %atts1)
    {
        unless($element1->att($att) eq $element2->att($att))
        {
            debug(3,"  elements have different values for attribute '",
                  $att,"'");
            return 0;
        }
    }
    debug(3,"  elements are duplicates of each other!");
    return 1;
}

=head2 C<twigelt_fix_oeb12_atts($element)>

Checks the attributes in a twig element to see if they match OPF names
with an opf: namespace, and if so, removes the namespace.  Used by the
fix_oeb12() method.

Takes as a sole argument a twig element.

Returns that element with the modified attributes, or undef if the
element didn't exist.  Returns an unmodified element if both att and
opf:att exist.

=cut

sub twigelt_fix_oeb12_atts
{
    my ($element) = @_;
    return unless($element);
    my $subname = ( caller(0) )[3];
    debug(3,"DEBUG[",$subname,"]");

    my %opfatts_no_ns = (
        "opf:role" => "role",
        "opf:file-as" => "file-as",
        "opf:scheme" => "scheme",
        "opf:event" => "event"
        );

    foreach my $att ($element->att_names)
    {
        debug(3,"DEBUG:   checking attribute '",$att,"'");
        if($opfatts_no_ns{$att})
        {
            # If the opf:att attribute properly exists already, do nothing.
            if($element->att($opfatts_no_ns{$att}))
            {
                debug(1,"DEBUG:   found both '",$att,"' and '",
                      $opfatts_no_ns{$att},"' -- skipping.");
                next;
            }
            debug(1,"DEBUG:   changing attribute '",$att,"' => '",
                  $opfatts_no_ns{$att},"'");
            $element->change_att_name($att,$opfatts_no_ns{$att});
        }
    }
    return $element;
}


=head2 C<twigelt_fix_opf20_atts($element)>

Checks the attributes in a twig element to see if they match OPF
names, and if so, prepends the OPF namespace.  Used by the fix_opf20()
method.

Takes as a sole argument a twig element.

Returns that element with the modified attributes, or undef if the
element didn't exist.

=cut

sub twigelt_fix_opf20_atts
{
    my ($element) = @_;
    return unless($element);
    my $subname = ( caller(0) )[3];
    debug(2,"DEBUG[",$subname,"]");

    my %opfatts_ns = (
        "role" => "opf:role",
        "file-as" => "opf:file-as",
        "scheme" => "opf:scheme",
        "event" => "opf:event"
        );

    foreach my $att ($element->att_names)
    {
        debug(2,"DEBUG:   checking attribute '",$att,"'");
        if($opfatts_ns{$att})
        {
            # If the opf:att attribute properly exists already, do nothing.
            if($element->att($opfatts_ns{$att}))
            {
                debug(1,"DEBUG:   found both '",$att,"' and '",
                      $opfatts_ns{$att},"' -- skipping.");
                next;
            }
            debug(1,"DEBUG:   changing attribute '",$att,"' => '",
                  $opfatts_ns{$att},"'");
            $element->change_att_name($att,$opfatts_ns{$att});
        }
    }
    return $element;
}


=head2 C<twigelt_is_author($element)>

Takes as an argument a twig element.  Returns true if the element is a
dc:creator (case-insensitive) with either a opf:role="aut" or
role="aut" attribute defined.  Returns undef otherwise, and also if
the element has no text.

Croaks if fed no argument, or fed an argument that isn't a twig
element.

Intended to be used as a twig search condition.

=head3 Example

 my @elements = $ebook->twigroot->descendants(\&twigelt_is_author);

=cut

sub twigelt_is_author
{
    my ($element) = @_;
    my $subname = ( caller(0) )[3];
    debug(3,"DEBUG[",$subname,"]");

    croak($subname,"(): no element provided") unless($element);

    my $ref = ref($element) || '';

    croak($subname,"(): argument was of type '",$ref,
          "', needs to be 'XML::Twig::Elt' or a subclass")
        unless($element->isa('XML::Twig::Elt'));

    return if( (lc $element->gi) ne 'dc:creator');
    return unless($element->text);

    my $role = $element->att('opf:role') || $element->att('role');
    return unless($role);

    return 1 if($role eq 'aut');
    return;
}


=head2 C<twigelt_is_isbn($element)>

Takes as an argument a twig element.  Returns true if the element is a
dc:identifier (case-insensitive) where any of the id, opf:scheme, or
scheme attributes start with 'isbn', '-isbn', 'eisbn', or 'e-isbn'
(again case-insensitive).

Returns undef otherwise, and also if the element has no text.

Croaks if fed no argument, or fed an argument that isn't a twig
element.

Intended to be used as a twig search condition.

=head3 Example

 my @elements = $ebook->twigroot->descendants(\&twigelt_is_isbn);

=cut

sub twigelt_is_isbn
{
    my ($element) = @_;
    my $subname = ( caller(0) )[3];
    debug(3,"DEBUG[",$subname,"]");

    croak($subname,"(): no element provided") unless($element);

    my $ref = ref($element) || '';
    my $id;
    my $scheme;

    croak($subname,"(): argument was of type '",$ref,
          "', needs to be 'XML::Twig::Elt' or a subclass")
        unless($element->isa('XML::Twig::Elt'));

    return if( (lc $element->gi) ne 'dc:identifier');
    return unless($element->text);

    $id = $element->id || '';
    return 1 if($id =~ /^e?-?isbn/ix);

    $scheme = $element->att('opf:scheme') || '';
    return 1 if($scheme =~ /^e?-?isbn/ix);
    $scheme = $element->att('scheme') || '';
    return 1 if($scheme =~ /^e?-?isbn/ix);
    return;
}


=head2 C<twigelt_is_knownuid($element)>

Takes as an argument a twig element.  Returns true if the element is a
dc:identifier (case-insensitive) element with an C<id> attribute
matching the known IDs of proper unique identifiers suitable for a
package-id (also case-insensitive).  Returns undef otherwise.

Croaks if fed no argument, or fed an argument that isn't a twig element.

Intended to be used as a twig search condition.

=head3 Example

 my @elements = $ebook->twigroot->descendants(\&twigelt_is_knownuid);

=cut

sub twigelt_is_knownuid
{
    my ($element) = @_;
    my $subname = ( caller(0) )[3];
    debug(3,"DEBUG[",$subname,"]");

    croak($subname,"(): no element provided") unless($element);

    my $ref = ref($element) || '';

    croak($subname,"(): argument was of type '",$ref,
          "', needs to be 'XML::Twig::Elt' or a subclass")
        unless($element->isa('XML::Twig::Elt'));

    return if( (lc $element->gi) ne 'dc:identifier');
    my $id = $element->id;
    return unless($id);

    my %knownuids = (
        'package-id' => 56,
        'overdriveguid' => 48,
        'guid' => 40,
        'uuid' => 32,
        'uid'  => 24,
        'calibre_id' => 16,
        'fwid' => 8,
        );

    if($knownuids{lc $id})
    {
#        debug(2,"DEBUG: '",$element->gi,"' has known UID '",$id,"'");
        return 1;
    }
    return;
}


=head2 C<usedir($dir)>

Changes the current working directory to the one specified, creating
it if necessary.

Returns the current working directory before the change.  If no
directory is specified, returns the current working directory without
changing anything.

Croaks on any failure.

=cut

sub usedir
{
    my ($dir) = @_;
    my $subname = ( caller(0) )[3];
    debug(2,"DEBUG[",$subname,"]");

    my $cwd = getcwd();
    return $cwd unless($dir);

    unless(-d $dir)
    {
        debug(2,"  Creating directory '",$dir,"'");
        mkpath($dir)
            or croak("Unable to create output directory '",$dir,"'!\n");
    }
    chdir($dir)
        or croak("Unable to change working directory to '",$dir,"'!\n");
    return $cwd;
}


=head2 C<userconfigdir()>

Returns the directory in which user configuration files and helper
programs are expected to be found, creating that directory if it does
not exist.  Typically, this directory is C<"$ENV{HOME}/.ebooktools">,
but on MSWin32 systems if that directory does not already exist,
C<"$ENV{USERPROFILE}/ApplicationData/EBook-Tools"> is returned (and
potentially created) instead.

If C<$ENV{HOME}> (and C<$ENV{USERPROFILE}> on MSWin32) are not set, the
sub returns undef.

=cut

sub userconfigdir
{
    my $subname = ( caller(0) )[3];
    debug(3,"DEBUG[",$subname,"]");

    my $dir;
    $dir = $ENV{HOME} . '/.ebooktools' if($ENV{HOME});
    if($OSNAME eq 'MSWin32')
    {
        if(! -d $dir)
        {
            $dir = $ENV{USERPROFILE} . '\Application Data\EBook-Tools'
                if($ENV{USERPROFILE});
        }
    }
    if($dir)
    {
        if(! -d $dir)
        {
            mkpath($dir)
                or croak($subname,
                         "(): unable to create configuration directory '",
                         $dir,"'!\n");
        }
        return $dir;
    }
    else { return; }
}


=head2 C<ymd_validate($year,$month,$day)>

Make sure month and day have valid values.  Return the passed values
if they are, return 3 undefs if not.  Testing of month or day can be
skipped by passing undef in that spot.

=cut

sub ymd_validate
{
    my ($year,$month,$day) = @_;

    return (undef,undef,undef) unless($year);

    if($month)
    {
	return (undef,undef,undef) if($month > 12);
	if($day)
	{
	    if(!eval { timelocal(0,0,0,$day,$month-1,$year); })
	    {
		debug(1,"DEBUG: timelocal validation failed for year=",
                      $year," month=",$month," day=",$day);
		return (undef,undef,undef);
	    }
	}
	return ($year,$month,$day);
    }

    # We don't have a month.  If we *do* have a day, the result is
    # broken, so send back the undefs.
    return (undef,undef,undef) if($day);
    return ($year,undef,undef);
}


########## END CODE ##########

=head1 BUGS AND LIMITATIONS

=over

=item * need to implement fix_primary_author() to convert names to
standard 'last, first' naming format

=item * fix_links() could be improved to download remote URIs instead
of ignoring them.

=item * fix_links() needs to check the <reference> links under <guide>

=item * fix_links() needs to be redone with HTML::TreeBuilder to avoid
the weakness with newlines between attribute names and values

=item * Need to implement fix_tours() that should collect the related
elements and delete the parent if none are found.  Empty <tours>
elements aren't allowed.

=item * fix_languages() needs to convert language names into IANA
language codes.

=item * set_language() should add a warning if the text isn't a valid
IANA language code.

=item * NCX generation only generates from the spine.  It should be
possible to use a TOC html file for generation instead.  In the long
term, it should be possible to generate one from the headers and
anchors in arbitrary HTML files.

=item * It might be better to use sysread / index / substr / syswrite in
&split_metadata to handle the split in 10k chunks, to avoid massive
memory usage on large files.

This may not be worth the effort, since the average size for most
books is less than 500k, and the largest books are rarely over 10M.

=item * The only generator is currently for .epub books.  PDF,
PalmDoc, Mobipocket, Plucker, and iSiloX are eventually planned.

=item * Although I like keeping warnings associated with the ebook
object, it may be better to throw exceptions on errors and catch them
later.  This probably won't be implemented until it bites someone who
complains, though.

=item * Unit tests are incomplete

=back

=head1 AUTHOR

Zed Pobre <zed@debian.org>

=head1 LICENSE AND COPYRIGHT

Copyright 2008 Zed Pobre

Licensed to the public under the terms of the GNU GPL, version 2

=cut

1;