summaryrefslogtreecommitdiffstats
path: root/cache.h
diff options
context:
space:
mode:
authorBreno Leitao <leitao@linux.vnet.ibm.com>2009-09-16 14:37:16 -0400
committerJosh Stone <jistone@redhat.com>2009-09-16 14:17:54 -0700
commit7a4c89f77923782e5e387e472608fe25a8bb8eab (patch)
tree48cd70239afb61e7f84e162acecfc298e86004f7 /cache.h
parent53e5699fe863f0a122c73782b4465296e3adc131 (diff)
downloadsystemtap-steved-7a4c89f77923782e5e387e472608fe25a8bb8eab.tar.gz
systemtap-steved-7a4c89f77923782e5e387e472608fe25a8bb8eab.tar.xz
systemtap-steved-7a4c89f77923782e5e387e472608fe25a8bb8eab.zip
A basic test to assure that networking tapset is building ok
This is a basic script to assure that the network devices tapset is building (-p4) properly. This script is basically a copy of another netdev example that is located on testsuite/systemtap.examples/network/netdev.stp Signed-off-by: Josh Stone <jistone@redhat.com>
Diffstat (limited to 'cache.h')
0 files changed, 0 insertions, 0 deletions
id='n111' href='#n111'>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
/*
|  Copyright (C) 2002-2007 Jorg Schuler <jcsjcs at users sourceforge net>
|  Part of the gtkpod project.
| 
|  URL: http://www.gtkpod.org/
|  URL: http://gtkpod.sourceforge.net/
|
|  Much of the code in this file has originally been ported from the
|  perl script "mktunes.pl" (part of the gnupod-tools collection)
|  written by Adrian Ulrich <pab at blinkenlights.ch>:
|
|  gnupod-tools: http://www.blinkenlights.ch/cgi-bin/fm.pl?get=ipod
|
|  The code contained in this file is free software; you can redistribute
|  it and/or modify it under the terms of the GNU Lesser General Public
|  License as published by the Free Software Foundation; either version
|  2.1 of the License, or (at your option) any later version.
|
|  This file is distributed in the hope that it will be useful,
|  but WITHOUT ANY WARRANTY; without even the implied warranty of
|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
|  Lesser General Public License for more details.
|
|  You should have received a copy of the GNU Lesser General Public
|  License along with this code; if not, write to the Free Software
|  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
|  USA
|
|  iTunes and iPod are trademarks of Apple
|
|  This product is not supported/written/published by Apple!
|
|  $Id$
*/

/* Some notes on how to use the functions in this file:


   *** Reading the iTunesDB ***

   Itdb_iTunesDB *itunesdb_parse (gchar *path); /+ path to mountpoint +/
   will read an Itdb_iTunesDB and pass the data over to your program.

   The information given in the "Play Counts" file is also read if
   available and the playcounts, star rating and the time last played
   is updated.

   Itdb_iTunesDB is a structure containing a GList for the tracks and a
   GList for the playlists.

   For each track these fields are set as follows:

   "transferred" will be set to TRUE because all tracks read from a
   Itdb_iTunesDB are obviously (or hopefully) already transferred to the
   iPod.

   "recent_playcount" is for information only (it will allow to
   generate playlists with tracks played since the last time) and will
   not be stored to the iPod.

   The master playlist is guaranteed to be the first playlist, and
   this must not be changed by your code.


   *** Writing the Itdb_iTunesDB ***

   gboolean itunesdb_write (gchar *path, Itdb_iTunesDB *itb)
   /+ @path to mountpoint, itb to @write +/
   will write an updated version of the Itdb_iTunesDB.

   The "Play Counts" file is renamed to "Play Counts.bak" if it exists
   to avoid reading it multiple times.

   Please note that non-transferred tracks are not automatically
   transferred to the iPod. A function

   gboolean itunesdb_copy_track_to_ipod (gchar *path, Itdb_Track *track, gchar *pcfile)

   is provided to help you do that, however.

   The following functions most likely will be useful:

   Itdb_Track *itunesdb_new_track (void);
   Use itunesdb_new_track() to get an "initialized" track structure
   (the "unknowns" are initialized with reasonable values).

   gboolean itunesdb_cp (gchar *from_file, gchar *to_file);
   void itunesdb_convert_filename_fs2ipod(gchar *ipod_file);
   void itunesdb_convert_filename_ipod2fs(gchar *ipod_file);

   void itunesdb_rename_files (const gchar *dirname);

   (Renames/removes some files on the iPod (Playcounts, OTG
   semaphore). Needs to be called if you write the Itdb_iTunesDB not
   directly to the iPod but to some other location and then manually
   copy the file from there to the iPod. That's much faster in the
   case of using an iPod mounted in sync'ed mode.)

   Jorg Schuler, 29.12.2004 */


/* call itdb_parse () to read the Itdb_iTunesDB  */
/* call itdb_write () to write the Itdb_iTunesDB */


#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include "db-artwork-parser.h"
#include "itdb_device.h"
#include "itdb_private.h"
#include "itdb_sha1.h"

#include <errno.h>
#include <fcntl.h>
#include <glib-object.h>
#include <glib/gi18n-lib.h>
#include <stdio.h>
#include <string.h>
#include <sys/statvfs.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>

#define ITUNESDB_DEBUG 0
#define ITUNESDB_MHIT_DEBUG 0

#define ITUNESDB_COPYBLK (1024*1024*4)      /* blocksize for cp () */


/* NOTE for developers:

   Sometimes new MHOD string fields are added by Apple in the
   iTunesDB. In that case you need to modify the code in the following
   places:

   itdb_itunesdb.c:
   - enum MHOD_ID
   - get_mhod(): inside the switch() statement. Currently no compiler
     warning is given.
   - get_mhod_string(): inside the switch() statement. A compiler warning
     will help you find it.
   - get_playlist(): inside the switch() statement. A compiler warning
     will help you find it.
   - get_mhit(): inside the switch() statement. A compiler warning
     will help you find it.
   - mk_mhod(): inside the switch() statement. A compiler warning
     will help you find it.
   - write_mhsd_tracks(): inside the for() loop.

   itdb_track.c:
   - itdb_track_free()
   - itdb_track_duplicate()

   itdb_playlists.c:
   Analogous to itdb_track.c in case the string is part of the playlist
   description.
*/

/* Note: some of the comments for the MHOD_IDs are copied verbatim
 * from http://ipodlinux.org/ITunesDB */
enum MHOD_ID {
  MHOD_ID_TITLE = 1,
  MHOD_ID_PATH = 2,   /* file path on iPod (special format) */
  MHOD_ID_ALBUM = 3,
  MHOD_ID_ARTIST = 4,
  MHOD_ID_GENRE = 5,
  MHOD_ID_FILETYPE = 6,
/* MHOD_ID_EQSETTING = 7, */
  MHOD_ID_COMMENT = 8,
  /* Category - This is the category ("Technology", "Music", etc.) where
     the podcast was located. Introduced in db version 0x0d. */
  MHOD_ID_CATEGORY = 9,
  MHOD_ID_COMPOSER = 12,
  MHOD_ID_GROUPING = 13,
  /* Description text (such as podcast show notes). Accessible by
     wselecting the center button on the iPod, where this string is
     displayed along with the song title, date, and
     timestamp. Introduced in db version 0x0d. */
  MHOD_ID_DESCRIPTION = 14,
  /* Podcast Enclosure URL. Note: this is either a UTF-8 or ASCII
     encoded string (NOT UTF-16). Also, there is no mhod::length value
     for this type. Introduced in db version 0x0d.  */
  MHOD_ID_PODCASTURL = 15,
  /* Podcast RSS URL. Note: this is either a UTF-8 or ASCII encoded
     string (NOT UTF-16). Also, there is no mhod::length value for this
     type. Introduced in db version 0x0d. */
  MHOD_ID_PODCASTRSS = 16,
  /* Chapter data. This is a m4a-style entry that is used to display
     subsongs within a mhit. Introduced in db version 0x0d. */
  MHOD_ID_CHAPTERDATA = 17,
  /* Subtitle (usually the same as Description). Introduced in db
     version 0x0d. */
  MHOD_ID_SUBTITLE = 18,
  /* Show (for TV Shows only). Introduced in db version 0x0d? */
  MHOD_ID_TVSHOW = 19, 
  /* Episode # (for TV Shows only). Introduced in db version 0x0d? */
  MHOD_ID_TVEPISODE = 20,
  /* TV Network (for TV Shows only). Introduced in db version 0x0d? */
  MHOD_ID_TVNETWORK = 21,
  /* Album Artist. Introduced in db version 0x13? */
  MHOD_ID_ALBUMARTIST = 22,
  /* Sort key for artist. */
  MHOD_ID_SORT_ARTIST = 23,
  /* Appears to be a list of keywords pertaining to a track. Introduced
     in db version 0x13? */
  MHOD_ID_KEYWORDS = 24,
  /* more sort keys, taking precedence over the standard entries if
     present */
  MHOD_ID_SORT_TITLE = 27,
  MHOD_ID_SORT_ALBUM = 28,
  MHOD_ID_SORT_ALBUMARTIST = 29,
  MHOD_ID_SORT_COMPOSER = 30,
  MHOD_ID_SORT_TVSHOW = 31,
  MHOD_ID_SPLPREF = 50,  /* settings for smart playlist */
  MHOD_ID_SPLRULES = 51, /* rules for smart playlist     */
  MHOD_ID_LIBPLAYLISTINDEX = 52,  /* Library Playlist Index */
  MHOD_ID_PLAYLIST = 100
};


/* Used as first iPod ID when renumbering (re-assigning) the iPod
   (track) IDs before writing out the iTunesDB. */
static const gint FIRST_IPOD_ID=52;


enum MHOD52_SORTTYPE {
    MHOD52_SORTTYPE_TITLE    = 0x03,
    MHOD52_SORTTYPE_ALBUM    = 0x04,
    MHOD52_SORTTYPE_ARTIST   = 0x05,
    MHOD52_SORTTYPE_GENRE    = 0x07,
    MHOD52_SORTTYPE_COMPOSER = 0x12/*,
    MHOD52_SORTTYPE_TVSHOW   = 0x1d,
    MHOD52_SORTTYPE_TVSEASON = 0x1e,
    MHOD52_SORTTYPE_TVEPISODE= 0x1f*/
};

struct mhod52track
{
    gchar *album;
    gchar *title;
    gchar *artist;
    gchar *genre;
    gchar *composer;
    gint track_nr;
    gint cd_nr;
    gint index;
    gint numtracks;
};

struct _MHODData
{
    gboolean valid;
    gint32 type;
    union
    {
	gint32 track_pos;
	gchar *string;
	gchar *chapterdata_raw;
	Itdb_Track *chapterdata_track; /* for writing chapterdata */
	Itdb_SPLPref *splpref;
	Itdb_SPLRules *splrules;
	GList *mhod52coltracks;
    } data;
    union
    {
	enum MHOD52_SORTTYPE mhod52sorttype;
    } data2;
};

typedef struct _MHODData MHODData;

/* Declarations */
static gboolean itdb_create_directories (Itdb_Device *device, GError **error);

/* ID for error domain */
GQuark itdb_file_error_quark (void)
{
    static GQuark q = 0;
    if (q == 0)
	q = g_quark_from_static_string ("itdb-file-error-quark");
    return q;
}


/* Read the contents of @filename and return a FContents
   struct. Returns NULL in case of error and @error is set
   accordingly */
static FContents *fcontents_read (const gchar *fname, GError **error)
{
    FContents *cts;

    g_return_val_if_fail (fname, NULL);

    cts = g_new0 (FContents, 1);
    cts->reversed = FALSE;

    if (g_file_get_contents (fname, &cts->contents, &cts->length, error))
    {
	cts->filename = g_strdup (fname);
    }
    else
    {
	g_free (cts);
	cts = NULL;
    }
    return cts;
}


/* Frees the memory taken by a FContents structure. NULL pointer will
 * be ignored */
static void fcontents_free (FContents *cts)
{
    if (cts)
    {
	g_free (cts->filename);
	g_free (cts->contents);
	/* must not g_error_free (cts->error) because the error was
	   propagated -> might free the error twice */
	g_free (cts);
    }
}


/* There seems to be a problem with some distributions (kernel
   versions or whatever -- even identical version numbers don't don't
   show identical behaviour...): even though vfat is supposed to be
   case insensitive, a difference is made between upper and lower case
   under some special circumstances. As in "/iPod_Control/Music/F00"
   and "/iPod_Control/Music/f00 "... If the former filename does not
   exist, we try to find an existing case insensitive match for each
   component of the filename.  If we can find such a match, we return
   it.  Otherwise, we return NULL.*/
     
/**
 * itdb_resolve_path:
 * @root: in local encoding
 * @components: in utf8
 *
 * Resolve the path to a track on the iPod
 *
 * We start by assuming that the ipod mount point exists.  Then, for
 * each component c of track-&gt;ipod_path, we try to find an entry d in
 * good_path that is case-insensitively equal to c.  If we find d, we
 * append d to good_path and make the result the new good_path.
 * Otherwise, we quit and return NULL.
 *
 * Return value: path to track on the iPod or NULL.
 **/
gchar * itdb_resolve_path (const gchar *root,
			   const gchar * const * components)
{
  gchar *good_path = g_strdup(root);
  guint32 i;

  if (!root) return NULL;

  for(i = 0 ; components[i] ; i++) {
    GDir *cur_dir;
    gchar *component_as_filename;
    gchar *test_path;
    gchar *component_stdcase;
    const gchar *dir_file=NULL;

    /* skip empty components */
    if (strlen (components[i]) == 0) continue;
    component_as_filename = 
      g_filename_from_utf8(components[i],-1,NULL,NULL,NULL);
    test_path = g_build_filename(good_path,component_as_filename,NULL);
    g_free(component_as_filename);
    if(g_file_test(test_path,G_FILE_TEST_EXISTS)) {
      /* This component does not require fixup */
      g_free(good_path);
      good_path = test_path;
      continue;
    }
    g_free(test_path);
    component_stdcase = g_utf8_casefold(components[i],-1);
    /* Case insensitively compare the current component with each entry
     * in the current directory. */

    cur_dir = g_dir_open(good_path,0,NULL);
    if (cur_dir) while ((dir_file = g_dir_read_name(cur_dir)))
    {
	gchar *file_utf8 = g_filename_to_utf8(dir_file,-1,NULL,NULL,NULL);
	gchar *file_stdcase = g_utf8_casefold(file_utf8,-1);
	gboolean found = !g_utf8_collate(file_stdcase,component_stdcase);
	gchar *new_good_path;
	g_free(file_stdcase);
	if(!found)
	{
	    /* This is not the matching entry */
	    g_free(file_utf8);
	    continue;
	}
      
	new_good_path = dir_file ? g_build_filename(good_path,dir_file,NULL) : NULL;
	g_free(good_path);
	good_path= new_good_path;
	/* This is the matching entry, so we can stop searching */
	break;
    }
    
    if(!dir_file) {
      /* We never found a matching entry */
      g_free(good_path);
      good_path = NULL;
    }

    g_free(component_stdcase);
    if (cur_dir) g_dir_close(cur_dir);
    if(!good_path || !g_file_test(good_path,G_FILE_TEST_EXISTS))
      break; /* We couldn't fix this component, so don't try later ones */
  }
    
  if(good_path && g_file_test(good_path,G_FILE_TEST_EXISTS))
    return good_path;
          
  return NULL;
}


/* Check if the @seek with length @len is legal or out of
 * range. Returns TRUE if legal and FALSE when it is out of range, in
 * which case cts->error is set as well. */
static gboolean check_seek (FContents *cts, glong seek, glong len)
{
    g_return_val_if_fail (cts, FALSE);
    g_return_val_if_fail (cts->contents, FALSE);

    if ((seek+len <= cts->length) && (seek >=0))
    {
	return TRUE;
    }
    else
    {
	g_return_val_if_fail (cts->filename, FALSE);
	g_set_error (&cts->error,
		     ITDB_FILE_ERROR,
		     ITDB_FILE_ERROR_SEEK,
		     _("Illegal seek to offset %ld (length %ld) in file '%s'."),
		     seek, len, cts->filename);
	return FALSE;
    }
}


/* Copies @len bytes from position @seek in @cts->contents to
   @data. Returns FALSE on error and sets cts->error accordingly. */
static gboolean seek_get_n_bytes (FContents *cts, gchar *data,
			      glong seek, glong len)
{
  if (check_seek (cts, seek, len))
  {
      memcpy (data, &cts->contents[seek], len);
      return TRUE;
  }
  return FALSE;
}

/* Compare @n bytes of @cts->contents starting at @seek and
 * @data. Returns TRUE if equal, FALSE if not. Also returns FALSE on
 * error, so you must check cts->error */
static gboolean cmp_n_bytes_seek (FContents *cts, const gchar *data,
				  glong seek, glong len)
{
    if (check_seek (cts, seek, len))
    {
	gint i;
	for (i=0; i<len; ++i)
	{
	    if (cts->contents[seek+i] != data[i]) return FALSE;
	}
	return TRUE;
    }
    return FALSE;
}


/* Compare 4 bytes of @header with 4 bytes at @seek taking into
 * consideration the status of cts->reversed */
static gboolean check_header_seek (FContents *cts, const gchar *data,
				   glong seek)
{
    gchar rdata[4];
    gint i, offset, sign;

    g_return_val_if_fail (cts, FALSE);
    g_return_val_if_fail (data, FALSE);
    /* reverse data for compare if necessary */
    if (cts->reversed)
    {
	offset = 3;
	sign = -1;
    }
    else
    {
	offset = 0;
	sign = 1;
    }
    for (i=0; i<4; ++i)
    {
	    rdata[i] = data[offset + sign*i];
    }

    return cmp_n_bytes_seek (cts, rdata, seek, 4);
}


/* ------------------------------------------------------------
   Not Endian Dependent
   ------------------------------------------------------------ */

/* Returns the 1-byte number stored at position @seek. On error the
 * GError in @cts is set. */
static guint8 get8int (FContents *cts, glong seek)
{
    guint8 n=0;

    if (check_seek (cts, seek, 1))
    {
	n = cts->contents[seek];
    }
    return n;
}


/* ------------------------------------------------------------
   Little Endian
   ------------------------------------------------------------ */

/* Get the 2-byte-number stored at position "seek" in little endian
   encoding. On error the GError in @cts is set. */
static guint16 raw_get16lint (FContents *cts, glong seek)
{
    guint16 n=0;

    if (check_seek (cts, seek, 2))
    {
	g_return_val_if_fail (cts->contents, 0);
	memcpy (&n, &cts->contents[seek], 2);
	n = GUINT16_FROM_LE (n);
    }
    return n;
}

/* Get the 3-byte-number stored at position "seek" in little endian
   encoding. On error the GError in @cts is set. */
static guint32 raw_get24lint (FContents *cts, glong seek)
{
    guint32 n=0;

    if (check_seek (cts, seek, 3))
    {
	g_return_val_if_fail (cts->contents, 0);
	n = ((guint32)get8int (cts, seek+0)) +
	    (((guint32)get8int (cts, seek+1)) >> 8) +
	    (((guint32)get8int (cts, seek+2)) >> 16);
    }
    return n;
}

/* Get the 4-byte-number stored at position "seek" in little endian
   encoding. On error the GError in @cts is set. */
static guint32 raw_get32lint (FContents *cts, glong seek)
{
    guint32 n=0;

    if (check_seek (cts, seek, 4))
    {
	g_return_val_if_fail (cts->contents, 0);
	memcpy (&n, &cts->contents[seek], 4);
	n = GUINT32_FROM_LE (n);
    }
    return n;
}

/* Get 4 byte floating number */
static float raw_get32lfloat (FContents *cts, glong seek)
{
    union
    {
	guint32 i;
	float   f;
    } flt;

    g_return_val_if_fail (sizeof (float) == 4, 0);

    flt.i = raw_get32lint (cts, seek);

    return flt.f;
}


/* Get the 8-byte-number stored at position "seek" in little endian
   encoding. On error the GError in @cts is set. */
static guint64 raw_get64lint (FContents *cts, glong seek)
{
    guint64 n=0;

    if (check_seek (cts, seek, 8))
    {
	g_return_val_if_fail (cts->contents, 0);
	memcpy (&n, &cts->contents[seek], 8);
	n = GUINT64_FROM_LE (n);
    }
    return n;
}


/* ------------------------------------------------------------
   Big Endian
   ------------------------------------------------------------ */

/* Get the 2-byte-number stored at position "seek" in little endian
   encoding. On error the GError in @cts is set. */
static guint16 raw_get16bint (FContents *cts, glong seek)
{
    guint16 n=0;

    if (check_seek (cts, seek, 2))
    {
	g_return_val_if_fail (cts->contents, 0);
	memcpy (&n, &cts->contents[seek], 2);
	n = GUINT16_FROM_BE (n);
    }
    return n;
}

/* Get the 3-byte-number stored at position "seek" in big endian
   encoding. On error the GError in @cts is set. */
static guint32 raw_get24bint (FContents *cts, glong seek)
{
    guint32 n=0;

    if (check_seek (cts, seek, 3))
    {
	g_return_val_if_fail (cts->contents, 0);
	n = ((guint32)get8int (cts, seek+2)) +
	    (((guint32)get8int (cts, seek+1)) >> 8) +
	    (((guint32)get8int (cts, seek+0)) >> 16);
    }
    return n;
}

/* Get the 4-byte-number stored at position "seek" in big endian
   encoding. On error the GError in @cts is set. */
static guint32 raw_get32bint (FContents *cts, glong seek)
{
    guint32 n=0;

    if (check_seek (cts, seek, 4))
    {
	g_return_val_if_fail (cts->contents, 0);
	memcpy (&n, &cts->contents[seek], 4);
	n = GUINT32_FROM_BE (n);
    }
    return n;
}

/* Get 4 byte floating number */
static float raw_get32bfloat (FContents *cts, glong seek)
{
    union
    {
	guint32 i;
	float   f;
    } flt;

    g_return_val_if_fail (sizeof (float) == 4, 0);

    flt.i = raw_get32bint (cts, seek);

    return flt.f;
}

/* Get the 8-byte-number stored at position "seek" in big endian
   encoding. On error the GError in @cts is set. */
static guint64 raw_get64bint (FContents *cts, glong seek)
{
    guint64 n=0;

    if (check_seek (cts, seek, 8))
    {
	g_return_val_if_fail (cts->contents, 0);
	memcpy (&n, &cts->contents[seek], 8);
	n = GUINT64_FROM_BE (n);
    }
    return n;
}


/* ------------------------------------------------------------
   Reversed Endian Sensitive (little endian)
   ------------------------------------------------------------ */

/* The following functions take into consideration the state of
 * cts->reversed and call either raw_getnnlint or raw_getnnbint */
static guint16 get16lint (FContents *cts, glong seek)
{
    g_return_val_if_fail (cts, 0);
    if (!cts->reversed)
	return raw_get16lint (cts, seek);
    else
	return raw_get16bint (cts, seek);
}

static guint32 get24lint (FContents *cts, glong seek)
{
    g_return_val_if_fail (cts, 0);
    if (!cts->reversed)
	return raw_get24lint (cts, seek);
    else
	return raw_get24bint (cts, seek);
}
#if 0
static guint32 get24bint (FContents *cts, glong seek)
{
    g_return_val_if_fail (cts, 0);
    if (!cts->reversed)
	return raw_get24bint (cts, seek);
    else
	return raw_get24lint (cts, seek);
}
#endif
static guint32 get32lint (FContents *cts, glong seek)
{
    g_return_val_if_fail (cts, 0);
    if (!cts->reversed)
	return raw_get32lint (cts, seek);
    else
	return raw_get32bint (cts, seek);
}

static float get32lfloat (FContents *cts, glong seek)
{
    g_return_val_if_fail (cts, 0);
    if (!cts->reversed)
	return raw_get32lfloat (cts, seek);
    else
	return raw_get32bfloat (cts, seek);
}

static guint64 get64lint (FContents *cts, glong seek)
{
    g_return_val_if_fail (cts, 0);
    if (!cts->reversed)
	return raw_get64lint (cts, seek);
    else
	return raw_get64bint (cts, seek);
}



/* ------------------------------------------------------------
   Reversed Endian Sensitive (big endian)
   ------------------------------------------------------------ */

#if 0
static guint16 get16bint (FContents *cts, glong seek)
{
    g_return_val_if_fail (cts, 0);
    if (!cts->reversed)
	return raw_get16bint (cts, seek);
    else
	return raw_get16lint (cts, seek);
}
#endif
static guint32 get32bint (FContents *cts, glong seek)
{
    g_return_val_if_fail (cts, 0);
    if (!cts->reversed)
	return raw_get32bint (cts, seek);
    else
	return raw_get32lint (cts, seek);
}

#if 0
static float get32bfloat (FContents *cts, glong seek)
{
    g_return_val_if_fail (cts, 0);
    if (!cts->reversed)
	return raw_get32bfloat (cts, seek);
    else
	return raw_get32lfloat (cts, seek);
}
#endif

static guint64 get64bint (FContents *cts, glong seek)
{
    g_return_val_if_fail (cts, 0);
    if (!cts->reversed)
	return raw_get64bint (cts, seek);
    else
	return raw_get64lint (cts, seek);
}




/* Fix little endian UTF16 String to correct byteorder if necessary
 * (all strings in the Itdb_iTunesDB are little endian except for the ones
 * in smart playlists). */
static gunichar2 *fixup_little_utf16 (gunichar2 *utf16_string)
{
#   if (G_BYTE_ORDER == G_BIG_ENDIAN)
    gint32 i;
    if (utf16_string)
    {
	for(i=0; utf16_string[i]; i++)
	{
	    utf16_string[i] = GUINT16_SWAP_LE_BE (utf16_string[i]);
	}
    }
#   endif
    return utf16_string;
}

/* Fix big endian UTF16 String to correct byteorder if necessary (only
 * strings in smart playlists are big endian) */
static gunichar2 *fixup_big_utf16 (gunichar2 *utf16_string)
{
#   if (G_BYTE_ORDER == G_LITTLE_ENDIAN)
    gint32 i;
    if (utf16_string)
    {
	for(i=0; utf16_string[i]; i++)
	{
	    utf16_string[i] = GUINT16_SWAP_LE_BE (utf16_string[i]);
	}
    }
#   endif
    return utf16_string;
}


#define CHECK_ERROR(imp, val) if (cts->error) { g_propagate_error (&imp->error, cts->error); return (val); }


/* get next playcount, that is the first entry of GList
 * playcounts. This entry is removed from the list. You must free the
 * return value after use */
static struct playcount *playcount_get_next (FImport *fimp)
{
    struct playcount *playcount;
    g_return_val_if_fail (fimp, NULL);

    playcount = g_list_nth_data (fimp->playcounts, 0);

    if (playcount)
	fimp->playcounts = g_list_remove (fimp->playcounts, playcount);
    return playcount;
}

/* delete all entries of GList *playcounts */
static void playcounts_free (FImport *fimp)
{
    struct playcount *playcount;

    g_return_if_fail (fimp);

    while ((playcount=playcount_get_next (fimp))) g_free (playcount);
}


/* called by init_playcounts */
static gboolean playcounts_read (FImport *fimp, FContents *cts)
{
    guint32 header_length, entry_length, entry_num, i=0;

    g_return_val_if_fail (fimp, FALSE);
    g_return_val_if_fail (cts, FALSE);

    if (!check_header_seek (cts, "mhdp", 0))
    {
	if (cts->error)
	{
	    g_propagate_error (&fimp->error, cts->error);
	    return FALSE;
	}
	cts->reversed = TRUE;
	if (!check_header_seek (cts, "mhdp", 0))
	{
	    if (cts->error)
	    {
		g_propagate_error (&fimp->error, cts->error);
		return FALSE;
	    }
	    else
	    {   /* set error */
		g_return_val_if_fail (cts->filename, FALSE);
		g_set_error (&fimp->error,
			     ITDB_FILE_ERROR,
			     ITDB_FILE_ERROR_CORRUPT,
			     _("Not a Play Counts file: '%s' (missing mhdp header)."),
			     cts->filename);
		return FALSE;
	    }
	}
    }
    header_length = get32lint (cts, 4);
    CHECK_ERROR (fimp, FALSE);
    /* all the headers I know are 0x60 long -- if this one is longer
       we can simply ignore the additional information */
    if (header_length < 0x60)
    {
	g_set_error (&fimp->error,
		     ITDB_FILE_ERROR,
		     ITDB_FILE_ERROR_CORRUPT,
		     _("Play Counts file ('%s'): header length smaller than expected (%d<96)."),
		     cts->filename, header_length);
	return FALSE;
    }
    entry_length = get32lint (cts, 8);
    CHECK_ERROR (fimp, FALSE);
    /* all the entries I know are 0x0c (firmware 1.3) or 0x10
     * (firmware 2.0), 0x14 (iTunesDB version 0x0d) or 0x1c (iTunesDB
     * version 0x13) in length */
    if (entry_length < 0x0c)
    {
	g_set_error (&fimp->error,
		     ITDB_FILE_ERROR,
		     ITDB_FILE_ERROR_CORRUPT,
		     _("Play Counts file ('%s'): entry length smaller than expected (%d<12)."),
		     cts->filename, entry_length);
	return FALSE;
    }
    /* number of entries */
    entry_num = get32lint (cts, 12);
    CHECK_ERROR (fimp, FALSE);
    for (i=0; i<entry_num; ++i)
    {
	guint32 mac_time;
	struct playcount *playcount = g_new0 (struct playcount, 1);
	glong seek = header_length + i*entry_length;

	check_seek (cts, seek, entry_length);
	CHECK_ERROR (fimp, FALSE);	

	fimp->playcounts = g_list_append (fimp->playcounts, playcount);
	playcount->playcount = get32lint (cts, seek);	
	mac_time = get32lint (cts, seek+4);
	playcount->time_played = device_time_mac_to_time_t (fimp->itdb->device, mac_time);
	playcount->bookmark_time = get32lint (cts, seek+8);
	
	/* rating only exists if the entry length is at least 0x10 */
	if (entry_length >= 0x10)
	{
	    playcount->rating = get32lint (cts, seek+12);
	}
	else
	{
	    playcount->rating = NO_PLAYCOUNT;
	}
	/* unk16 only exists if the entry length is at least 0x14 */
	if (entry_length >= 0x14)
	{
	    playcount->pc_unk16 = get32lint (cts, seek+16);
	}
	/* skip_count and last_skipped only exists if the entry length
	   is at least 0x1c */
	if (entry_length >= 0x1c)
	{
	    playcount->skipcount = get32lint (cts, seek+20);
	    mac_time = get32lint (cts, seek+24);
	    playcount->last_skipped = device_time_mac_to_time_t (fimp->itdb->device,
							       mac_time);

	}
    }
    return TRUE;
}


/* called by init_playcounts */
static gboolean itunesstats_read (FImport *fimp, FContents *cts)
{
    guint32 entry_num, i=0;
    glong seek;

    g_return_val_if_fail (fimp, FALSE);
    g_return_val_if_fail (cts, FALSE);

    /* number of entries */
    entry_num = get32lint (cts, 0);
    CHECK_ERROR (fimp, FALSE);

    seek = 6;
    for (i=0; i<entry_num; ++i)
    {
	struct playcount *playcount = g_new0 (struct playcount, 1);
	guint32 entry_length = get24lint (cts, seek+0);
	CHECK_ERROR (fimp, FALSE);
	if (entry_length < 18)
	{
	    g_set_error (&fimp->error,
			 ITDB_FILE_ERROR,
			 ITDB_FILE_ERROR_CORRUPT,
			 _("iTunesStats file ('%s'): entry length smaller than expected (%d<18)."),
			 cts->filename, entry_length);
	    return FALSE;
	}

	fimp->playcounts = g_list_append (fimp->playcounts, playcount);
	/* NOTE:
	 *
	 * The iPod (firmware 1.3, 2.0, ...?) doesn't seem to use the
	 * timezone information correctly -- no matter what you set
	 * iPod's timezone to, it will always record as if it were set
	 * to UTC -- we need to subtract the difference between
	 * current timezone and UTC to get a correct
	 * display. -- this should be done by the application were
	 * necessary */
	playcount->bookmark_time = get24lint (cts, seek+3);
	CHECK_ERROR (fimp, FALSE);
	playcount->st_unk06 = get24lint (cts, seek+6);
	CHECK_ERROR (fimp, FALSE);
	playcount->st_unk09 = get24lint (cts, seek+9);
	CHECK_ERROR (fimp, FALSE);
	playcount->playcount = get24lint (cts, seek+12);
	CHECK_ERROR (fimp, FALSE);
	playcount->skipped = get24lint (cts, seek+15);
	CHECK_ERROR (fimp, FALSE);
	
	playcount->rating = NO_PLAYCOUNT;

	seek += entry_length;
    }
    return TRUE;
}



/* Read the Play Count file (formed by adding "Play Counts" to the
 * directory component of fimp->itdb->itdb_filename) and set up the
 * GList *playcounts. If no Play Count file is present, attempt to
 * read the iTunesStats file instead, which is used on the Shuffle for
 * the same purpose.
 *
 * Returns TRUE on success (also when no Play Count
 * file is found as this is not an error) and FALSE otherwise, in
 * which case fimp->error is set accordingly. */
static gboolean playcounts_init (FImport *fimp)
{
  const gchar *plc[] = {"Play Counts", NULL};
  const gchar *ist[] = {"iTunesStats", NULL};
  gchar *plcname, *dirname, *istname;
  gboolean result=TRUE;
  struct stat filestat;
  FContents *cts;

  g_return_val_if_fail (fimp, FALSE);
  g_return_val_if_fail (!fimp->error, FALSE);
  g_return_val_if_fail (!fimp->playcounts, FALSE);
  g_return_val_if_fail (fimp->itdb, FALSE);
  g_return_val_if_fail (fimp->itdb->filename, FALSE);

  dirname = g_path_get_dirname (fimp->itdb->filename);

  plcname = itdb_resolve_path (dirname, plc);
  istname = itdb_resolve_path (dirname, ist);

  g_free (dirname);

  /* skip if no playcounts file is present */
  if (plcname)
  {
      /* skip if playcounts file has zero-length (often happens after
       * dosfsck) */
      stat (plcname, &filestat);
      if (filestat.st_size >= 0x60)
      {
	  cts = fcontents_read (plcname, &fimp->error);
	  if (cts)
	  {
	      result = playcounts_read (fimp, cts);
	      fcontents_free (cts);
	  }
	  else
	  {
	      result = FALSE;
	  }
      }
  }
  else if (istname)
  {
      /* skip if iTunesStats file has zero-length (often happens after
       * dosfsck) */
      stat (istname, &filestat);
      if (filestat.st_size >= 0x06)
      {
	  cts = fcontents_read (istname, &fimp->error);
	  if (cts)
	  {
	      result = itunesstats_read (fimp, cts);
	      fcontents_free (cts);
	  }
	  else
	  {
	      result = FALSE;
	  }
      }
  }

  g_free (plcname);
  g_free (istname);

  return result;
}


/* Free the memory taken by @fimp. fimp->itdb must be freed separately
 * before calling this function */
static void itdb_free_fimp (FImport *fimp)
{
    if (fimp)
    {
	if (fimp->fcontents)  fcontents_free (fimp->fcontents);
	g_list_free (fimp->pos_glist);
	playcounts_free (fimp);
	g_free (fimp);
    }
}

/** 
 * itdb_free:
 * @itdb: an #Itdb_iTunesDB
 *
 * Free the memory taken by @itdb. 
 **/
void itdb_free (Itdb_iTunesDB *itdb)
{
    if (itdb)
    {
	g_list_foreach (itdb->playlists,
			(GFunc)(itdb_playlist_free), NULL);
	g_list_free (itdb->playlists);
	g_list_foreach (itdb->tracks,
			(GFunc)(itdb_track_free), NULL);
	g_list_free (itdb->tracks);
	g_free (itdb->filename);
	itdb_device_free (itdb->device);
	if (itdb->userdata && itdb->userdata_destroy)
	    (*itdb->userdata_destroy) (itdb->userdata);
	g_free (itdb);
    }
}

/**
 * itdb_duplicate:
 * @itdb: an #Itdb_iTunesDB
 *
 * Duplicate @itdb 
 * FIXME: not implemented yet 
 *
 * Return value: always return NULL since it's unimplemented
 **/
Itdb_iTunesDB *itdb_duplicate (Itdb_iTunesDB *itdb)
{
    g_return_val_if_fail (itdb, NULL);
    /* FIXME: not yet implemented */
    g_return_val_if_reached (NULL);
}

/**
 * itdb_playlists_number:
 * @itdb: an #Itdb_iTunesDB
 *
 * Counts the number of playlists stored in @itdb
 *
 * Return value: the number of playlists in @itdb (including the master 
 * playlist)
 **/
guint32 itdb_playlists_number (Itdb_iTunesDB *itdb)
{
    g_return_val_if_fail (itdb, 0);

    return g_list_length (itdb->playlists);
}


/**
 * itdb_tracks_number:
 * @itdb: an #Itdb_iTunesDB
 *
 * Counts the number of tracks stored in @itdb
 *
 * Return value: the number of tracks in @itdb
 **/
guint32 itdb_tracks_number (Itdb_iTunesDB *itdb)
{
    g_return_val_if_fail (itdb, 0);

    return g_list_length (itdb->tracks);
}

/**
 * itdb_tracks_number_nontransferred:
 * @itdb: an #Itdb_iTunesDB
 *
 * Counts the number of non-transferred tracks in @itdb
 *
 * Return value: the number of tracks in @itdb that haven't been transferred
 * to the iPod yet (ie the number of #Itdb_Track in which the transferred field
 * is false)
 **/
guint32 itdb_tracks_number_nontransferred (Itdb_iTunesDB *itdb)
{
    guint n = 0;
    GList *gl;
    g_return_val_if_fail (itdb, 0);

    for (gl=itdb->tracks; gl; gl=gl->next)
    {
	Itdb_Track *track = gl->data;
	g_return_val_if_fail (track, 0);
	if (!track->transferred)   ++n;
    }
    return n;
}



/**
 * itdb_new:
 *
 * Creates a new Itdb_iTunesDB with the unknowns filled in to reasonable
 * values.
 *
 * Return value: a newly created Itdb_iTunesDB to be freed with itdb_free()
 * when it's no longer needed
 **/
Itdb_iTunesDB *itdb_new (void)
{
    static GOnce g_type_init_once = G_ONCE_INIT;
    Itdb_iTunesDB *itdb;

    g_once (&g_type_init_once, (GThreadFunc)g_type_init, NULL);
    itdb = g_new0 (Itdb_iTunesDB, 1);
    itdb->device = itdb_device_new ();
    itdb->version = 0x13;
    itdb->id = ((guint64)g_random_int () << 32) |
	((guint64)g_random_int ());
    return itdb;
}

/* Returns the type of the mhod and the length *ml. *ml is set to -1
 * on error (e.g. because there's no mhod at @seek). */
/* A return value of -1 and no error set means that no mhod was found
   at @seek */
static gint32 get_mhod_type (FContents *cts, glong seek, guint32 *ml)
{
    gint32 type = -1;

#if ITUNESDB_DEBUG
    fprintf(stderr, "get_mhod_type seek: %x\n", (int)seek);
#endif

    if (ml) *ml = -1;

    if (check_header_seek (cts, "mhod", seek))
    {
	guint32 len = get32lint (cts, seek+8);    /* total length */
	if (cts->error) return -1;
	if (ml) *ml = len;
	type = get32lint (cts, seek+12);          /* mhod_id      */
	if (cts->error) return -1;
    }
    return type;
}

/* Returns the contents of the mhod at position @mhod_seek. This can
   be a simple string or something more complicated as in the case for
   Itdb_SPLPREF OR Itdb_SPLRULES.

   *mhod_len is set to the total length of the mhod (-1 in case an
   *error occured).

   MHODData.valid is set to FALSE in case of any error. cts->error
   will be set accordingly.

   MHODData.type is set to the type of the mhod. The data (or a
   pointer to the data) will be stored in
   .playlist_id/.string/.chapterdata/.splp/.splrs
*/

static MHODData get_mhod (FImport *fimp, glong mhod_seek, guint32 *ml)
{
  gunichar2 *entry_utf16 = NULL;
  MHODData result;
  gint32 xl;
  guint32 mhod_len;
  gint32 header_length;
  guint32 string_type;
  gulong seek;
  FContents *cts;
  
  cts = fimp->fcontents;
    
  result.valid = FALSE;
  result.type = -1;
  g_return_val_if_fail (ml, result);
  *ml = -1;

  g_return_val_if_fail (cts, result);
  g_return_val_if_fail (!cts->error, result);

#if ITUNESDB_DEBUG
  fprintf(stderr, "get_mhod seek: %ld\n", mhod_seek);
#endif

  result.type = get_mhod_type (cts, mhod_seek, &mhod_len);

  if (mhod_len == -1)
  {
      if (!cts->error)
      {   /* set error */
	  g_set_error (&cts->error,
		       ITDB_FILE_ERROR,
		       ITDB_FILE_ERROR_CORRUPT,
		       _("iTunesDB corrupt: no MHOD at offset %ld in file '%s'."),
		       mhod_seek, cts->filename);
      }
      return result;
  }

  if (!check_seek (cts, mhod_seek, mhod_len))
      return result;


  header_length = get32lint (cts, mhod_seek+4); /* header length  */

  seek = mhod_seek + header_length;

#if ITUNESDB_DEBUG
  fprintf(stderr, "ml: %x type: %x\n", *ml, result.type);
#endif

  switch ((enum MHOD_ID)result.type)
  {
  case MHOD_ID_LIBPLAYLISTINDEX:
      /* this is not yet supported */
  case MHOD_ID_PLAYLIST:
      /* return the position indicator */
      result.data.track_pos = get32lint (cts, mhod_seek+24);
      break;
  case MHOD_ID_TITLE:
  case MHOD_ID_PATH:
  case MHOD_ID_ALBUM:
  case MHOD_ID_ARTIST:
  case MHOD_ID_GENRE:
  case MHOD_ID_FILETYPE:
  case MHOD_ID_COMMENT:
  case MHOD_ID_CATEGORY:
  case MHOD_ID_COMPOSER:
  case MHOD_ID_GROUPING:
  case MHOD_ID_DESCRIPTION:
  case MHOD_ID_SUBTITLE:
  case MHOD_ID_TVSHOW:
  case MHOD_ID_TVEPISODE:
  case MHOD_ID_TVNETWORK:
  case MHOD_ID_ALBUMARTIST:
  case MHOD_ID_KEYWORDS:
  case MHOD_ID_SORT_ARTIST:
  case MHOD_ID_SORT_TITLE:
  case MHOD_ID_SORT_ALBUM:
  case MHOD_ID_SORT_ALBUMARTIST:
  case MHOD_ID_SORT_COMPOSER:
  case MHOD_ID_SORT_TVSHOW:
      /* type of string: 0x02: UTF8, 0x01 or 0x00: UTF16 LE */
      string_type = get32lint (cts, seek);
      xl = get32lint (cts, seek+4);   /* length of string */
      g_return_val_if_fail (xl < G_MAXUINT - 2, result);
      if (string_type != 0x02)
      {
	  entry_utf16 = g_new0 (gunichar2, (xl+2)/2);
	  if (seek_get_n_bytes (cts, (gchar *)entry_utf16, seek+16, xl))
	  {
	      fixup_little_utf16 (entry_utf16);
	      result.data.string = g_utf16_to_utf8 (entry_utf16, -1,
						    NULL, NULL, NULL);
	      g_free (entry_utf16);
	  }
	  else
	  {   /* error */
	      g_free (entry_utf16);
	      return result;  /* *ml==-1, result.valid==FALSE */
	  }
      }
      else
      {
	  result.data.string = g_new0 (gchar, xl+1);
	  if (!seek_get_n_bytes (cts, result.data.string, seek+16, xl))
	  {   /* error */
	      g_free (entry_utf16);
	      return result;  /* *ml==-1, result.valid==FALSE */
	  }
      }
      break;
  case MHOD_ID_PODCASTURL:
  case MHOD_ID_PODCASTRSS:
      /* length of string */
      xl = mhod_len - header_length;
      g_return_val_if_fail (xl < G_MAXUINT - 1, result);
      result.data.string = g_new0 (gchar, xl+1);
      if (!seek_get_n_bytes (cts, result.data.string, seek, xl))
      {
	  g_free (result.data.string);
	  return result;  /* *ml==-1, result.valid==FALSE */
      }
      break;
  case MHOD_ID_CHAPTERDATA: 
      /* we'll just copy the entire data section */
      xl = mhod_len - header_length;
      result.data.chapterdata_raw = g_new0 (gchar, xl);
      if (!seek_get_n_bytes (cts, result.data.chapterdata_raw, seek, xl))
      {
	  g_free (result.data.chapterdata_raw);
	  return result;  /* *ml==-1, result.valid==FALSE */
      }
      break;
  case MHOD_ID_SPLPREF:  /* Settings for smart playlist */
      if (!check_seek (cts, seek, 14))
	  return result;  /* *ml==-1, result.valid==FALSE */
      result.data.splpref = g_new0 (Itdb_SPLPref, 1);
      result.data.splpref->liveupdate = get8int (cts, seek);
      result.data.splpref->checkrules = get8int (cts, seek+1);
      result.data.splpref->checklimits = get8int (cts, seek+2);
      result.data.splpref->limittype = get8int (cts, seek+3);
      result.data.splpref->limitsort = get8int (cts, seek+4);
      result.data.splpref->limitvalue = get32lint (cts, seek+8);
      result.data.splpref->matchcheckedonly = get8int (cts, seek+12);
      /* if the opposite flag is on (seek+13), set limitsort's high
	 bit -- see note in itunesdb.h for more info */
      if (get8int (cts, seek+13))
	  result.data.splpref->limitsort |= 0x80000000;
      break;
  case MHOD_ID_SPLRULES:  /* Rules for smart playlist */
      if (check_header_seek (cts, "SLst", seek))
      {
	  /* !!! for some reason the SLst part is the only part of the
	     iTunesDB with big-endian encoding, including UTF16
	     strings */
	  gint i;
	  guint32 numrules;
	  if (!check_seek (cts, seek, 136))
	      return result;  /* *ml==-1, result.valid==FALSE */
	  result.data.splrules = g_new0 (Itdb_SPLRules, 1);
	  result.data.splrules->unk004 = get32bint (cts, seek+4);
	  numrules = get32bint (cts, seek+8);
	  result.data.splrules->match_operator = get32bint (cts, seek+12);
	  seek += 136;  /* I can't find this value stored in the
			   iTunesDB :-( */
	  for (i=0; i<numrules; ++i)
	  {
	      guint32 length;
	      ItdbSPLFieldType ft;
	      gunichar2 *string_utf16;
	      Itdb_SPLRule *splr = g_new0 (Itdb_SPLRule, 1);
	      result.data.splrules->rules = g_list_append (
		  result.data.splrules->rules, splr);
	      if (!check_seek (cts, seek, 56))
		  goto splrules_error;
	      splr->field = get32bint (cts, seek);
	      splr->action = get32bint (cts, seek+4);

	      if (!itdb_spl_action_known (splr->action))
	      {
		  g_warning (_("Unknown smart rule action at %ld: %x. Trying to continue.\n"), seek, splr->action);
	      }

	      seek += 52;
	      length = get32bint (cts, seek);
	      g_return_val_if_fail (length < G_MAXUINT-2, result);

	      ft = itdb_splr_get_field_type (splr);
	      switch (ft)
	      {
	      case ITDB_SPLFT_STRING:
		  string_utf16 = g_new0 (gunichar2, (length+2)/2);
		  if (!seek_get_n_bytes (cts, (gchar *)string_utf16,
					 seek+4, length))
		  {
		      g_free (string_utf16);
		      goto splrules_error;
		  }
		  fixup_big_utf16 (string_utf16);
		  splr->string = g_utf16_to_utf8 (
		      string_utf16, -1, NULL, NULL, NULL);
		  g_free (string_utf16);
		  break;
	      case ITDB_SPLFT_INT:
	      case ITDB_SPLFT_DATE:
	      case ITDB_SPLFT_BOOLEAN:
	      case ITDB_SPLFT_PLAYLIST:
	      case ITDB_SPLFT_UNKNOWN:
	      case ITDB_SPLFT_BINARY_AND:
		  if (length != 0x44)
		  {
		      g_warning (_("Length of smart playlist rule field (%d) not as expected. Trying to continue anyhow.\n"), length);
		  }
		  if (!check_seek (cts, seek, 72))
		      goto splrules_error;
		  splr->fromvalue = get64bint (cts, seek+4);
		  splr->fromdate = get64bint (cts, seek+12);
		  splr->fromunits = get64bint (cts, seek+20);
		  splr->tovalue = get64bint (cts, seek+28);
		  splr->todate = get64bint (cts, seek+36);
		  splr->tounits = get64bint (cts, seek+44);
		  /* ITDB_SPLFIELD_PLAYLIST seems to use these unknowns*/
		  splr->unk052 = get32bint (cts, seek+52);
		  splr->unk056 = get32bint (cts, seek+56);
		  splr->unk060 = get32bint (cts, seek+60);
		  splr->unk064 = get32bint (cts, seek+64);
		  splr->unk068 = get32bint (cts, seek+68);

		  if (ft == ITDB_SPLFT_DATE) {
		      ItdbSPLActionType at;
		      at = itdb_splr_get_action_type (splr);
		      if ((at == ITDB_SPLAT_RANGE_DATE) ||
			  (at == ITDB_SPLAT_DATE))
		      {
			  Itdb_iTunesDB *itdb = fimp->itdb;
			  splr->fromvalue = device_time_mac_to_time_t (itdb->device,
								     splr->fromvalue);
			  splr->tovalue = device_time_mac_to_time_t (itdb->device,
								   splr->tovalue);
		      }
		  }

		  break;
	      }
	      seek += length+4;
	  }
      }
      else
      {
	  if (!cts->error)
	  {   /* set error */
	      g_set_error (&cts->error,
			   ITDB_FILE_ERROR,
			   ITDB_FILE_ERROR_CORRUPT,
			   _("iTunesDB corrupt: no SLst at offset %ld in file '%s'."),
			   seek, cts->filename);
	  }
	  return result;  /* *ml==-1, result.valid==FALSE */
      }
      break;
    splrules_error:
      g_list_foreach (result.data.splrules->rules,
		      (GFunc)(itdb_splr_free), NULL);
      g_list_free (result.data.splrules->rules);
      g_free (result.data.splrules);
      return result;  /* *ml==-1, result.valid==FALSE */
  default:
      g_warning (_("Encountered unknown MHOD type (%d) while parsing the iTunesDB. Ignoring.\n\n"), result.type);
      *ml = mhod_len;
      return result;
  }

  *ml = mhod_len;
  result.valid = TRUE;
  return result;
}

/* Returns the value of a string type mhod. return the length of the
   mhod *ml, the mhod type *mty, and a string with the entry (in
   UTF8). After use you must free the string with g_free(). Returns
   NULL if no string is avaible. *ml is set to -1 in case of error and
   cts->error is set appropriately. */
static gchar *get_mhod_string (FImport *fimp, glong seek, guint32 *ml, gint32 *mty)
{
    MHODData mhoddata;
    FContents *cts;

    cts = fimp->fcontents;

    *mty = get_mhod_type (cts, seek, ml);
    if (cts->error) return NULL;

    if (*ml != -1) switch ((enum MHOD_ID)*mty)
    {
    case MHOD_ID_TITLE:
    case MHOD_ID_PATH:
    case MHOD_ID_ALBUM:
    case MHOD_ID_ARTIST:
    case MHOD_ID_GENRE:
    case MHOD_ID_FILETYPE:
    case MHOD_ID_COMMENT:
    case MHOD_ID_CATEGORY:
    case MHOD_ID_COMPOSER:
    case MHOD_ID_GROUPING:
    case MHOD_ID_DESCRIPTION:
    case MHOD_ID_PODCASTURL:
    case MHOD_ID_PODCASTRSS:
    case MHOD_ID_SUBTITLE:
    case MHOD_ID_TVSHOW:
    case MHOD_ID_TVEPISODE:
    case MHOD_ID_TVNETWORK:
    case MHOD_ID_ALBUMARTIST:
    case MHOD_ID_KEYWORDS:
    case MHOD_ID_SORT_ARTIST:
    case MHOD_ID_SORT_TITLE:
    case MHOD_ID_SORT_ALBUM:
    case MHOD_ID_SORT_ALBUMARTIST:
    case MHOD_ID_SORT_COMPOSER:
    case MHOD_ID_SORT_TVSHOW:
	mhoddata = get_mhod (fimp, seek, ml);
	if ((*ml != -1) && mhoddata.valid)
	    return mhoddata.data.string;
	else
	    return NULL;
    case MHOD_ID_SPLPREF:
    case MHOD_ID_SPLRULES:
    case MHOD_ID_LIBPLAYLISTINDEX:
    case MHOD_ID_PLAYLIST:
    case MHOD_ID_CHAPTERDATA:
	/* these do not have a string entry */
	return NULL;
    }
#if ITUNESDB_MHIT_DEBUG
    fprintf (stderr, "Ignoring unknown MHOD of type %d at offset %ld\n", *mty, seek);
#endif
    return NULL;
}


/* convenience function: set error for zero length hunk */
static void set_error_zero_length_hunk (GError **error, glong seek,
					const gchar *filename)
{
    g_set_error (error,
		 ITDB_FILE_ERROR,
		 ITDB_FILE_ERROR_CORRUPT,
		 _("iTunesDB corrupt: hunk length 0 for hunk at %ld in file '%s'."),
		 seek, filename);
}

/* convenience function: set error for missing hunk */
static void set_error_a_not_found_in_b (GError **error,
					const gchar *a,
					const gchar *b,
					glong b_seek)
{
    g_set_error (error,
		 ITDB_FILE_ERROR,
		 ITDB_FILE_ERROR_CORRUPT,
		 _("iTunesDB corrupt: no section '%s' found in section '%s' starting at %ld."),
		 a, b, b_seek);
}

/* convenience function: set error if header is smaller than expected */
static void set_error_a_header_smaller_than_b (GError **error,
					       const gchar *a,
					       guint32 b, guint32 len,
					       glong a_seek,
					       const gchar *filename)
{
      g_set_error (error,
		   ITDB_FILE_ERROR,
		   ITDB_FILE_ERROR_CORRUPT,
		   _("header length of '%s' smaller than expected (%d < %d) at offset %ld in file '%s'."),
		   a, b, len, a_seek, filename);
}


/* finds next occurence of section @a in section b (@b_seek) starting
   at @start_seek
*/
/* Return value:
   -1 and cts->error not set: section @a could not be found
   -1 and cts->error set: some error occured
   >=0: start of next occurence of section @a
*/
static glong find_next_a_in_b (FContents *cts,
			       const gchar *a,
			       glong b_seek, glong start_seek)
{
    glong b_len;
    glong offset, len;

    g_return_val_if_fail (a, -1);
    g_return_val_if_fail (cts, -1);
    g_return_val_if_fail (strlen (a) == 4, -1);
    g_return_val_if_fail (b_seek>=0, -1);
    g_return_val_if_fail (start_seek >= b_seek, -1);

/*     printf ("%s: b_seek: %lx, start_seek: %lx\n", a, b_seek, start_seek); */

    b_len = get32lint (cts, b_seek+8);
    if (cts->error) return -1;

    offset = start_seek - b_seek;
    len = 0;
    do
    {   /* skip headers inside the b hunk (b_len) until we find header
	   @a */
	len = get32lint (cts, b_seek+offset+4);
	if (cts->error) return -1;
	if (len == 0)
	{   /* This needs to be checked, otherwise we might hang */
	    set_error_zero_length_hunk (&cts->error, b_seek+offset,
					cts->filename);
	    return -1;
	}
	offset += len;
/* 	printf ("offset: %lx, b_len: %lx, bseek+offset: %lx\n",  */
/* 		offset, b_len, b_seek+offset); */
    } while ((offset < b_len-4) && 
	     !check_header_seek (cts, a, b_seek+offset));
    if (cts->error) return -1;

    if (offset >= b_len)	return -1;

/*     printf ("%s found at %lx\n", a, b_seek+offset); */

    return b_seek+offset;
}




/* return the position of mhsd with type @type */
/* Return value:
     -1 if mhsd cannot be found. cts->error will not be set

     0 and cts->error is set if some other error occurs.
     Since the mhsd can never be at position 0 (a mhbd must be there),
     a return value of 0 always indicates an error.
*/
static glong find_mhsd (FContents *cts, guint32 type)
{
    guint32 i, len, mhsd_num;
    glong seek;

    if (!check_header_seek (cts, "mhbd", 0))
    {
	cts->reversed = TRUE;
	if (cts->error) return 0;
	if (!check_header_seek (cts, "mhbd", 0))
	{
	    if (!cts->error)
	    {   /* set error */
		g_set_error (&cts->error,
			     ITDB_FILE_ERROR,
			     ITDB_FILE_ERROR_CORRUPT,
			     _("Not a iTunesDB: '%s' (missing mhdb header)."),
			     cts->filename);
	    }
	    return 0;
	}
    }
    len = get32lint (cts, 4);
    if (cts->error) return 0;
    /* all the headers I know are 0x68 long -- if this one is longer
       we can could simply ignore the additional information */
    /* Since 'we' (parse_fimp()) only need data from the first 32
       bytes, don't complain unless it's smaller than that */
    if (len < 32)
    {
	g_set_error (&cts->error,
		     ITDB_FILE_ERROR,
		     ITDB_FILE_ERROR_CORRUPT,
		     _("iTunesDB ('%s'): header length of mhsd hunk smaller than expected (%d<32). Aborting."),
		     cts->filename, len);
	return FALSE;
    }

    mhsd_num = get32lint (cts, 20);
    if (cts->error) return 0;

    seek = 0;
    for (i=0; i<mhsd_num; ++i)
    {
	guint32 mhsd_type;

	seek += len;
	if (!check_header_seek (cts, "mhsd", seek))
	{
	    if (!cts->error)
	    {   /* set error */
		g_set_error (&cts->error,
			     ITDB_FILE_ERROR,
			     ITDB_FILE_ERROR_CORRUPT,
			     _("iTunesDB '%s' corrupt: mhsd expected at %ld."),
			     cts->filename, seek);
	    }
	    return 0;
	}
	len = get32lint (cts, seek+8);
	if (cts->error) return 0;
	
	mhsd_type = get32lint (cts, seek+12);
	if (cts->error) return 0;

	if (mhsd_type == type) return seek;
    }
    return -1;
}



gint pos_comp (gpointer a, gpointer b);
gint pos_comp (gpointer a, gpointer b)
{
    return (GPOINTER_TO_UINT(a) - GPOINTER_TO_UINT(b));
}


/* Read and process the mhip at @seek. Return a pointer to the next
   possible mhip. */
/* Return value: -1 if no mhip is present at @seek */
static glong get_mhip (FImport *fimp, Itdb_Playlist *plitem,
		       glong mhip_seek)
{
    gboolean first_entry = TRUE;
    FContents *cts;
    guint32 mhip_hlen, mhip_len, mhod_num, mhod_seek;
    Itdb_Track *tr;
    gint32 i, pos=-1;
    gint32 mhod_type;
    guint32 trackid;


    g_return_val_if_fail (fimp, -1);
    g_return_val_if_fail (plitem, -1);

    cts = fimp->fcontents;

    if (!check_header_seek (cts, "mhip", mhip_seek))
    {
	CHECK_ERROR (fimp, -1);
	return -1;
    }

    mhip_hlen = get32lint (cts, mhip_seek+4);
    CHECK_ERROR (fimp, -1);

    if (mhip_hlen < 36)
    {
	set_error_a_header_smaller_than_b (&fimp->error,
					   "mhip",
					   mhip_hlen, 36,
					   mhip_seek, cts->filename);
	return -1;
    }

    /* Check if entire mhip header can be read -- that way we won't
       have to check for read errors every time we access a single
       byte */

    check_seek (cts, mhip_seek, mhip_hlen);
    CHECK_ERROR (fimp, -1);

    mhip_len = get32lint (cts, mhip_seek+8);
    mhod_num = get32lint (cts, mhip_seek+12);
    trackid = get32lint(cts, mhip_seek+24);

    mhod_seek = mhip_seek + mhip_hlen;
 
    /* the mhod that follows gives us the position in the
       playlist (type 100). Just for flexibility, we scan all
       following mhods and pick the type 100 */
    for (i=0; i<mhod_num; ++i)
    {
	guint32 mhod_len;

	mhod_type = get_mhod_type (cts, mhod_seek, &mhod_len);
	CHECK_ERROR (fimp, -1);
	if (mhod_type == MHOD_ID_PLAYLIST)
	{
	    MHODData mhod;
	    mhod = get_mhod (fimp, mhod_seek, &mhod_len);
	    CHECK_ERROR (fimp, -1);
	    pos = -1;
	    if (mhod.valid && first_entry)
	    {
		/* The posids don't have to be in numeric order, but our
		   database depends on the playlist members being sorted
		   according to the order they appear in the
		   playlist. Therefore we need to find out at which
		   position to insert the track */
		fimp->pos_glist = g_list_insert_sorted (
		    fimp->pos_glist,
		    GUINT_TO_POINTER(mhod.data.track_pos),
		    (GCompareFunc)pos_comp);
		pos = g_list_index (
		    fimp->pos_glist,
		    GUINT_TO_POINTER(mhod.data.track_pos));
		/* for speedup: pos==-1 is appending at the end */
		if (pos == fimp->pos_len)   pos = -1;
		/* don't call this section more than once (it never
		   should happen except in the case of corrupted
		   iTunesDBs...) */
		first_entry = FALSE;
	    }
	}
	else
	{
	    if (mhod_len == -1)
	    {
		g_warning (_("Number of MHODs in mhip at %ld inconsistent in file '%s'."),
			   mhip_seek, cts->filename);
		break;
	    }
	}
	mhod_seek += mhod_len;
    }

    tr = itdb_track_id_tree_by_id (fimp->idtree, trackid);
    if (tr)
    {
	itdb_playlist_add_track (plitem, tr, pos);
	++fimp->pos_len;
    }
    else
    {
	if (plitem->podcastflag == ITDB_PL_FLAG_NORM)
	{
	g_warning (_("Itdb_Track ID '%d' not found.\n"), trackid);
	}
    }

    /* Up to iTunesd V4.7 or so the mhip_len was set incorrectly
       (mhip_len == mhip_hlen). In that case we need to find the seek
       to the next mhip by going through all mhods.
    */
    if ((mhip_len == mhip_hlen) && (mhod_num > 0))
	return mhod_seek;
    else
	return mhip_seek+mhip_len;
}




/* Get a playlist. Returns the position where the next playlist should
   be. On error -1 is returned and fimp->error is set
   appropriately. */
/* get_mhyp */
static glong get_playlist (FImport *fimp, glong mhyp_seek)
{
  guint32 i, mhipnum, mhod_num;
  glong nextseek, mhod_seek, mhip_seek;
  guint32 header_len;
  Itdb_Playlist *plitem = NULL;
  FContents *cts;

#if ITUNESDB_DEBUG
  fprintf(stderr, "mhyp seek: %x\n", (int)mhyp_seek);
#endif
  g_return_val_if_fail (fimp, -1);
  g_return_val_if_fail (fimp->idtree, -1);
  g_return_val_if_fail (fimp->pos_glist == NULL, -1);
  g_return_val_if_fail (fimp->pos_len == 0, -1);

  cts = fimp->fcontents;

  if (!check_header_seek (cts, "mhyp", mhyp_seek))
  {
      if (cts->error)
	  g_propagate_error (&fimp->error, cts->error);
      return -1;
  }
  header_len = get32lint (cts, mhyp_seek+4); /* length of header */
  CHECK_ERROR (fimp, -1);

  if (header_len < 48)
  {
      set_error_a_header_smaller_than_b (&fimp->error,
					 "mhyp",
					 header_len, 48,
					 mhyp_seek, cts->filename);
      return -1;
  }

  /* Check if entire mhyp can be read -- that way we won't have to
   * check for read errors every time we access a single byte */

  check_seek (cts, mhyp_seek, header_len);
  CHECK_ERROR (fimp, -1);

  nextseek = mhyp_seek + get32lint (cts, mhyp_seek+8);/* possible begin of next PL */  mhod_num = get32lint (cts, mhyp_seek+12); /* number of MHODs we expect */
  mhipnum = get32lint (cts, mhyp_seek+16); /* number of tracks
					       (mhips) in playlist */

  plitem = itdb_playlist_new (NULL, FALSE);

  /* Some Playlists have added 256 to their type -- I don't know what
     it's for, so we just ignore it for now -> & 0xff */
  plitem->type = get8int (cts, mhyp_seek+20);
  plitem->flag1 = get8int (cts, mhyp_seek+21);
  plitem->flag2 = get8int (cts, mhyp_seek+22);
  plitem->flag3 = get8int (cts, mhyp_seek+23);
  plitem->timestamp = get32lint (cts, mhyp_seek+24);
  plitem->timestamp = device_time_mac_to_time_t (fimp->itdb->device, plitem->timestamp);
  plitem->id = get64lint (cts, mhyp_seek+28);
/*  plitem->mhodcount = get32lint (cts, mhyp_seek+36);   */
/*  plitem->libmhodcount = get16lint (cts, mhyp_seek+40);*/
  plitem->podcastflag = get16lint (cts, mhyp_seek+42);
  plitem->sortorder = get32lint (cts, mhyp_seek+44);

  mhod_seek = mhyp_seek + header_len;

  for (i=0; i < mhod_num; ++i)
  {
      gint32 type;
      MHODData mhod;

      type = get_mhod_type (cts, mhod_seek, &header_len);
      CHECK_ERROR (fimp, -1);
      if (header_len != -1)
      {
	  switch ((enum MHOD_ID)type)
	  {
	  case MHOD_ID_PLAYLIST:
	      /* here we could do something about the playlist settings */
	      break;
	  case MHOD_ID_TITLE:
	      mhod = get_mhod (fimp, mhod_seek, &header_len);
	      CHECK_ERROR (fimp, -1);
	      if (mhod.valid && mhod.data.string)
	      {
		  /* sometimes there seem to be two mhod TITLE headers */
		  g_free (plitem->name);
		  plitem->name = mhod.data.string;
		  mhod.valid = FALSE;
	      }
	      break;
	  case MHOD_ID_SPLPREF:
	      mhod = get_mhod (fimp, mhod_seek, &header_len);
	      CHECK_ERROR (fimp, -1);
	      if (mhod.valid && mhod.data.splpref)
	      {
		  plitem->is_spl = TRUE;
		  memcpy (&plitem->splpref, mhod.data.splpref,
			  sizeof (Itdb_SPLPref));
		  g_free (mhod.data.splpref);
		  mhod.valid = FALSE;
	      }
	      break;
	  case MHOD_ID_SPLRULES:
	      mhod = get_mhod (fimp, mhod_seek, &header_len);
	      CHECK_ERROR (fimp, -1);
	      if (mhod.valid && mhod.data.splrules)
	      {
		  plitem->is_spl = TRUE;
		  memcpy (&plitem->splrules, mhod.data.splrules,
			  sizeof (Itdb_SPLRules));
		  g_free (mhod.data.splrules);
		  mhod.valid = FALSE;
	      }
	      break;
	  case MHOD_ID_PATH:
	  case MHOD_ID_ALBUM:
	  case MHOD_ID_ARTIST:
	  case MHOD_ID_GENRE:
	  case MHOD_ID_FILETYPE:
	  case MHOD_ID_COMMENT:
	  case MHOD_ID_CATEGORY:
	  case MHOD_ID_COMPOSER:
	  case MHOD_ID_GROUPING:
	  case MHOD_ID_DESCRIPTION:
	  case MHOD_ID_PODCASTURL:
	  case MHOD_ID_PODCASTRSS:
	  case MHOD_ID_SUBTITLE:
	  case MHOD_ID_TVSHOW:
	  case MHOD_ID_TVEPISODE:
	  case MHOD_ID_TVNETWORK:
	  case MHOD_ID_ALBUMARTIST:
	  case MHOD_ID_KEYWORDS:
	  case MHOD_ID_CHAPTERDATA:
	  case MHOD_ID_SORT_ARTIST:
	  case MHOD_ID_SORT_TITLE:
	  case MHOD_ID_SORT_ALBUM:
	  case MHOD_ID_SORT_ALBUMARTIST:
	  case MHOD_ID_SORT_COMPOSER:
	  case MHOD_ID_SORT_TVSHOW:
	      /* these are not expected here */
	      break;
	  case MHOD_ID_LIBPLAYLISTINDEX:
	      /* this I don't know how to handle */
	      break;
	  }
	  mhod_seek += header_len;
      }
      else
      {
	  g_warning (_("Number of MHODs in mhyp at %ld inconsistent in file '%s'."),
		     mhyp_seek, cts->filename);
	  break;
      }
  }

  if (!plitem->name)
  {   /* we did not read a valid mhod TITLE header -> */
      /* we simply make up our own name */
      if (itdb_playlist_is_mpl (plitem))
	  plitem->name = g_strdup (_("Master-PL"));
      else
      {
	  if (itdb_playlist_is_podcasts (plitem))
	      plitem->name = g_strdup (_("Podcasts"));
	  else
	      plitem->name = g_strdup (_("Playlist"));
      }
  }

#if ITUNESDB_DEBUG
  fprintf(stderr, "pln: %s(%d Itdb_Tracks) \n", plitem->name, (int)tracknum);
#endif

  /* add new playlist */
  itdb_playlist_add (fimp->itdb, plitem, -1);

  mhip_seek = mhod_seek;

  i=0; /* tracks read */
  for (i=0; i < mhipnum; ++i)
  {
      mhip_seek = get_mhip (fimp, plitem, mhip_seek);
      if (mhip_seek == -1)
      {
	  g_set_error (&fimp->error,
		       ITDB_FILE_ERROR,
		       ITDB_FILE_ERROR_CORRUPT,
		       _("iTunesDB corrupt: number of mhip sections inconsistent in mhyp starting at %ld in file '%s'."),
		       mhyp_seek, cts->filename);
	  return -1;
      }
  }	  


  g_list_free (fimp->pos_glist);
  fimp->pos_glist = NULL;
  fimp->pos_len = 0;
  return nextseek;
}


/* returns a pointer to the next header or -1 on error. fimp->error is
   set appropriately. If no "mhit" header is found at the location
   specified, -1 is returned but no error is set. */
static glong get_mhit (FImport *fimp, glong mhit_seek)
{
  Itdb_Track *track;
  gchar *entry_utf8;
  gint32 type;
  guint32 header_len;
  guint32 zip;
  struct playcount *playcount;
  guint32 i, mhod_nums;
  FContents *cts;
  glong seek = mhit_seek;

#if ITUNESDB_DEBUG
  fprintf(stderr, "get_mhit seek: %x\n", (int)seek);
#endif

  g_return_val_if_fail (fimp, -1);

  cts = fimp->fcontents;

  if (!check_header_seek (cts, "mhit", seek))
  {
      if (cts->error)
	  g_propagate_error (&fimp->error, cts->error);
      return -1;
  }

  header_len = get32lint (cts, seek+4);
  CHECK_ERROR (fimp, -1);

  /* size of the mhit header: For dbversion <= 0x0b (iTunes 4.7 and
     earlier), the length is 0x9c. As of dbversion 0x0c and 0x0d
     (iTunes 4.7.1 - iTunes 4.9), the size is 0xf4. */
  if (header_len < 0x9c)
  {
      set_error_a_header_smaller_than_b (&fimp->error,
					 "mhit",
					 header_len, 0x9c,
					 seek, cts->filename);
      return -1;
  }

  /* Check if entire mhit can be read -- that way we won't have to
   * check for read errors every time we access a single byte */

  check_seek (cts, seek, header_len);

  mhod_nums = get32lint (cts, seek+12);
  CHECK_ERROR (fimp, -1);


  track = itdb_track_new ();

  if (header_len >= 0x9c)
  {
      guint32 val32;
      track->id = get32lint(cts, seek+16);         /* iPod ID          */
      track->visible = get32lint (cts, seek+20);
      track->filetype_marker = get32lint (cts, seek+24);
      track->type1 = get8int (cts, seek+28);
      track->type2 = get8int (cts, seek+29);
      track->compilation = get8int (cts, seek+30);
      track->rating = get8int (cts, seek+31);
      track->time_modified = get32lint(cts, seek+32); /* time added       */
      track->time_modified = device_time_mac_to_time_t (fimp->itdb->device, 
						      track->time_modified);
      track->size = get32lint(cts, seek+36);       /* file size        */
      track->tracklen = get32lint(cts, seek+40);   /* time             */
      track->track_nr = get32lint(cts, seek+44);   /* track number     */
      track->tracks = get32lint(cts, seek+48);     /* nr of tracks     */
      track->year = get32lint(cts, seek+52);       /* year             */
      track->bitrate = get32lint(cts, seek+56);    /* bitrate          */
      val32 = get32lint (cts, seek+60);
      track->samplerate = val32 >> 16;             /* sample rate      */
      track->samplerate_low = val32 & 0xffff;      /* remaining bits   */
      track->volume = get32lint(cts, seek+64);     /* volume adjust    */
      track->starttime = get32lint (cts, seek+68);
      track->stoptime = get32lint (cts, seek+72);
      track->soundcheck = get32lint (cts, seek+76);/* soundcheck       */
      track->playcount = get32lint (cts, seek+80); /* playcount        */
      track->playcount2 = get32lint (cts, seek+84);
      track->time_played = get32lint(cts, seek+88);/* last time played */
      track->time_played = device_time_mac_to_time_t (fimp->itdb->device, 
						    track->time_played);
      track->cd_nr = get32lint(cts, seek+92);      /* CD nr            */
      track->cds = get32lint(cts, seek+96);        /* CD nr of..       */
      /* Apple Store/Audible User ID (for DRM'ed files only, set to 0
	 otherwise). */
      track->drm_userid = get32lint (cts, seek+100);
      track->time_added = get32lint(cts, seek+104);/* last mod. time */
      track->time_added = device_time_mac_to_time_t (fimp->itdb->device, 
						   track->time_added);
      track->bookmark_time = get32lint (cts, seek+108);/*time bookmarked*/
      track->dbid = get64lint (cts, seek+112);
      track->checked = get8int (cts, seek+120); /*Checked/Unchecked: 0/1*/
      /* The rating set by the application, as opposed to the rating
	 set on the iPod itself */
      track->app_rating = get8int (cts, seek+121);
      track->BPM = get16lint (cts, seek+122);
      track->artwork_count = get16lint (cts, seek+124);
      track->unk126 = get16lint (cts, seek+126);
      track->artwork_size = get32lint (cts, seek+128);
      track->unk132 = get32lint (cts, seek+132);
      track->samplerate2 = get32lfloat (cts, seek+136);
      track->time_released = get32lint (cts, seek+140);
      track->time_released = device_time_mac_to_time_t (fimp->itdb->device,
						      track->time_released);
      track->unk144 = get16lint (cts, seek+144);
      track->unk146 = get16lint (cts, seek+146);
      track->unk148 = get32lint (cts, seek+148);
      track->unk152 = get32lint (cts, seek+152);
  }
  if (header_len >= 0xf4)
  {
      track->skipcount = get32lint (cts, seek+156);
      track->last_skipped = get32lint (cts, seek+160);
      track->last_skipped = device_time_mac_to_time_t (fimp->itdb->device, 
						     track->last_skipped);
      track->has_artwork = get8int (cts, seek+164);
      track->skip_when_shuffling = get8int (cts, seek+165);
      track->remember_playback_position = get8int (cts, seek+166);
      track->flag4 = get8int (cts, seek+167);
      track->dbid2 = get64lint (cts, seek+168);
      track->lyrics_flag = get8int (cts, seek+176);
      track->movie_flag = get8int (cts, seek+177);
      track->mark_unplayed = get8int (cts, seek+178);
      track->unk179 = get8int (cts, seek+179);
      track->unk180 = get32lint (cts, seek+180);
      track->pregap = get32lint (cts, seek+184);
      track->samplecount = get64lint (cts, seek+188);
      track->unk196 = get32lint (cts, seek+196);
      track->postgap = get32lint (cts, seek+200);
      track->unk204 = get32lint (cts, seek+204);
      track->mediatype = get32lint (cts, seek+208);
      track->season_nr = get32lint (cts, seek+212);
      track->episode_nr = get32lint (cts, seek+216);
      track->unk220 = get32lint (cts, seek+220);
      track->unk224 = get32lint (cts, seek+224);
      track->unk228 = get32lint (cts, seek+228);
      track->unk232 = get32lint (cts, seek+232);
      track->unk236 = get32lint (cts, seek+236);
      track->unk240 = get32lint (cts, seek+240);
  }
  if (header_len >= 0x148)
  {
      track->unk244 = get32lint (cts, seek+244);
      track->gapless_data = get32lint (cts, seek+248);
      track->unk252 = get32lint (cts, seek+252);
      track->gapless_track_flag = get16lint (cts, seek+256);
      track->gapless_album_flag = get16lint (cts, seek+258);
  }

  track->transferred = TRUE;                   /* track is on iPod! */

  seek += get32lint (cts, seek+4);             /* 1st mhod starts here! */
  CHECK_ERROR (fimp, -1);

  for (i=0; i<mhod_nums; ++i)
  {
      entry_utf8 = get_mhod_string (fimp, seek, &zip, &type);
      CHECK_ERROR (fimp, -1);
      if (entry_utf8 != NULL)
      {
	  switch ((enum MHOD_ID)type)
	  {
	  case MHOD_ID_TITLE:
	      track->title = entry_utf8;
	      break;
	  case MHOD_ID_PATH:
	      track->ipod_path = entry_utf8;
	      break;
	  case MHOD_ID_ALBUM:
	      track->album = entry_utf8;
	      break;
	  case MHOD_ID_ARTIST:
	      track->artist = entry_utf8;
	      break;
	  case MHOD_ID_GENRE:
	      track->genre = entry_utf8;
	      break;
	  case MHOD_ID_FILETYPE:
	      track->filetype = entry_utf8;
	      break;
	  case MHOD_ID_COMMENT:
	      track->comment = entry_utf8;
	      break;
	  case MHOD_ID_CATEGORY:
	      track->category = entry_utf8;
	      break;
	  case MHOD_ID_COMPOSER:
	      track->composer = entry_utf8;
	      break;
	  case MHOD_ID_GROUPING:
	      track->grouping = entry_utf8;
	      break;
	  case MHOD_ID_DESCRIPTION:
	      track->description = entry_utf8;
	      break;
	  case MHOD_ID_PODCASTURL:
	      track->podcasturl = entry_utf8;
	      break;
	  case MHOD_ID_PODCASTRSS:
	      track->podcastrss = entry_utf8;
	      break;
	  case MHOD_ID_SUBTITLE:
	      track->subtitle = entry_utf8;
	      break;
	  case MHOD_ID_TVSHOW:
	      track->tvshow = entry_utf8;
	      break;
	  case MHOD_ID_TVEPISODE:
	      track->tvepisode = entry_utf8;
	      break;
	  case MHOD_ID_TVNETWORK:
	      track->tvnetwork = entry_utf8;
	      break;
	  case MHOD_ID_ALBUMARTIST:
	      track->albumartist = entry_utf8;
	      break;
	  case MHOD_ID_KEYWORDS:
	      track->keywords = entry_utf8;
	      break;
	  case MHOD_ID_SORT_ARTIST:
	      track->sort_artist = entry_utf8;
	      break;
	  case MHOD_ID_SORT_TITLE:
	      track->sort_title = entry_utf8;
	      break;
	  case MHOD_ID_SORT_ALBUM:
	      track->sort_album = entry_utf8;
	      break;
	  case MHOD_ID_SORT_ALBUMARTIST:
	      track->sort_albumartist = entry_utf8;
	      break;
	  case MHOD_ID_SORT_COMPOSER:
	      track->sort_composer = entry_utf8;
	      break;
	  case MHOD_ID_SORT_TVSHOW:
	      track->sort_tvshow = entry_utf8;
	      break;
	  case MHOD_ID_SPLPREF:
	  case MHOD_ID_SPLRULES:
	  case MHOD_ID_LIBPLAYLISTINDEX:
	  case MHOD_ID_PLAYLIST:
	  case MHOD_ID_CHAPTERDATA:
	      g_free (entry_utf8);
	      break;
	  }
      }
      else
      {
	  MHODData mhod;
	  switch (type)
	  {
	  case MHOD_ID_CHAPTERDATA:
	      /* we just read the entire chapterdata info until we
		 have a better way to parse and represent it */
	      mhod = get_mhod (fimp, seek, &zip);
	      if (mhod.valid && mhod.data.chapterdata_raw)
	      {
		  track->chapterdata_raw = mhod.data.chapterdata_raw;
		  track->chapterdata_raw_length =
		      zip - get32lint (cts, seek+4);
		  mhod.valid = FALSE;
	      }
	      break;
	  default:
/*
	  printf ("found mhod type %d at %lx inside mhit starting at %lx\n",
	  type, seek, mhit_seek);*/
	      break;
	  }
      }
      seek += zip;
  }

  playcount = playcount_get_next (fimp);
  if (playcount)
  {
      if (playcount->rating != NO_PLAYCOUNT)
      {
	  if (track->rating != playcount->rating)
	  {
	      /* backup original rating to app_rating */
	      track->app_rating = track->rating;
	      track->rating = playcount->rating;
	  }
      }
      if (playcount->time_played)
	  track->time_played = playcount->time_played;

      if (playcount->bookmark_time)
	  track->bookmark_time = playcount->bookmark_time;

      track->playcount += playcount->playcount;
      if (playcount->playcount != 0)
      {   /* unmark the 'unplayed' flag */
	  track->mark_unplayed = 0x01;
      }
      track->recent_playcount = playcount->playcount;

      track->skipcount += playcount->skipcount;
      track->recent_skipcount = playcount->skipcount;

      g_free (playcount);
  }
  itdb_track_add (fimp->itdb, track, -1);
  return seek;
}


/* Called by read_OTG_playlists(): OTG playlist stored in @cts by
 * adding a new playlist (named @plname) with the tracks specified in
 * @cts. If @plname is NULL, a standard name will be substituted */
/* Returns FALSE on error, TRUE on success. On error @fimp->error will
 * be set apropriately. */
static gboolean process_OTG_file (FImport *fimp, FContents *cts,
				  const gchar *plname)
{
    guint32 header_length, entry_length, entry_num;

    g_return_val_if_fail (fimp && cts, FALSE);
    g_return_val_if_fail (fimp->itdb, FALSE);

    if (!plname) plname = _("OTG Playlist");

    if (!check_header_seek (cts, "mhpo", 0))
    {
	if (cts->error)
	{
	    g_propagate_error (&fimp->error, cts->error);
	    return FALSE;
	}
	cts->reversed = TRUE;
	if (!check_header_seek (cts, "mhpo", 0))
	{
	    /* cts->error can't be set as already checked above */
	    /* set error */
	    g_return_val_if_fail (cts->filename, FALSE);
	    g_set_error (&fimp->error,
			 ITDB_FILE_ERROR,
			 ITDB_FILE_ERROR_CORRUPT,
			 _("Not a OTG playlist file: '%s' (missing mhpo header)."),
			 cts->filename);
	    return FALSE;
	}
    }
    header_length = get32lint (cts, 4);
    CHECK_ERROR (fimp, FALSE);
    /* all the headers I know are 0x14 long -- if this one is
       longer we can simply ignore the additional information */
    if (header_length < 0x14)
    {
	g_set_error (&fimp->error,
		     ITDB_FILE_ERROR,
		     ITDB_FILE_ERROR_CORRUPT,
		     _("OTG playlist file ('%s'): header length smaller than expected (%d<20)."),
		     cts->filename, header_length);
	return FALSE;
    }
    entry_length = get32lint (cts, 8);
    CHECK_ERROR (fimp, FALSE);
    /* all the entries I know are 0x04 long */
    if (entry_length < 0x04)
    {
	g_set_error (&fimp->error,
		     ITDB_FILE_ERROR,
		     ITDB_FILE_ERROR_CORRUPT,
		     _("OTG playlist file ('%s'): entry length smaller than expected (%d<4)."),
		     cts->filename, entry_length);
	return FALSE;
    }
    /* number of entries */
    entry_num = get32lint (cts, 12);
    CHECK_ERROR (fimp, FALSE);

    if (entry_num > 0)
    {
	gint i;
	Itdb_Playlist *pl;

	pl = itdb_playlist_new (plname, FALSE);
	/* Add new playlist */
	itdb_playlist_add (fimp->itdb, pl, -1);

	/* Add items */
	for (i=0; i<entry_num; ++i)
	{
	    Itdb_Track *track;
	    guint32 num = get32lint (cts,
				     header_length + entry_length *i);
	    CHECK_ERROR (fimp, FALSE);

	    track = g_list_nth_data (fimp->itdb->tracks, num);
	    if (track)
	    {
		itdb_playlist_add_track (pl, track, -1);
	    }
	    else
	    {
		g_set_error (&fimp->error,
			     ITDB_FILE_ERROR,
			     ITDB_FILE_ERROR_CORRUPT,
			     _("OTG playlist file '%s': reference to non-existent track (%d)."),
			     cts->filename, num);
		return FALSE;
	    }
	}
    }
    return TRUE;
}




/* Add the On-The-Go Playlist(s) to the database */
/* The OTG-Files are located in the directory given by
   fimp->itdb->itdb_filename.
   On error FALSE is returned and fimp->error is set accordingly. */
static gboolean read_OTG_playlists (FImport *fimp)
{
    gchar *db[] = {"OTGPlaylistInfo", NULL};
    gchar *dirname, *otgname;

    g_return_val_if_fail (fimp, FALSE);
    g_return_val_if_fail (fimp->itdb, FALSE);
    g_return_val_if_fail (fimp->itdb->filename, FALSE);

    dirname = g_path_get_dirname (fimp->itdb->filename);

    otgname = itdb_resolve_path (dirname, (const gchar **)db);


    /* only parse if "OTGPlaylistInfo" exists */
    if (otgname)
    {
	gchar *filename;
	gint i=1;
	do
	{
	    db[0] = g_strdup_printf ("OTGPlaylistInfo_%d", i);
	    filename = itdb_resolve_path (dirname, (const gchar **)db);
	    g_free (db[0]);
	    if (filename)
	    {
		FContents *cts = fcontents_read (filename, &fimp->error);
		if (cts)
		{
		    gchar *plname = g_strdup_printf (_("OTG Playlist %d"), i);
		    process_OTG_file (fimp, cts, plname);
		    g_free (plname);
		    fcontents_free (cts);
		}
		g_free (filename);
	    }
	    if (fimp->error) break;
	    ++i;
	} while (filename);
	g_free (otgname);
    }
    g_free (dirname);
    return TRUE;
}


/* Read the tracklist (mhlt). mhsd_seek must point to type 1 mhsd
   (this is treated as a programming error) */
/* Return value:
   TRUE: import successful
   FALSE: error occured, fimp->error is set */
static gboolean parse_tracks (FImport *fimp, glong mhsd_seek)
{
    FContents *cts;
    glong mhlt_seek, seek;
    guint32 nr_tracks, i;

    g_return_val_if_fail (fimp, FALSE);
    g_return_val_if_fail (fimp->itdb, FALSE);
    g_return_val_if_fail (fimp->fcontents, FALSE);
    g_return_val_if_fail (fimp->fcontents->filename, FALSE);
    g_return_val_if_fail (mhsd_seek >= 0, FALSE);

    cts = fimp->fcontents;

    g_return_val_if_fail (check_header_seek (cts, "mhsd", mhsd_seek),
			  FALSE);

   /* The mhlt header should be the next after the mhsd header. In
      order to allow slight changes in the format, we skip headers
      until we find an mhlt inside the given mhsd */

    mhlt_seek = find_next_a_in_b (cts, "mhlt", mhsd_seek, mhsd_seek);
    CHECK_ERROR (fimp, FALSE);

    if (mhlt_seek == -1)
    {
	set_error_a_not_found_in_b (&fimp->error,
				    "mhlt", "mhsd", mhsd_seek);
	return FALSE;
    }

    /* Now we are at the mhlt */
    nr_tracks = get32lint (cts, mhlt_seek+8);
    CHECK_ERROR (fimp, FALSE);

    seek = find_next_a_in_b (cts, "mhit", mhsd_seek, mhlt_seek);
    CHECK_ERROR (fimp, FALSE);
    /* seek should now point to the first mhit */
    for (i=0; i<nr_tracks; ++i)
    {
	/* seek could be -1 if first mhit could not be found */
	if (seek != -1)
	    seek = get_mhit (fimp, seek);
	if (fimp->error) return FALSE;
	if (seek == -1)
	{   /* this should not be -- issue warning */
	    g_warning (_("iTunesDB corrupt: number of tracks (mhit hunks) inconsistent. Trying to continue.\n"));
	    break;
	}
    }
    return TRUE;
}



/* Read the playlists (mhlp). mhsd_seek must point to type 2 or type 3
   mhsd (this is treated as a programming error) */
/* Return value:
   TRUE: import successful
   FALSE: error occured, fimp->error is set */
static gboolean parse_playlists (FImport *fimp, glong mhsd_seek)
{
    FContents *cts;
    glong seek, mhlp_seek;
    guint32 nr_playlists, i;

    g_return_val_if_fail (fimp, FALSE);
    g_return_val_if_fail (fimp->itdb, FALSE);
    g_return_val_if_fail (fimp->fcontents, FALSE);
    g_return_val_if_fail (fimp->fcontents->filename, FALSE);
    g_return_val_if_fail (mhsd_seek >= 0, FALSE);

    cts = fimp->fcontents;

    g_return_val_if_fail (check_header_seek (cts, "mhsd", mhsd_seek),
			  FALSE);

    /* The mhlp header should be the next after the mhsd header. In
       order to allow slight changes in the format, we skip headers
       until we find an mhlp inside the given mhsd */

    mhlp_seek = find_next_a_in_b (cts, "mhlp", mhsd_seek, mhsd_seek);
    CHECK_ERROR (fimp, FALSE);

    if (mhlp_seek == -1)
    {
	set_error_a_not_found_in_b (&fimp->error,
				    "mhlp", "mhsd", mhsd_seek);
	return FALSE;
    }
    /* Now we are at the mhlp */

    nr_playlists = get32lint (cts, mhlp_seek+8);
    CHECK_ERROR (fimp, FALSE);

    /* Create track-id tree for quicker track lookup */
    fimp->idtree = itdb_track_id_tree_create (fimp->itdb);

    seek = find_next_a_in_b (cts, "mhyp", mhsd_seek, mhlp_seek);
    CHECK_ERROR (fimp, FALSE);
    /* seek should now point to the first mhit */
    for (i=0; i<nr_playlists; ++i)
    {
	/* seek could be -1 if first mhyp could not be found */
	if (seek != -1)
	    seek = get_playlist (fimp, seek);
	if (fimp->error) return FALSE;
	if (seek == -1)
	{   /* this should not be -- issue warning */
	    g_warning (_("iTunesDB possibly corrupt: number of playlists (mhyp hunks) inconsistent. Trying to continue.\n"));
	    break;
	}
    }

    itdb_track_id_tree_destroy (fimp->idtree);
    fimp->idtree = NULL;

    return TRUE;
}

static gboolean parse_fimp (FImport *fimp)
{
    glong seek=0;
    FContents *cts;
    glong mhsd_1, mhsd_2, mhsd_3;

    g_return_val_if_fail (fimp, FALSE);
    g_return_val_if_fail (fimp->itdb, FALSE);
    g_return_val_if_fail (fimp->fcontents, FALSE);
    g_return_val_if_fail (fimp->fcontents->filename, FALSE);

    cts = fimp->fcontents;

    /* get the positions of the various mhsd */
    /* type 1: track list */
    mhsd_1 = find_mhsd (cts, 1);
    CHECK_ERROR (fimp, FALSE);
    /* type 2: standard playlist section -- Podcasts playlist will be
       just an ordinary playlist */
    mhsd_2 = find_mhsd (cts, 2);
    CHECK_ERROR (fimp, FALSE);
    /* type 3: playlist section with special version of Podcasts
       playlist (optional) */
    mhsd_3 = find_mhsd (cts, 3);
    CHECK_ERROR (fimp, FALSE);

    fimp->itdb->version = get32lint (cts, seek+16);
    CHECK_ERROR (fimp, FALSE);
    fimp->itdb->id = get64lint (cts, seek+24);
    CHECK_ERROR (fimp, FALSE);

    if (mhsd_1 == -1)
    {   /* Very bad: no type 1 mhsd which should hold the tracklist */
	g_set_error (&fimp->error,
		     ITDB_FILE_ERROR,
		     ITDB_FILE_ERROR_CORRUPT,
		     _("iTunesDB '%s' corrupt: Could not find tracklist (no mhsd type 1 section found)"),
		     cts->filename);
	return FALSE;
    }

    /* copy the 'reversed endian flag' */
    if (cts->reversed) {
      fimp->itdb->device->byte_order = G_BIG_ENDIAN;
    } else {
      fimp->itdb->device->byte_order = G_LITTLE_ENDIAN;
    }
#if 0
    fimp->itdb->device->endianess_set = TRUE;
    fimp->itdb->device->endianess_reversed = cts->reversed;
#endif

    parse_tracks (fimp, mhsd_1);
    if (fimp->error) return FALSE;

    if (mhsd_3 != -1)
	parse_playlists (fimp, mhsd_3);
    else if (mhsd_2 != -1)
	parse_playlists (fimp, mhsd_2);
    else
    {  /* Very bad: no type 2 or type 3 mhsd which should hold the
	  playlists */
	g_set_error (&fimp->error,
		     ITDB_FILE_ERROR,
		     ITDB_FILE_ERROR_CORRUPT,
		     _("iTunesDB '%s' corrupt: Could not find playlists (no mhsd type 2 or type 3 sections found)"),
		     cts->filename);
	return FALSE;
    }

    return TRUE;
}



/* Set @error with standard error message */
static void error_no_itunes_dir (const gchar *mp, GError **error)
{
    gchar *str;

    g_return_if_fail (mp);
    g_return_if_fail (error);

    str = g_build_filename (mp, "iPod_Control", "iTunes", NULL);
    g_set_error (error,
		 ITDB_FILE_ERROR,
		 ITDB_FILE_ERROR_NOTFOUND,
		 _("iTunes directory not found: '%s' (or similar)."),
		 str);
    g_free (str);
}

/* Set @error with standard error message */
static void error_no_music_dir (const gchar *mp, GError **error)
{
    gchar *str;

    g_return_if_fail (mp);
    g_return_if_fail (error);

    str = g_build_filename (mp, "iPod_Control", "Music", NULL);
    g_set_error (error,
		 ITDB_FILE_ERROR,
		 ITDB_FILE_ERROR_NOTFOUND,
		 _("Music directory not found: '%s' (or similar)."),
		 str);
    g_free (str);
}

#if 0
/* Set @error with standard error message */
static void error_no_control_dir (const gchar *mp, GError **error)
{
    gchar *str;

    g_return_if_fail (mp);
    g_return_if_fail (error);

    str = g_build_filename (mp, "iPod_Control", NULL);
    g_set_error (error,
		 ITDB_FILE_ERROR,
		 ITDB_FILE_ERROR_NOTFOUND,
		 _("Control directory not found: '%s' (or similar)."),
		 str);
    g_free (str);
}
#endif


static gboolean
itdb_parse_internal (Itdb_iTunesDB *itdb, GError **error)
{
    FImport *fimp;
    gboolean success = FALSE;

    g_return_val_if_fail (itdb->filename != NULL, FALSE);
    
    fimp = g_new0 (FImport, 1);
    fimp->itdb = itdb;

    fimp->fcontents = fcontents_read (itdb->filename, error);

    if (fimp->fcontents)
    {
	if (playcounts_init (fimp))
	{
	    if (parse_fimp (fimp))
	    {
		if (read_OTG_playlists (fimp))
		{
		    success = TRUE;
		}
	    }
	}
    }

    if (fimp->error)
	g_propagate_error (error, fimp->error);

    itdb_free_fimp (fimp);

    return success;
}

/**
 * itdb_parse:
 * @mp: mount point of the iPod (eg "/mnt/ipod) in local encoding
 * @error: return location for a #GError or NULL
 *
 * Parse the Itdb_iTunesDB of the iPod located at @mp
 *
 * Return value: a newly allocated #Itdb_iTunesDB struct holding the tracks and
 * the playlists present on the iPod at @mp, NULL if @mp isn't an iPod mount
 * point. If non-NULL, the #Itdb_iTunesDB is to be freed with itdb_free() when
 * it's no longer needed
 **/
Itdb_iTunesDB *itdb_parse (const gchar *mp, GError **error)
{
    gchar *filename;
    gchar *itunes_dir;
    Itdb_iTunesDB *itdb = NULL;
    const gchar *db[] = {"iTunesDB", NULL};


    itunes_dir = itdb_get_itunes_dir (mp);

    if (!itunes_dir)
    {
	error_no_itunes_dir (mp, error);
	return NULL;
    }

    filename = itdb_resolve_path (itunes_dir, db);

    if (filename)
    {
	itdb = itdb_new ();
	
	if (itdb)
	{
	    gboolean success;

	    itdb_set_mountpoint (itdb, mp);
	    itdb->filename = filename;
	    success = itdb_parse_internal (itdb, error);
	    if (success)
	    {
		/* We don't test the return value of ipod_parse_artwork_db
		 * since the database content will be consistent even if
		 * we fail to get the various thumbnails, we ignore the
		 * error since older ipods don't have thumbnails.

		 * FIXME: this probably should go into itdb_parse_file,
		 * but I don't understand its purpose, and
		 * ipod_parse_artwork_db needs the mountpoint field from
		 * the itdb, which may not be available in the other
		 * function

		 * JCS: itdb_parse_file is used to read local repositories
		 * (usually repositories stored in
		 * ~/.gtkpod). ipod_parse_artwork_db (and the
		 * corresponding artbook write function) should probably
		 * be expanded to look for (write) the required files into
		 * the same directory as itdb->filename in case
		 * itdb->mountpoint does not exist. Because several local
		 * repositories may exist in the same directory, the names
		 * should be modified by the repository name.
		 */
		ipod_parse_artwork_db (itdb);
	    }
	    else
	    {
		itdb_free (itdb);
		itdb = NULL;
	    }
	}
    }
    else
    {
	gchar *str = g_build_filename (mp, db[0], db[1], db[2], db[3], NULL);
	g_set_error (error,
		     ITDB_FILE_ERROR,
		     ITDB_FILE_ERROR_NOTFOUND,
		     _("File not found: '%s'."),
		     str);
	g_free (str);
    }
    g_free (itunes_dir);
    return itdb;
}


/**
 * itdb_parse_file:
 * @filename: path to a file in iTunesDB format
 * @error: return location for a #GError or NULL
 *
 *  Same as itunesdb_parse(), but filename is specified directly.
 *
 * Return value: a newly allocated #Itdb_iTunesDB struct holding the tracks and
 * the playlists present in @filename, NULL if @filename isn't a parsable 
 * iTunesDB file. If non-NULL, the #Itdb_iTunesDB is to be freed with 
 * itdb_free() when it's no longer needed
 **/
Itdb_iTunesDB *itdb_parse_file (const gchar *filename, GError **error)
{
    Itdb_iTunesDB *itdb;
    gboolean success;

    g_return_val_if_fail (filename, NULL);

    itdb = itdb_new ();
    itdb->filename = g_strdup (filename);

    success = itdb_parse_internal (itdb, error);
    if (!success)
    {
	itdb_free (itdb);
	itdb = NULL;
    }

    return itdb;
}


/* up to here we had the functions for reading the iTunesDB               */
/* ---------------------------------------------------------------------- */
/* from here on we have the functions for writing the iTunesDB            */

/* will expand @cts when necessary in order to accomodate @len bytes
   starting at @seek */
static void wcontents_maybe_expand (WContents *cts, gulong len,
				    gulong seek)
{
    g_return_if_fail (cts);

    while (cts->pos+len > cts->total)
    {
	cts->total += WCONTENTS_STEPSIZE;
	cts->contents = g_realloc (cts->contents, cts->total);
    }
}


/* Write @data, @n bytes long to position @seek. Will always be
 * successful because glib terminates when out of memory */
static void put_data_seek (WContents *cts, gchar *data,
			   gulong len, gulong seek)
{
    g_return_if_fail (cts);

    if (len != 0)
    {
	g_return_if_fail (data);
	wcontents_maybe_expand (cts, len, seek);

	memcpy (&cts->contents[seek], data, len);
	/* adjust end position if necessary */
	if (seek+len > cts->pos)
	    cts->pos = seek+len;
    }
}



/* Write @data, @n bytes long to end of @cts. Will always be
 * successful because glib terminates when out of memory */
static void put_data (WContents *cts, gchar *data, gulong len)
{
    g_return_if_fail (cts);

    put_data_seek (cts, data, len, cts->pos);
}


/* Write @string without trailing Null to end of @cts. Will always be
 * successful because glib terminates when out of memory */
static void put_string (WContents *cts, gchar *string)
{
    g_return_if_fail (cts);
    g_return_if_fail (string);

    put_data (cts, string, strlen(string));
}

/* Write 4-byte long @header identifcation taking into account
 * possible reversed endianess */
static void put_header (WContents *cts, gchar *header)
{
    gchar rdata[4];
    gint i, offset, sign;


    g_return_if_fail (cts);
    g_return_if_fail (header);
    g_return_if_fail (strlen (header) == 4);

    /* reverse data for write if necessary */
    if (cts->reversed)
    {
	offset = 3;
	sign = -1;
    }
    else
    {
	offset = 0;
	sign = 1;
    }
    for (i=0; i<4; ++i)
    {
	    rdata[i] = header[offset + sign*i];
    }

    put_data (cts, rdata, 4);
}



/* ------------------------------------------------------------
   Little Endian
   ------------------------------------------------------------ */

/* Write 2-byte integer @n to @cts in little endian order. */
static void raw_put16lint (WContents *cts, guint16 n)
{
    n = GUINT16_TO_LE (n);
    put_data (cts, (gchar *)&n, 2);
}


/* Write 3-byte integer @n to @cts in big endian order. */
static void raw_put24lint (WContents *cts, guint32 n)
{
    gchar buf[3] ;
    buf[2] = (n >> 16) & 0xff ;
    buf[1] = (n >> 8)  & 0xff ;
    buf[0] = (n >> 0)  & 0xff ;
    put_data (cts, buf, 3);
}


/* Write 4-byte integer @n to @cts in little endian order. */
static void raw_put32lint (WContents *cts, guint32 n)
{
    n = GUINT32_TO_LE (n);
    put_data (cts, (gchar *)&n, 4);
}

/* Write 4 byte floating number */
static void raw_put32lfloat (WContents *cts, float f)
{
    union
    {
	guint32 i;
	float   f;
    } flt;

    if (sizeof (float) != 4)
    {
	raw_put32lint (cts, 0);
	g_return_if_reached ();
    }

    flt.f = f;
    raw_put32lint (cts, flt.i);
}


/* Write 4-byte integer @n to @cts at position @seek in little
   endian order. */
static void raw_put32lint_seek (WContents *cts, guint32 n, gulong seek)
{
    n = GUINT32_TO_LE (n);
    put_data_seek (cts, (gchar *)&n, 4, seek);
}


/* Write 8-byte integer @n to @cts in big little order. */
static void raw_put64lint (WContents *cts, guint64 n)
{
    n = GUINT64_TO_LE (n);
    put_data (cts, (gchar *)&n, 8);
}


/* ------------------------------------------------------------
   Big Endian
   ------------------------------------------------------------ */

/* Write 2-byte integer @n to @cts in big endian order. */
static void raw_put16bint (WContents *cts, guint16 n)
{
    n = GUINT16_TO_BE (n);
    put_data (cts, (gchar *)&n, 2);
}


/* Write 3-byte integer @n to @cts in big endian order. */
static void raw_put24bint (WContents *cts, guint32 n)
{
    gchar buf[3] ;
    buf[0] = (n >> 16) & 0xff ;
    buf[1] = (n >> 8)  & 0xff ;
    buf[2] = (n >> 0)  & 0xff ;
    put_data (cts, buf, 3);
}

/* Write 4-byte integer @n to @cts in big endian order. */
static void raw_put32bint (WContents *cts, guint32 n)
{
    n = GUINT32_TO_BE (n);
    put_data (cts, (gchar *)&n, 4);
}


/* Write 4-byte integer @n to @cts at position @seek in big
   endian order. */
static void raw_put32bint_seek (WContents *cts, guint32 n, gulong seek)
{
    n = GUINT32_TO_BE (n);
    put_data_seek (cts, (gchar *)&n, 4, seek);
}


/* Write 4 byte floating number */
static void raw_put32bfloat (WContents *cts, float f)
{
    union
    {
	guint32 i;
	float   f;
    } flt;

    if (sizeof (float) != 4)
    {
	raw_put32bint (cts, 0);
	g_return_if_reached ();
    }

    flt.f = f;
    raw_put32bint (cts, flt.i);
}


/* Write 8-byte integer @n to cts in big endian order. */
static void raw_put64bint (WContents *cts, guint64 n)
{
    n = GUINT64_TO_BE (n);
    put_data (cts, (gchar *)&n, 8);
}


/* ------------------------------------------------------------
   Not Endian Dependent
   ------------------------------------------------------------ */

/* Write 1-byte integer @n to @cts */
static void put8int (WContents *cts, guint8 n)
{
    put_data (cts, (gchar *)&n, 1);
}


/* Append @n times 2-byte-long zeros */
static void put16_n0 (WContents *cts, gulong n)
{
    g_return_if_fail (cts);

    if (n>0)
    {
	wcontents_maybe_expand (cts, 2*n, cts->pos);
	memset (&cts->contents[cts->pos], 0, 2*n);
	cts->pos += 2*n;
    }
}

/* Append @n times 4-byte-long zeros */
static void put32_n0 (WContents *cts, gulong n)
{
    g_return_if_fail (cts);

    if (n>0)
    {
	wcontents_maybe_expand (cts, 4*n, cts->pos);
	memset (&cts->contents[cts->pos], 0, 4*n);
	cts->pos += 4*n;
    }
}


/* ------------------------------------------------------------
   Reversed Endian Sensitive (little endian)
   ------------------------------------------------------------ */

static void put16lint (WContents *cts, guint16 n)
{
    if (!cts->reversed)
	raw_put16lint (cts, n);
    else
	raw_put16bint (cts, n);
}
#if 0
static void put24lint (WContents *cts, guint32 n)
{
    if (!cts->reversed)
	raw_put24lint (cts, n);
    else
	raw_put24bint (cts, n);
}
#endif
static void put32lint (WContents *cts, guint32 n)
{
    if (!cts->reversed)
	raw_put32lint (cts, n);
    else
	raw_put32bint (cts, n);
}

static void put32lfloat (WContents *cts, float f)
{
    if (!cts->reversed)
	raw_put32lfloat (cts, f);
    else
	raw_put32bfloat (cts, f);
}

static void put32lint_seek (WContents *cts, guint32 n, gulong seek)
{
    if (!cts->reversed)
	raw_put32lint_seek (cts, n, seek);
    else
	raw_put32bint_seek (cts, n, seek);
}


static void put64lint (WContents *cts, guint64 n)
{
    if (!cts->reversed)
	raw_put64lint (cts, n);
    else
	raw_put64bint (cts, n);
}

/* ------------------------------------------------------------
   Reversed Endian Sensitive (big endian)
   ------------------------------------------------------------ */
#if 0
static void put16bint (WContents *cts, guint16 n)
{
    if (cts->reversed)
	raw_put16lint (cts, n);
    else
	raw_put16bint (cts, n);
}
#endif
static void put24bint (WContents *cts, guint32 n)
{
    if (cts->reversed)
	raw_put24lint (cts, n);
    else
	raw_put24bint (cts, n);
}

static void put32bint (WContents *cts, guint32 n)
{
    if (cts->reversed)
	raw_put32lint (cts, n);
    else
	raw_put32bint (cts, n);
}
#if 0
static void put32bfloat (WContents *cts, float f)
{
    if (cts->reversed)
	raw_put32lfloat (cts, f);
    else
	raw_put32bfloat (cts, f);
}

static void put32bint_seek (WContents *cts, guint32 n, gulong seek)
{
    if (cts->reversed)
	raw_put32lint_seek (cts, n, seek);
    else
	raw_put32bint_seek (cts, n, seek);
}
#endif
static void put64bint (WContents *cts, guint64 n)
{
    if (cts->reversed)
	raw_put64lint (cts, n);
    else
	raw_put64bint (cts, n);
}



/* Write out the mhbd header. Size will be written later */
static void mk_mhbd (FExport *fexp, guint32 children)
{
  WContents *cts;

  g_return_if_fail (fexp);
  g_return_if_fail (fexp->itdb);
  g_return_if_fail (fexp->wcontents);

  cts = fexp->wcontents;

  put_header (cts, "mhbd");
  put32lint (cts, 188); /* header size */
  put32lint (cts, -1);  /* size of whole mhdb -- fill in later */
  put32lint (cts, 1);   /* ? */
  /* Version number: 0x01: iTunes 2
                     0x02: iTunes 3
		     0x09: iTunes 4.2
		     0x0a: iTunes 4.5
		     0x0b: iTunes 4.7
		     0x0c: iTunes 4.71/4.8 (required for shuffle)
                     0x0d: iTunes 4.9
                     0x0e: iTunes 5
		     0x0f: iTunes 6
		     0x10: iTunes 6.0.1(?)
		     0x11: iTunes 6.0.2
                     0x12 = iTunes 6.0.5.
		     0x13 = iTunes 7 
                     0x14 = iTunes 7.1
                     0x15 = iTunes 7.2
                     0x19 = iTunes 7.4
    Be aware that newer ipods won't work if the library version number is too 
    old
  */
  fexp->itdb->version = 0x19;
  put32lint (cts, fexp->itdb->version);
  put32lint (cts, children);
  put64lint (cts, fexp->itdb->id);
  /* 0x20 */
  put16lint (cts, 2);   /* always seems to be 2 */
  put16_n0  (cts, 7);  /* unknown */
  /* 0x30 */
  put16lint (cts, 1);   /* ? but iPod Classic/fat Nanos won't display any song
			 * if it's not 1 */
  put16_n0  (cts, 10);  /* unknown */
  /* 0x46 */
  put16lint (cts, 0);   /* langauge */
  put64lint (cts, 0);   /* library persistent ID */
  /* 0x50 */
  put32lint (cts, 0);   /* unknown: seen: 0x05 for nano 3G */
  put32lint (cts, 0);   /* unknown: seen: 0x4d for nano 3G */
  put32_n0 (cts, 5);    /* 20 bytes hash */
  put32lint (cts, 0);   /* timezone offset in seconds */
  put32_n0 (cts, 19);   /* dummy space */
}

/* Fill in the length of a standard header */
static void fix_header (WContents *cts, gulong header_seek)
{
  put32lint_seek (cts, cts->pos-header_seek, header_seek+8);
}


/* Write out the mhsd header. Size will be written later */
static void mk_mhsd (FExport *fexp, guint32 type)
{
  WContents *cts;

  g_return_if_fail (fexp);
  g_return_if_fail (fexp->itdb);
  g_return_if_fail (fexp->wcontents);

  cts = fexp->wcontents;

  put_header (cts, "mhsd");
  put32lint (cts, 96);   /* Headersize */
  put32lint (cts, -1);   /* size of whole mhsd -- fill in later */
  put32lint (cts, type); /* type: 1 = track, 2 = playlist */
  put32_n0 (cts, 20);      /* dummy space */
}


/* Write out the mhlt header. */
static void mk_mhlt (FExport *fexp, guint32 num)
{
  WContents *cts;

  g_return_if_fail (fexp);
  g_return_if_fail (fexp->itdb);
  g_return_if_fail (fexp->wcontents);

  cts = fexp->wcontents;

  put_header (cts, "mhlt");
  put32lint (cts, 92);       /* Headersize */
  put32lint (cts, num);      /* tracks in this itunesdb */
  put32_n0 (cts, 20);        /* dummy space */
}


/* Write out the mhit header. Size will be written later */
static void mk_mhit (WContents *cts, Itdb_Track *track)
{
  guint32 mac_time;
  g_return_if_fail (cts);
  g_return_if_fail (track);

  put_header (cts, "mhit");
  put32lint (cts, 0x184);/* header size */
  put32lint (cts, -1);   /* size of whole mhit -- fill in later */
  put32lint (cts, -1);   /* nr of mhods in this mhit -- later   */
  put32lint (cts, track->id); /* track index number */

  put32lint (cts, track->visible);
  put32lint (cts, track->filetype_marker);
  put8int (cts, track->type1);
  put8int (cts, track->type2);
  put8int   (cts, track->compilation);
  put8int   (cts, track->rating);
  mac_time = device_time_time_t_to_mac (track->itdb->device, track->time_modified);
  put32lint (cts, mac_time); /* timestamp               */
  put32lint (cts, track->size);    /* filesize                   */
  put32lint (cts, track->tracklen);/* length of track in ms      */
  put32lint (cts, track->track_nr);/* track number               */
  put32lint (cts, track->tracks);  /* number of tracks           */
  put32lint (cts, track->year);    /* the year                   */
  put32lint (cts, track->bitrate); /* bitrate                    */
  put32lint (cts, (((guint32)track->samplerate)<<16) |
	     ((guint32)track->samplerate_low));
  put32lint (cts, track->volume);  /* volume adjust              */
  put32lint (cts, track->starttime);
  put32lint (cts, track->stoptime);
  put32lint (cts, track->soundcheck);
  put32lint (cts, track->playcount);/* playcount                 */
  track->playcount2 = track->playcount;
  put32lint (cts, track->playcount2);
  mac_time = device_time_time_t_to_mac (track->itdb->device, track->time_played);
  put32lint (cts, mac_time); /* last time played       */
  put32lint (cts, track->cd_nr);   /* CD number                  */
  put32lint (cts, track->cds);     /* number of CDs              */
  put32lint (cts, track->drm_userid);
  mac_time = device_time_time_t_to_mac (track->itdb->device, track->time_added);
  put32lint (cts, mac_time); /* timestamp            */
  put32lint (cts, track->bookmark_time);
  put64lint (cts, track->dbid);
  if (track->checked)   put8int (cts, 1);
  else                  put8int (cts, 0);
  put8int (cts, track->app_rating);
  put16lint (cts, track->BPM);
  put16lint (cts, track->artwork_count);
  put16lint (cts, track->unk126);
  put32lint (cts, track->artwork_size);
  put32lint (cts, track->unk132);
  put32lfloat (cts, track->samplerate2);
  mac_time = device_time_time_t_to_mac (track->itdb->device, track->time_released);
  put32lint (cts, mac_time);
  put16lint (cts, track->unk144);
  put16lint (cts, track->unk146);
  put32lint (cts, track->unk148);
  put32lint (cts, track->unk152);
  /* since iTunesDB version 0x0c */
  put32lint (cts, track->skipcount);
  mac_time = device_time_time_t_to_mac (track->itdb->device, track->last_skipped);
  put32lint (cts, mac_time);
  put8int (cts, track->has_artwork);
  put8int (cts, track->skip_when_shuffling);
  put8int (cts, track->remember_playback_position);
  put8int (cts, track->flag4);
  put64lint (cts, track->dbid2);
  put8int (cts, track->lyrics_flag);
  put8int (cts, track->movie_flag);
  put8int (cts, track->mark_unplayed);
  put8int (cts, track->unk179);
  put32lint (cts, track->unk180);
  put32lint (cts, track->pregap);
  put64lint (cts, track->samplecount);
  put32lint (cts, track->unk196);
  put32lint (cts, track->postgap);
  put32lint (cts, track->unk204);
  put32lint (cts, track->mediatype);
  put32lint (cts, track->season_nr);
  put32lint (cts, track->episode_nr);
  put32lint (cts, track->unk220);
  put32lint (cts, track->unk224);
  put32lint (cts, track->unk228);
  put32lint (cts, track->unk232);
  put32lint (cts, track->unk236);
  put32lint (cts, track->unk240);
  put32lint (cts, track->unk244);
  put32lint (cts, track->gapless_data);
  put32lint (cts, track->unk252);
  put16lint (cts, track->gapless_track_flag);
  put16lint (cts, track->gapless_album_flag);
  put32_n0 (cts, 23);
  put32lint (cts, track->id); /* Needed on fat nanos/ipod classic to get art
			       * in the right sidepane
			       */
  put32_n0 (cts, 8); /* padding */
}


/* Fill in the missing items of the mhit header:
   total size and number of mhods */
static void fix_mhit (WContents *cts, gulong mhit_seek, guint32 mhod_num)
{
  g_return_if_fail (cts);

  /* size of whole mhit */
  put32lint_seek (cts, cts->pos-mhit_seek, mhit_seek+8);
  /* nr of mhods */
  put32lint_seek (cts, mhod_num, mhit_seek+12);
}

/* Returns:
   - track->sort_artist if track->sort_artist is not NULL

   - 'Artist, The' if track->sort_artist is NULL and track->artist of
     of type 'The Artist'.

   - NULL if track->sort_artist is NULL and track->artist is not of
     type 'The Artist'.

   You must g_free() the returned string */
static gchar *get_sort_artist (Itdb_Track *track)
{
    g_return_val_if_fail (track, NULL);

    if (track->sort_artist && *track->sort_artist)
    {
	return g_strdup (track->sort_artist);
    }

    if (!(track->artist && *track->artist))
    {
	return NULL;
    }

    /* check if artist is of type 'The Artist' */
    if (g_ascii_strncasecmp ("The ", track->artist, 4) == 0)
    {   /* return 'Artist, The', followed by five 0x01 chars
	   (analogous to iTunes) */
	return g_strdup_printf ("%s, The%c%c%c%c%c",
				track->artist+4,
				0x01, 0x01, 0x01, 0x01, 0x01);
    }

    return NULL;
}




static gint mhod52_sort_title (const struct mhod52track *a, const struct mhod52track *b)
{
    return strcmp (a->title, b->title);
}


static gint mhod52_sort_album (const struct mhod52track *a, const struct mhod52track *b)
{
    gint result;

    result = strcmp (a->album, b->album);
    if (result == 0)
	result = a->cd_nr - b->cd_nr;
    if (result == 0)
	result = a->track_nr - b->track_nr;
    if (result == 0)
	result = strcmp (a->title, b->title);
    return result;
}

static gint mhod52_sort_artist (struct mhod52track *a, struct mhod52track *b)
{
    gint result;

    result = strcmp (a->artist, b->artist);
    if (result == 0)
	result = strcmp (a->album, b->album);
    if (result == 0)
	result = a->cd_nr - b->cd_nr;
    if (result == 0)
	result = a->track_nr - b->track_nr;
    if (result == 0)
	result = strcmp (a->title, b->title);
    return result;
}

static gint mhod52_sort_genre (struct mhod52track *a, struct mhod52track *b)
{
    gint result;

    result = strcmp (a->genre, b->genre);
    if (result == 0)
	result = strcmp (a->artist, b->artist);
    if (result == 0)
	result = strcmp (a->album, b->album);
    if (result == 0)
	result = a->cd_nr - b->cd_nr;
    if (result == 0)
	result = a->track_nr - b->track_nr;
    if (result == 0)
	result = strcmp (a->title, b->title);
    return result;
}

static gint mhod52_sort_composer (struct mhod52track *a, struct mhod52track *b)
{
    gint result;

    result = strcmp (a->composer, b->composer);
    if (result == 0)
	result = strcmp (a->title, b->title);
    return result;
}


/* Create a new list containing all tracks but with collate keys
   instead of the actual strings (title, artist, album, genre,
   composer) */
static GList *mhod52_make_collate_keys (GList *tracks)
{
    gint numtracks = g_list_length (tracks);
    GList *gl, *coltracks = NULL;
    gint index=0;

    for (gl=tracks; gl; gl=gl->next)
    {
	gchar *str;
	struct mhod52track *ct;
	Itdb_Track *tr = gl->data;
	g_return_val_if_fail (tr, NULL);

	ct = g_new0 (struct mhod52track, 1);
	coltracks = g_list_prepend (coltracks, ct);

	/* album */
	if (tr->sort_album && *tr->sort_album)
	{
	    ct->album = g_utf8_collate_key (tr->sort_album, -1);
	}
	else if (tr->album)
	{
	    ct->album = g_utf8_collate_key (tr->album, -1);
	}
	else
	{
	    ct->album = g_strdup ("");
	}

	/* title */
	if (tr->sort_title && *tr->sort_title)
	{
	    ct->title = g_utf8_collate_key (tr->sort_title, -1);
	}
	else if (tr->title)
	{
	    ct->title = g_utf8_collate_key (tr->title, -1);
	}
	else
	{
	    ct->title = g_strdup ("");
	}

	/* artist */
	str = get_sort_artist (tr);
	if (str)
	{
	    ct->artist = g_utf8_collate_key (str, -1);
	    g_free (str);
	}
	else if (tr->artist)
	{
	    ct->artist = g_utf8_collate_key (tr->artist, -1);
	}
	else
	{
	    ct->artist = g_strdup ("");
	}

	/* genre */
	if (tr->genre)
	{
	    ct->genre = g_utf8_collate_key (tr->genre, -1);
	}
	else
	{
	    ct->genre = g_strdup ("");
	}

	/* composer */
	if (tr->sort_composer && *tr->sort_composer)
	{
	    ct->composer = g_utf8_collate_key (tr->sort_composer, -1);
	}
	else if (tr->composer)
	{
	    ct->composer = g_utf8_collate_key (tr->composer, -1);
	}
	else
	{
	    ct->composer = g_strdup ("");
	}

	ct->track_nr = tr->track_nr;
	ct->cd_nr = tr->cd_nr;
	ct->numtracks = numtracks;
	ct->index = index++;
    }
    return coltracks;
}


/* Free all memory used up by the collate keys */
static void mhod52_free_collate_keys (GList *coltracks)
{
    GList *gl;

    for (gl=coltracks; gl; gl=gl->next)
    {
	struct mhod52track *ct = gl->data;
	g_return_if_fail (ct);
	g_free (ct->album);
	g_free (ct->title);
	g_free (ct->artist);
	g_free (ct->genre);
	g_free (ct->composer);
	g_free (ct);
    }
    g_list_free (coltracks);
}


/* Write out one mhod header.
     type: see enum of MHMOD_IDs;
     data: utf8 string for text items
           position indicator for MHOD_ID_PLAYLIST
           Itdb_SPLPref for MHOD_ID_SPLPREF
	   Itdb_SPLRules for MHOD_ID_SPLRULES */
static void mk_mhod (FExport *fexp, MHODData *mhod)
{
  WContents *cts = fexp->wcontents;

  g_return_if_fail (cts);
  g_return_if_fail (mhod->valid);

  switch ((enum MHOD_ID)mhod->type)
  {
  case MHOD_ID_TITLE:
  case MHOD_ID_PATH:
  case MHOD_ID_ALBUM:
  case MHOD_ID_ARTIST:
  case MHOD_ID_GENRE:
  case MHOD_ID_FILETYPE:
  case MHOD_ID_COMMENT:
  case MHOD_ID_CATEGORY:
  case MHOD_ID_COMPOSER:
  case MHOD_ID_GROUPING:
  case MHOD_ID_DESCRIPTION:
  case MHOD_ID_SUBTITLE:
  case MHOD_ID_TVSHOW:
  case MHOD_ID_TVEPISODE:
  case MHOD_ID_TVNETWORK:
  case MHOD_ID_ALBUMARTIST:
  case MHOD_ID_KEYWORDS:
  case MHOD_ID_SORT_ARTIST:
  case MHOD_ID_SORT_TITLE:
  case MHOD_ID_SORT_ALBUM:
  case MHOD_ID_SORT_ALBUMARTIST:
  case MHOD_ID_SORT_COMPOSER:
  case MHOD_ID_SORT_TVSHOW:
      g_return_if_fail (mhod->data.string);
      /* normal iTunesDBs seem to take utf16 strings), endian-inversed
	 iTunesDBs seem to take utf8 strings */
      if (!cts->reversed)
      {
	  /* convert to utf16  */
	  glong len;
	  gunichar2 *entry_utf16 = g_utf8_to_utf16 (mhod->data.string, -1,
						    NULL, &len, NULL);
	  fixup_little_utf16 (entry_utf16);
	  put_header (cts, "mhod");   /* header                     */
	  put32lint (cts, 24);        /* size of header             */
	  put32lint (cts, sizeof (gunichar2)*len+40);  /* size of header + body      */
	  put32lint (cts, mhod->type);/* type of the mhod           */
	  put32_n0 (cts, 2);          /* unknown                    */
	  /* end of header, start of data */
	  put32lint (cts, 1);         /* string type UTF16          */
	  put32lint (cts, sizeof (gunichar2)*len);     /* size of string             */
	  put32_n0 (cts, 2);          /* unknown                    */
	  put_data (cts, (gchar *)entry_utf16, sizeof (gunichar2)*len);/* the string */
	  g_free (entry_utf16);
      }
      else
      {
	  guint32 len = strlen (mhod->data.string);
	  put_header (cts, "mhod");   /* header                     */
	  put32lint (cts, 24);        /* size of header             */
	  put32lint (cts, len+40);    /* size of header + body      */
	  put32lint (cts, mhod->type);/* type of the mhod           */
	  put32_n0 (cts, 2);          /* unknown                    */
	  /* end of header, start of data */
	  put32lint (cts, 2);         /* string type UTF 8          */
	  put32lint (cts, len);       /* size of string             */
	  put8int (cts, 1);           /* unknown                    */
	  put8int (cts, 0);           /* unknown                    */
	  put8int (cts, 0);           /* unknown                    */
	  put8int (cts, 0);           /* unknown                    */
	  put32lint (cts, 0);         /* unknown                    */
	  put_string (cts, mhod->data.string);/* the string         */
      }
      break;
  case MHOD_ID_PODCASTURL:
  case MHOD_ID_PODCASTRSS:
      g_return_if_fail (mhod->data.string);
      {
	  guint32 len = strlen (mhod->data.string);
	  put_header (cts, "mhod");   /* header                     */
	  put32lint (cts, 24);        /* size of header             */
	  put32lint (cts, 24+len);    /* size of header + data      */
	  put32lint (cts, mhod->type);/* type of the mhod           */
	  put32_n0 (cts, 2);          /* unknown                    */
	  put_string (cts, mhod->data.string);/* the string         */
      }
      break;
  case MHOD_ID_PLAYLIST:
      put_header (cts, "mhod");   /* header                     */
      put32lint (cts, 24);        /* size of header             */
      put32lint (cts, 44);        /* size of header + body      */
      put32lint (cts, mhod->type); /* type of the entry          */
      put32_n0 (cts, 2);          /* unknown                    */
      /* end of header, start of data */
      put32lint (cts, mhod->data.track_pos);/* position of track in playlist */
      put32_n0 (cts, 4);             /* unknown                    */
      break;
  case MHOD_ID_CHAPTERDATA:
      g_return_if_fail (mhod->data.chapterdata_track);
      {
	  Itdb_Track *track = mhod->data.chapterdata_track;
	  put_header (cts, "mhod");   /* header                     */
	  put32lint (cts, 24);        /* size of header             */
	  put32lint (cts, 24+track->chapterdata_raw_length); /*size */
	  put32lint (cts, mhod->type); /* type of the entry          */
	  put32_n0 (cts, 2);          /* unknown                    */
	  put_data (cts, track->chapterdata_raw,
		    track->chapterdata_raw_length);
      }
      break;
  case MHOD_ID_SPLPREF:
      g_return_if_fail (mhod->data.splpref);
      put_header (cts, "mhod");  /* header                 */
      put32lint (cts, 24);       /* size of header         */
      put32lint (cts, 96);       /* size of header + body  */
      put32lint (cts, mhod->type);/* type of the entry      */
      put32_n0 (cts, 2);         /* unknown                */
      /* end of header, start of data */
      put8int (cts, mhod->data.splpref->liveupdate);
      put8int (cts, mhod->data.splpref->checkrules? 1:0);
      put8int (cts, mhod->data.splpref->checklimits);
      put8int (cts, mhod->data.splpref->limittype);
      put8int (cts, mhod->data.splpref->limitsort & 0xff);
      put8int (cts, 0);          /* unknown                */
      put8int (cts, 0);          /* unknown                */
      put8int (cts, 0);          /* unknown                */
      put32lint (cts, mhod->data.splpref->limitvalue);
      put8int (cts, mhod->data.splpref->matchcheckedonly);
      /* for the following see note at definitions of limitsort
	 types in itunesdb.h */
      put8int (cts, (mhod->data.splpref->limitsort & 0x80000000) ? 1:0);
      put8int (cts, 0);          /* unknown                */
      put8int (cts, 0);          /* unknown                */
      put32_n0 (cts, 14);        /* unknown                */
      break;
  case MHOD_ID_SPLRULES:
      g_return_if_fail (mhod->data.splrules);
      {
	  gulong header_seek = cts->pos; /* needed to fix length */
	  GList *gl;
	  gint numrules = g_list_length (mhod->data.splrules->rules);

	  put_header (cts, "mhod");  /* header                   */
	  put32lint (cts, 24);       /* size of header           */
	  put32lint (cts, -1);       /* total length, fix later  */
	  put32lint (cts, mhod->type);/* type of the entry        */
	  put32_n0 (cts, 2);         /* unknown                  */
	  /* end of header, start of data */
	  /* For some reason this is the only part of the iTunesDB
	     that uses big endian */
	  put_header (cts, "SLst");  /* header                   */
	  put32bint (cts, mhod->data.splrules->unk004); /* unknown*/
	  put32bint (cts, numrules);
	  put32bint (cts, mhod->data.splrules->match_operator);
	  put32_n0 (cts, 30);            /* unknown              */
	  /* end of header, now follow the rules */
	  for (gl=mhod->data.splrules->rules; gl; gl=gl->next)
	  {
	      Itdb_SPLRule *splr = gl->data;
	      ItdbSPLFieldType ft;
	      glong len;
	      gunichar2 *entry_utf16;
	      g_return_if_fail (splr);
	      ft = itdb_splr_get_field_type (splr);
/*	      printf ("%p: field: %d ft: %d\n", splr, splr->field, ft);*/
	      itdb_splr_validate (splr);
	      put32bint (cts, splr->field);
	      put32bint (cts, splr->action);
	      put32_n0 (cts, 11);          /* unknown              */	      
	      switch (ft)
	      {
	      case ITDB_SPLFT_STRING:
		  /* write string-type rule */
		  len = 0;
		  entry_utf16 = NULL;
		  /* splr->string may be NULL */
		  if (splr->string)
		      entry_utf16 = g_utf8_to_utf16 (splr->string,
						     -1,NULL,&len,NULL);
		  fixup_big_utf16 (entry_utf16);
		  put32bint (cts, sizeof (gunichar2)*len); /* length of string     */
		  put_data (cts, (gchar *)entry_utf16, sizeof (gunichar2)*len);
		  g_free (entry_utf16);
		  break;
	      case ITDB_SPLFT_DATE:
	      case ITDB_SPLFT_INT:
	      case ITDB_SPLFT_BOOLEAN:
	      case ITDB_SPLFT_PLAYLIST:
	      case ITDB_SPLFT_UNKNOWN:
	      case ITDB_SPLFT_BINARY_AND: {
		  guint64 fromvalue;	       
		  guint64 tovalue;
		  
		  fromvalue = splr->fromvalue;
		  tovalue = splr->tovalue;

		  if (ft == ITDB_SPLFT_DATE) {
		      ItdbSPLActionType at;
		      at = itdb_splr_get_action_type (splr);
		      if ((at == ITDB_SPLAT_RANGE_DATE) ||
			  (at == ITDB_SPLAT_DATE))
		      {
			  Itdb_iTunesDB *itdb = fexp->itdb;
			  fromvalue = device_time_time_t_to_mac (itdb->device, fromvalue);
			  tovalue = device_time_time_t_to_mac (itdb->device, tovalue);
		      }
		  }

		  /* write non-string-type rule */
		  put32bint (cts, 0x44); /* length of data        */
		  /* data */
		  put64bint (cts, fromvalue);
		  put64bint (cts, splr->fromdate);
		  put64bint (cts, splr->fromunits);
		  put64bint (cts, tovalue);
		  put64bint (cts, splr->todate);
		  put64bint (cts, splr->tounits);
		  put32bint (cts, splr->unk052);
		  put32bint (cts, splr->unk056);
		  put32bint (cts, splr->unk060);
		  put32bint (cts, splr->unk064);
		  put32bint (cts, splr->unk068);
		  break;
	      }
	      }
	  }
	  /* insert length of mhod junk */
	  fix_header (cts, header_seek);
      }
      break;
  case MHOD_ID_LIBPLAYLISTINDEX:
      g_return_if_fail (mhod->data.mhod52coltracks);
      g_return_if_fail (mhod->data.mhod52coltracks->data);
      {
	  struct mhod52track *ct = mhod->data.mhod52coltracks->data;
	  gint numtracks = ct->numtracks;
	  GList *gl;
	  gpointer compfunc = NULL;

	  /* sort list */
	  switch (mhod->data2.mhod52sorttype)
	  {
	  case MHOD52_SORTTYPE_TITLE:
	      compfunc = mhod52_sort_title;
	      break;
	  case MHOD52_SORTTYPE_ALBUM:
	      compfunc = mhod52_sort_album;
	      break;
	  case MHOD52_SORTTYPE_ARTIST:
	      compfunc = mhod52_sort_artist;
	      break;
	  case MHOD52_SORTTYPE_GENRE:
	      compfunc = mhod52_sort_genre;
	      break;
	  case MHOD52_SORTTYPE_COMPOSER:
	      compfunc = mhod52_sort_composer;
	      break;
	  }
	  g_return_if_fail (compfunc);

	  /* sort the tracks */
	  mhod->data.mhod52coltracks = g_list_sort (mhod->data.mhod52coltracks,
						    compfunc);
	  /* Write the MHOD */
	  put_header (cts, "mhod");         /* header                     */
	  put32lint (cts, 24);              /* size of header             */
	  put32lint (cts, 4*numtracks+72);  /* size of header + body      */
	  put32lint (cts, mhod->type);      /* type of the mhod           */
	  put32_n0 (cts, 2);                /* unknown                    */
	  /* end of header, start of data */
	  put32lint (cts, mhod->data2.mhod52sorttype);   /* sort type     */
	  put32lint (cts, numtracks);       /* number of entries          */
	  put32_n0 (cts, 10);               /* unknown                    */
	  for (gl=mhod->data.mhod52coltracks; gl; gl=gl->next)
	  {
	      ct = gl->data;
	      g_return_if_fail (ct);
	      put32lint (cts, ct->index);
	  }
      }
      break;
  }
}


/* Write out the mhlp header. Size will be written later */
static void mk_mhlp (FExport *fexp)
{
  WContents *cts;

  g_return_if_fail (fexp);
  g_return_if_fail (fexp->wcontents);

  cts = fexp->wcontents;

  put_header (cts, "mhlp");        /* header                   */
  put32lint (cts, 92);             /* size of header           */
  /* playlists on iPod (including main!) */
  put32lint (cts, g_list_length (fexp->itdb->playlists));
  put32_n0 (cts, 20);               /* dummy space              */
}


/* Write out the long MHOD_ID_PLAYLIST mhod header.
   This seems to be an itunespref thing.. dunno know this
   but if we set everything to 0, itunes doesn't show any data
   even if you drag an mp3 to your ipod: nothing is shown, but itunes
   will copy the file!
   .. so we create a hardcoded-pref.. this will change in future
   Seems to be a Preferences mhod, every PL has such a thing
   FIXME !!! */
static void mk_long_mhod_id_playlist (FExport *fexp, Itdb_Playlist *pl)
{
  WContents *cts;

  g_return_if_fail (fexp);
  g_return_if_fail (fexp->wcontents);
  g_return_if_fail (pl);

  cts = fexp->wcontents;

  put_header (cts, "mhod");          /* header                   */
  put32lint (cts, 0x18);             /* size of header  ?        */
  put32lint (cts, 0x0288);           /* size of header + body    */
  put32lint (cts, MHOD_ID_PLAYLIST); /* type of the entry        */
  put32_n0 (cts, 6);
  put32lint (cts, 0x010084);         /* ? */
  put32lint (cts, 0x05);             /* ? */
  put32lint (cts, 0x09);             /* ? */
  put32lint (cts, 0x03);             /* ? */
  put32lint (cts, 0x120001);         /* ? */
  put32_n0 (cts, 3);
  put32lint (cts, 0xc80002);         /* ? */
  put32_n0 (cts, 3);
  put32lint (cts, 0x3c000d);         /* ? */
  put32_n0 (cts, 3);
  put32lint (cts, 0x7d0004);         /* ? */
  put32_n0 (cts, 3);
  put32lint (cts, 0x7d0003);         /* ? */
  put32_n0 (cts, 3);
  put32lint (cts, 0x640008);         /* ? */
  put32_n0 (cts, 3);
  put32lint (cts, 0x640017);         /* ? */
  put32lint (cts, 0x01);             /* bool? (visible? / colums?) */
  put32_n0 (cts, 2);
  put32lint (cts, 0x500014);         /* ? */
  put32lint (cts, 0x01);             /* bool? (visible?) */
  put32_n0 (cts, 2);
  put32lint (cts, 0x7d0015);         /* ? */
  put32lint (cts, 0x01);             /* bool? (visible?) */
  put32_n0 (cts, 114);
}



/* Header for new PL item */
/* @pos: position in playlist */
static void mk_mhip (FExport *fexp,
		     guint32 childcount,
		     guint32 podcastgroupflag,
		     guint32 podcastgroupid,
		     guint32 trackid,
		     guint32 timestamp,
		     guint32 podcastgroupref)
{
  WContents *cts;

  g_return_if_fail (fexp);
  g_return_if_fail (fexp->wcontents);

  cts = fexp->wcontents;

  put_header (cts, "mhip");
  put32lint (cts, 76);                              /*  4 */
  put32lint (cts, -1);  /* fill in later */         /*  8 */
  put32lint (cts, childcount);                      /* 12 */
  put32lint (cts, podcastgroupflag);                /* 16 */
  put32lint (cts, podcastgroupid);                  /* 20 */
  put32lint (cts, trackid);                         /* 24 */
  timestamp = device_time_time_t_to_mac (fexp->itdb->device, timestamp);
  put32lint (cts, timestamp);                       /* 28 */
  put32lint (cts, podcastgroupref);                 /* 32 */
  put32_n0 (cts, 10);                               /* 36 */
}


/* Write first mhsd hunk. Return FALSE in case of error and set
 * fexp->error */
static gboolean write_mhsd_tracks (FExport *fexp)
{
    GList *gl;
    gulong mhsd_seek;
    WContents *cts;

    g_return_val_if_fail (fexp, FALSE);
    g_return_val_if_fail (fexp->itdb, FALSE);
    g_return_val_if_fail (fexp->wcontents, FALSE);

    cts = fexp->wcontents;
    
    mhsd_seek = cts->pos;      /* get position of mhsd header  */
    mk_mhsd (fexp, 1);         /* write header: type 1: tracks */
    /* write header with nr. of tracks */
    mk_mhlt (fexp, g_list_length (fexp->itdb->tracks));
    for (gl=fexp->itdb->tracks; gl; gl=gl->next)  /* Write each track */
    {
	Itdb_Track *track = gl->data;
	guint32 mhod_num = 0;
	gulong mhit_seek = cts->pos;
	MHODData mhod;

	g_return_val_if_fail (track, FALSE);

	mhod.valid = TRUE;

	mk_mhit (cts, track);
	if (track->title && *track->title)
	{
	    mhod.type = MHOD_ID_TITLE;
	    mhod.data.string = track->title;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->ipod_path && *track->ipod_path)
	{
	    mhod.type = MHOD_ID_PATH;
	    mhod.data.string = track->ipod_path;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->album && *track->album)
	{
	    mhod.type = MHOD_ID_ALBUM;
	    mhod.data.string = track->album;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->artist && *track->artist)
	{
	    mhod.type = MHOD_ID_ARTIST;
	    mhod.data.string = track->artist;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->genre && *track->genre)
	{
	    mhod.type = MHOD_ID_GENRE;
	    mhod.data.string = track->genre;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->filetype && *track->filetype)
	{
	    mhod.type = MHOD_ID_FILETYPE;
	    mhod.data.string = track->filetype;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->comment && *track->comment)
	{
	    mhod.type = MHOD_ID_COMMENT;
	    mhod.data.string = track->comment;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->category && *track->category)
	{
	    mhod.type = MHOD_ID_CATEGORY;
	    mhod.data.string = track->category;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->composer && *track->composer)
	{
	    mhod.type = MHOD_ID_COMPOSER;
	    mhod.data.string = track->composer;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->grouping && *track->grouping)
	{
	    mhod.type = MHOD_ID_GROUPING;
	    mhod.data.string = track->grouping;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->description && *track->description)
	{
	    mhod.type = MHOD_ID_DESCRIPTION;
	    mhod.data.string = track->description;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->subtitle && *track->subtitle)
	{
	    mhod.type = MHOD_ID_SUBTITLE;
	    mhod.data.string = track->subtitle;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->tvshow && *track->tvshow)
	{
	    mhod.type = MHOD_ID_TVSHOW;
	    mhod.data.string = track->tvshow;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->tvepisode && *track->tvepisode)
	{
	    mhod.type = MHOD_ID_TVEPISODE;
	    mhod.data.string = track->tvepisode;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->tvnetwork && *track->tvnetwork)
	{
	    mhod.type = MHOD_ID_TVNETWORK;
	    mhod.data.string = track->tvnetwork;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->albumartist && *track->albumartist)
	{
	    mhod.type = MHOD_ID_ALBUMARTIST;
	    mhod.data.string = track->albumartist;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->keywords && *track->keywords)
	{
	    mhod.type = MHOD_ID_KEYWORDS;
	    mhod.data.string = track->keywords;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->podcasturl && *track->podcasturl)
	{
	    mhod.type = MHOD_ID_PODCASTURL;
	    mhod.data.string = track->podcasturl;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->podcastrss && *track->podcastrss)
	{
	    mhod.type = MHOD_ID_PODCASTRSS;
	    mhod.data.string = track->podcastrss;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->sort_artist && *track->sort_artist)
	{
	    mhod.type = MHOD_ID_SORT_ARTIST;
	    mhod.data.string = track->sort_artist;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->sort_title && *track->sort_title)
	{
	    mhod.type = MHOD_ID_SORT_TITLE;
	    mhod.data.string = track->sort_title;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->sort_album && *track->sort_album)
	{
	    mhod.type = MHOD_ID_SORT_ALBUM;
	    mhod.data.string = track->sort_album;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->sort_albumartist && *track->sort_albumartist)
	{
	    mhod.type = MHOD_ID_SORT_ALBUMARTIST;
	    mhod.data.string = track->sort_albumartist;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->sort_composer && *track->sort_composer)
	{
	    mhod.type = MHOD_ID_SORT_COMPOSER;
	    mhod.data.string = track->sort_composer;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->sort_tvshow && *track->sort_tvshow)
	{
	    mhod.type = MHOD_ID_SORT_TVSHOW;
	    mhod.data.string = track->sort_tvshow;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
	if (track->chapterdata_raw && track->chapterdata_raw_length)
	{
	    mhod.type = MHOD_ID_CHAPTERDATA;
	    mhod.data.chapterdata_track = track;
	    mk_mhod (fexp, &mhod);
	    ++mhod_num;
	}
        /* Fill in the missing items of the mhit header */
	fix_mhit (cts, mhit_seek, mhod_num);
    }
    fix_header (cts, mhsd_seek);
    return TRUE;
}


/* write out the mhip/mhod pairs for playlist @pl. @mhyp_seek points
   to the start of the corresponding mhyp, but is not used yet. */
static gboolean write_playlist_mhips (FExport *fexp,
				      Itdb_Playlist *pl,
				      glong mhyp_seek)
{
    GList *gl;
    WContents *cts;
    guint32 i=0;
    guint32 mhip_num;

    g_return_val_if_fail (fexp, FALSE);
    g_return_val_if_fail (fexp->itdb, FALSE);
    g_return_val_if_fail (fexp->wcontents, FALSE);
    g_return_val_if_fail (pl, FALSE);

    cts = fexp->wcontents;

    for (gl=pl->members; gl; gl=gl->next)
    {
	Itdb_Track *track = gl->data;
	glong mhip_seek = cts->pos;
	MHODData mhod;

	g_return_val_if_fail (track, FALSE);

	mk_mhip (fexp, 1, 0, 0, track->id, 0, 0);
	mhod.valid = TRUE;
	mhod.type = MHOD_ID_PLAYLIST;
	mhod.data.track_pos = i;
	mk_mhod (fexp, &mhod);
	/* note: with iTunes 4.9 the mhod is counted as a child to
	   mhip, so we have put the total length of the mhip and mhod
	   into the mhip header */
	fix_header (cts, mhip_seek);
	++i;
    }

    /* set number of mhips */
    mhip_num = g_list_length (pl->members);
    put32lint_seek (cts, mhip_num, mhyp_seek+16);

    return TRUE;
}


void free_memberlist (gpointer data);
void write_one_podcast_group (gpointer key, gpointer value, gpointer userdata);
void free_memberlist (gpointer data)
{
    GList **memberlist = data;
    if (memberlist)
    {
	g_list_free (*memberlist);
	g_free (memberlist);
    }
}
void write_one_podcast_group (gpointer key, gpointer value,
			      gpointer userdata)
{
    gchar *album = key;
    GList **memberlist = value;
    FExport *fexp = userdata;
    GList *gl;
    WContents *cts;
    glong mhip_seek;
    guint32 groupid;
    Itdb_iTunesDB *itdb;
    MHODData mhod;

    g_return_if_fail (album);
    g_return_if_fail (memberlist);
    g_return_if_fail (fexp);
    g_return_if_fail (fexp->itdb);
    g_return_if_fail (fexp->wcontents);

    cts = fexp->wcontents;
    itdb = fexp->itdb;
    mhip_seek = cts->pos;

    groupid = fexp->next_id++;
    mk_mhip (fexp, 1, 256, groupid, 0, 0, 0);

    mhod.valid = TRUE;
    mhod.type = MHOD_ID_TITLE;
    mhod.data.string = album;
    mk_mhod (fexp, &mhod);
    fix_header (cts, mhip_seek);

    /* write members */
    for (gl=*memberlist; gl; gl=gl->next)
    {
	Itdb_Track *track = gl->data;
	guint32 mhip_id;

	g_return_if_fail (track);

	mhip_seek = cts->pos;
	mhip_id = fexp->next_id++;
	mk_mhip (fexp, 1, 0, mhip_id, track->id, 0, groupid);
	mhod.type = MHOD_ID_PLAYLIST;
	mhod.data.track_pos = mhip_id;
	mk_mhod (fexp, &mhod);
	fix_header (cts, mhip_seek);
    }
}



/* write out the mhip/mhod pairs for the podcast playlist
   @pl. @mhyp_seek points to the start of the corresponding mhyp, but
   is not used yet. */
static gboolean write_podcast_mhips (FExport *fexp,
				     Itdb_Playlist *pl,
				     glong mhyp_seek)
{
    GList *gl;
    WContents *cts;
    guint32 mhip_num;
    GHashTable *album_hash;

    g_return_val_if_fail (fexp, FALSE);
    g_return_val_if_fail (fexp->itdb, FALSE);
    g_return_val_if_fail (fexp->wcontents, FALSE);
    g_return_val_if_fail (pl, FALSE);

    cts = fexp->wcontents;

    /* Create a list wit all available album names because we have to
       group the podcasts according to albums */

    album_hash = g_hash_table_new_full (g_str_hash, g_str_equal,
					NULL, free_memberlist);
    for (gl=pl->members; gl; gl=gl->next)
    {
	GList **memberlist;
	gchar *album;
	Itdb_Track *track = gl->data;
	g_return_val_if_fail (track, FALSE);

	if (track->album)
	    album = track->album;
	else
	    album = "";

	memberlist = g_hash_table_lookup (album_hash, album);

	if (!memberlist)
	{
	    memberlist = g_new0 (GList *, 1);
	    g_hash_table_insert (album_hash, album, memberlist);
	}
	*memberlist = g_list_append (*memberlist, track);
    }

    g_hash_table_foreach (album_hash, write_one_podcast_group, fexp);

    /* set number of mhips */
    mhip_num = g_list_length (pl->members)+g_hash_table_size (album_hash);
    put32lint_seek (cts, mhip_num, mhyp_seek+16);

    g_hash_table_destroy (album_hash);

    return TRUE;
}


/* corresponds to mk_mhyp */
/* mhsd_type: 2: write normal playlists
              3: write podcast playlist in special format */
/* Return FALSE in case of error and set fexp->error */
static gboolean write_playlist (FExport *fexp,
				Itdb_Playlist *pl, guint32 mhsd_type)
{
    gulong mhyp_seek;
    WContents *cts;
    gboolean result = TRUE;
    MHODData mhod;
    gint mhodnum;
    guint32 mac_time;

    g_return_val_if_fail (fexp, FALSE);
    g_return_val_if_fail (fexp->itdb, FALSE);
    g_return_val_if_fail (fexp->wcontents, FALSE);
    g_return_val_if_fail (pl, FALSE);

    cts = fexp->wcontents;
    mhyp_seek = cts->pos;

#if ITUNESDB_DEBUG
  fprintf(stderr, "Playlist: %s (%d tracks)\n", pl->name, g_list_length (pl->members));
#endif

    put_header (cts, "mhyp");      /* header                    */
    put32lint (cts, 108);          /* length		        */
    put32lint (cts, -1);           /* size -> later             */
    mhodnum = 2;
    if (pl->is_spl)
    {   /* 2 more SPL MHODs */
	mhodnum += 2;
    }
    else
    {
	if ((pl->type == ITDB_PL_TYPE_MPL) && pl->members)
	{   /* 5 more MHOD 52 lists */
	    mhodnum += 5;
	}
    }
    put32lint (cts, mhodnum);      /* nr of mhods               */
    /* number of tracks in plist */
    put32lint (cts, -1);           /* number of mhips -> later  */
    put8int (cts, pl->type);       /* 1 = main, 0 = visible     */
    put8int (cts, pl->flag1);      /* unknown                   */
    put8int (cts, pl->flag2);      /* unknown                   */
    put8int (cts, pl->flag3);      /* unknown                   */
    mac_time = device_time_time_t_to_mac (fexp->itdb->device, pl->timestamp);
    put32lint (cts, mac_time);     /* some timestamp            */
    put64lint (cts, pl->id);       /* 64 bit ID                 */
    put32lint (cts, 0);            /* unknown, always 0?        */
    put16lint (cts, 1);            /* string mhod count (1)     */
    put16lint (cts, pl->podcastflag);
    put32lint (cts, pl->sortorder);
    put32_n0 (cts, 15);            /* ?                         */

    mhod.valid = TRUE;
    mhod.type = MHOD_ID_TITLE;
    mhod.data.string = pl->name;
    mk_mhod (fexp, &mhod);
    mk_long_mhod_id_playlist (fexp, pl);

    if ((pl->type == ITDB_PL_TYPE_MPL) && pl->members)
    {   /* write out the MHOD 52 lists */
	/* We have to sort all tracks five times. To speed this up,
	   translate the utf8 keys into collate_keys and use the
	   faster strcmp() for comparison */
	mhod.valid = TRUE;
	mhod.type = MHOD_ID_LIBPLAYLISTINDEX;
	mhod.data.mhod52coltracks = mhod52_make_collate_keys (pl->members);
	mhod.data2.mhod52sorttype = MHOD52_SORTTYPE_TITLE;
	mk_mhod (fexp, &mhod);
	mhod.data2.mhod52sorttype = MHOD52_SORTTYPE_ARTIST;
	mk_mhod (fexp, &mhod);
	mhod.data2.mhod52sorttype = MHOD52_SORTTYPE_ALBUM;
	mk_mhod (fexp, &mhod);
	mhod.data2.mhod52sorttype = MHOD52_SORTTYPE_GENRE;
	mk_mhod (fexp, &mhod);
	mhod.data2.mhod52sorttype = MHOD52_SORTTYPE_COMPOSER;
	mk_mhod (fexp, &mhod);
	mhod52_free_collate_keys (mhod.data.mhod52coltracks);
    }
    else  if (pl->is_spl)
    {  /* write the smart rules */
	mhod.type = MHOD_ID_SPLPREF;
	mhod.data.splpref = &pl->splpref;
	mk_mhod (fexp, &mhod);

	mhod.type = MHOD_ID_SPLRULES;
	mhod.data.splrules = &pl->splrules;
	mk_mhod (fexp, &mhod);
    }

    if (itdb_playlist_is_podcasts(pl) && (mhsd_type == 3))
    {
	/* write special podcast playlist */
	result = write_podcast_mhips (fexp, pl, mhyp_seek);
    }
    else
    {   /* write standard playlist hard-coded tracks */
	result = write_playlist_mhips (fexp, pl, mhyp_seek);
    }
    fix_header (cts, mhyp_seek);
    return result;
}


/* Expects the master playlist to be the first in the list */
/* Return FALSE in case of error and set fexp->error */
static gboolean write_mhsd_playlists (FExport *fexp, guint32 mhsd_type)
{
    GList *gl;
    glong mhsd_seek;
    WContents *cts;

    g_return_val_if_fail (fexp, FALSE);
    g_return_val_if_fail (fexp->itdb, FALSE);
    g_return_val_if_fail (fexp->wcontents, FALSE);
    g_return_val_if_fail ((mhsd_type == 2) || (mhsd_type == 3), FALSE);

    cts = fexp->wcontents;
    mhsd_seek = cts->pos;      /* get position of mhsd header */
    mk_mhsd (fexp, mhsd_type); /* write header */
    /* write header with nr. of playlists */
    mk_mhlp (fexp);
    for (gl=fexp->itdb->playlists; gl; gl=gl->next)
    {
	Itdb_Playlist *pl = gl->data;
	g_return_val_if_fail (pl, FALSE);

	write_playlist (fexp, pl, mhsd_type);
	if (fexp->error)  return FALSE;
    }
    fix_header (cts, mhsd_seek);
    return TRUE;
}


/* create a WContents structure */
static WContents *wcontents_new (const gchar *filename)
{
    WContents *cts;

    g_return_val_if_fail (filename, NULL);

    cts = g_new0 (WContents, 1);
    cts->filename = g_strdup (filename);

    return cts;
}


/* write the contents of WContents. Return FALSE on error and set
 * cts->error accordingly. */
static gboolean wcontents_write (WContents *cts)
{
    int fd;

    g_return_val_if_fail (cts, FALSE);
    g_return_val_if_fail (cts->filename, FALSE);

    fd = creat (cts->filename, S_IRWXU|S_IRWXG|S_IRWXO);

    if (fd == -1)
    {
	cts->error = g_error_new (G_FILE_ERROR,
				  g_file_error_from_errno (errno),
				  _("Opening of '%s' for writing failed (%s)."),
				  cts->filename, g_strerror (errno));
	return FALSE;
    }
    if (cts->contents && cts->pos)
    {
	ssize_t written = write (fd, cts->contents, cts->pos);
	if (written == -1)
	{
	    cts->error = g_error_new (G_FILE_ERROR,
				      g_file_error_from_errno (errno),
				      _("Writing to '%s' failed (%s)."),
				      cts->filename, g_strerror (errno));
	    close (fd);
	    return FALSE;
	}
    }
    fd = close (fd);
    if (fd == -1)
    {
	cts->error = g_error_new (G_FILE_ERROR,
				  g_file_error_from_errno (errno),
				  _("Writing to '%s' failed (%s)."),
				  cts->filename, g_strerror (errno));
	return FALSE;
    }
    return TRUE;
}


/* Free memory associated with WContents @cts */
static void wcontents_free (WContents *cts)
{
    if (cts)
    {
	g_free (cts->filename);
	g_free (cts->contents);
	/* must not g_error_free (cts->error) because the error was
	   propagated -> might free the error twice */
	g_free (cts);
    }
}


/* - reassign the iPod IDs
   - make sure the itdb->tracks are in the same order as the mpl
*/
static void prepare_itdb_for_write (FExport *fexp)
{
    GList *gl;
    Itdb_iTunesDB *itdb;
    Itdb_Playlist *mpl;

    g_return_if_fail (fexp);
    itdb = fexp->itdb;
    g_return_if_fail (itdb);

    /* Arrange itdb->tracks in the same order as mpl->members
       (otherwise On-The-Go Playlists will not show the correct
       content. Unfortunately we cannot just copy mpl->members to
       itdb->tracks because podcasts do not show up in the MPL. */

    mpl = itdb_playlist_mpl (itdb);
    g_return_if_fail (mpl);

    for (gl=g_list_last(mpl->members); gl; gl=gl->prev)
    {
	GList *link;
	Itdb_Track *track = gl->data;
	g_return_if_fail (track);
	link = g_list_find (itdb->tracks, track);
	g_return_if_fail (link);

	/* move this track to the beginning of itdb_tracks */
	itdb->tracks = g_list_delete_link (itdb->tracks, link);
	itdb->tracks = g_list_prepend (itdb->tracks, track);
    }

    fexp->next_id = FIRST_IPOD_ID;

    /* assign unique IDs and create sort keys */
    for (gl=itdb->tracks; gl; gl=gl->next)
    {
	Itdb_Track *track = gl->data;
	g_return_if_fail (track);
	track->id = fexp->next_id++;
    }
}


static gboolean write_db_checksum (FExport *fexp, GError **error)
{
    guint64 fwid;
    guchar backup18[8];
    guchar backup32[20];
    unsigned char *itdb_data;
    unsigned char *checksum;
    gsize len;

    fwid = itdb_device_get_firewire_id (fexp->itdb->device);
    if (fwid == 0) {
	g_set_error (error, 0, -1, "Couldn't find the iPod firewire ID");
	return FALSE;
    }

    if (fexp->wcontents->pos < 0x6c) {
	g_set_error (error, 0, -1, "iTunesDB file too small to write checksum");
	return FALSE;
    }
    itdb_data = (unsigned char *)fexp->wcontents->contents;

    memcpy (backup18, itdb_data+0x18, sizeof (backup18));
    memcpy (backup32, itdb_data+0x32, sizeof (backup32));

    /* Those fields must be zero'ed out for the sha1 calculation */
    memset(itdb_data+0x18, 0, 8);
    memset(itdb_data+0x32, 0, 20);
    memset(itdb_data+0x58, 0, 20);

    checksum = itdb_compute_hash (fwid, itdb_data, fexp->wcontents->pos, &len);
    if (checksum == NULL) {
	g_set_error (error, 0, -1, "Failed to compute checksum");
	return FALSE;
    }
    memcpy (itdb_data+0x58, checksum, len);    
    g_free (checksum);

    memcpy (itdb_data+0x18, backup18, sizeof (backup18));
    memcpy (itdb_data+0x32, backup32, sizeof (backup32));

    return TRUE;
}

/**
 * itdb_write_file:
 * @itdb: the #Itdb_iTunesDB to save
 * @filename: filename to save @itdb to
 * @error: return location for a #GError or NULL
 *
 * Write the content of @itdb to @filename. If @filename is NULL, it attempts
 * to write to itdb-&gt;filename.
 *
 * Return value: TRUE if all went well, FALSE otherwise
 **/
gboolean itdb_write_file (Itdb_iTunesDB *itdb, const gchar *filename,
			  GError **error)
{
    FExport *fexp;
    gulong mhbd_seek = 0;
    WContents *cts;
    gboolean result = TRUE;;

    g_return_val_if_fail (itdb, FALSE);
    g_return_val_if_fail (itdb->device, FALSE);
    g_return_val_if_fail (filename || itdb->filename, FALSE);

    if (!filename) filename = itdb->filename;

    /* set endianess flag */
    if (!itdb->device->byte_order)
	itdb_device_autodetect_endianess (itdb->device);

    fexp = g_new0 (FExport, 1);
    fexp->itdb = itdb;
    fexp->wcontents = wcontents_new (filename);
    cts = fexp->wcontents;

    cts->reversed = (itdb->device->byte_order == G_BIG_ENDIAN);

    prepare_itdb_for_write (fexp);

#if HAVE_GDKPIXBUF
    /* only write ArtworkDB if we deal with an iPod
       FIXME: figure out a way to store the artwork data when storing
       to local directories. At the moment it's the application's task
       to handle this. */
    /* The ArtworkDB must be written after the call to
     * prepare_itdb_for_write since it needs Itdb_Track::id to be set
     * to its final value to write properly on nano video/ipod classics
     */
    if (itdb_device_supports_artwork (itdb->device)) {
		ipod_write_artwork_db (itdb);
    }
#endif

    mk_mhbd (fexp, 3);   /* three mhsds */
    /* write tracklist */
    if (write_mhsd_tracks (fexp))
    {   /* write special podcast version mhsd */
	if (write_mhsd_playlists (fexp, 3))
	{   /* write standard playlist mhsd */
	    if (write_mhsd_playlists (fexp, 2))
	    {
		fix_header (cts, mhbd_seek);

		/* Set checksum (ipods require it starting from iPod Classic 
		 * and fat Nanos)
		 */
		write_db_checksum (fexp, &fexp->error);
	    }
	}
    }
    if (!fexp->error)
    {
	if (!wcontents_write (cts))
	    g_propagate_error (&fexp->error, cts->error);
    }
    if (fexp->error)
    {
	g_propagate_error (error, fexp->error);
	result = FALSE;
    }
    wcontents_free (cts);
    g_free (fexp);
    if (result == TRUE)
    {
	gchar *fn = g_strdup (filename);
	g_free (itdb->filename);
	itdb->filename = fn;
    }

    /* make sure all buffers are flushed as some people tend to
       disconnect as soon as gtkpod returns */
    sync ();

    return result;
}

/**
 * itdb_write:
 * @itdb: the #Itdb_iTunesDB to write to disk
 * @error: return location for a #GError or NULL
 *
 * Write out an iTunesDB. It reassigns unique IDs to all tracks. 
 * An existing "Play Counts" file is renamed to "Play Counts.bak" if
 * the export was successful.
 * An existing "OTGPlaylistInfo" file is removed if the export was
 * successful.
 *
 * Return value: TRUE on success, FALSE on error, in which case @error is
 * set accordingly.
 **/
gboolean itdb_write (Itdb_iTunesDB *itdb, GError **error)
{
    gchar *itunes_filename, *itunes_path;
    gboolean result = FALSE;

    g_return_val_if_fail (itdb, FALSE);
    g_return_val_if_fail (itdb_get_mountpoint (itdb), FALSE);

    /* First, let's try to write the .ithmb files containing the artwork data
     * since this operation modifies the 'artwork_count' and 'artwork_size' 
     * field in the Itdb_Track contained in the database.
     * Errors happening during that operation are considered non fatal since
     * they shouldn't corrupt the main database.
     */


    itunes_path = itdb_get_itunes_dir (itdb_get_mountpoint (itdb));

    if(!itunes_path)
    {
	error_no_itunes_dir (itdb_get_mountpoint (itdb), error);
	return FALSE;
    }

    itunes_filename = g_build_filename (itunes_path, "iTunesDB", NULL);

    result = itdb_write_file (itdb, itunes_filename, error);

    g_free (itunes_filename);
    g_free (itunes_path);

    if (result != FALSE)
    {
	/* Write SysInfo file if it has changed */
	if (itdb->device->sysinfo_changed)
	{
	    itdb_device_write_sysinfo (itdb->device, error);
	}
	result = itdb_rename_files (itdb_get_mountpoint (itdb), error);
    }

    /* make sure all buffers are flushed as some people tend to
       disconnect as soon as gtkpod returns */
    sync ();

    return result;
}


/* from here on we have the functions for writing the iTunesDB          */
/* -------------------------------------------------------------------- */
/* up to here we had the functions for writing the iTunesSD             */

/*
|  Copyright (C) 2005 Jorg Schuler <jcsjcs at users.sourceforge.net>
|  Part of the gtkpod project.
|
|  Based on itunessd.c written by Steve Wahl for gtkpod-0.88:
|
|  Copyright 2005 Steve Wahl <steve at pro-ns dot net>
|
|  This file contains routines to create the iTunesSD file, as
|  used by the ipod shuffle.
|
|  Like itunesdb.c, it is derived from the perl script "mktunes.pl"
|  (part of the gnupod-tools collection) written by Adrian
|  Ulrich <pab at blinkenlights.ch>.
|
|  Small(?) portions derived from itunesdb.c, so Jorg Schuler probably
|  has some copyright ownership in this file as well.
|
|  The code contained in this file is free software; you can redistribute
|  it and/or modify it under the terms of the GNU Lesser General Public
|  License as published by the Free Software Foundation; either version
|  2.1 of the License, or (at your option) any later version.
|
|  This file is distributed in the hope that it will be useful,
|  but WITHOUT ANY WARRANTY; without even the implied warranty of
|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
|  Lesser General Public License for more details.
|
|  You should have received a copy of the GNU Lesser General Public
|  License along with this code; if not, write to the Free Software
|  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
|
|  iTunes and iPod are trademarks of Apple
|
|  This product is not supported/written/published by Apple!
|
*/

/* notes:

  All software currently seems to write iTunesDB as well as iTunesSD
  on the iPod shuffle.  I assume that reading from the iTunesSD file
  is not necessary.  The iTunesStats file is different, but I leave
  that for another day.

  The iTunesSD file format is as follows (taken from WikiPodLinux, feb
  '05):

    Offset Field         Bytes   Value
     (hex)               (dec)

  iTunesSD header (occurs once, at beginning of file):

    00      num_songs     3       number of song entries in the file

    03      unknown       3       always(?) 0x010600
    06      header size   3       size of the header (0x12, 18 bytes)
    09      unknown       3       possibly zero padding

  iTunesSD song entry format (occurs once for each song)

   000      size of entry 3       always(?) 0x00022e (558 bytes)
   003      unk1          3       unknown, always(?) 0x5aa501
   006      starttime     3       Start Time, in 256 ms increments
                                  e.g. 60s = 0xea (234 dec)
   009      unk2          3       unknown (always 0?)
   00C      unk3          3       unknown, some relationship to starttime
   00F      stoptime      3       Stop Time, also in 256 ms increments.
                                  Zero means play to end of file.
   012      unk4          3       Unknown.
   015      unk5          3       Unknown, but associated with stoptime?
   018      volume        3       Volume - ranges from 0x00 (-100%) to 0x64
                                  (0%) to 0xc8 (100%)
   01B      file_type     3       0x01 = MP3, 0x02 = AAC, 0x04=WAV
   01E      unk6          3       unknown (always 0x200?)
   021      filename      522     filename of the song, padded at the end
                                  with 0's.  Note: forward slashes are used
                                  here, not colons like in the iTunesDB --
                                  for example,
                                  "/iPod_Control/Music/F00/Song.mp3"
   22B      shuffleflag   1       If this value is 0x00, the song will be
                                  skipped while the player is in shuffle
                                  mode.  Any other value will allow it to be
                                  played in both normal and shuffle modes.
                                  iTunes 4.7.1 sets this to 0 for audio books.
   22C      bookmarkflag  1       If this flag is 0x00, the song will not be
                                  bookmarkable (i.e. its playback position
                                  won't be saved when switching to a different
                                  song). Any other value wil make it
                                  Bookmarkable.  Unlike hard drive based iPods,
                                  all songs can be marked as bookmarkable,
                                  not just .m4b and .aa
   22D      unknownflag   1       unknown, always? 0x00.

All integers in the iTunesSD file are in BIG endian form...

*/


/**
 * itdb_shuffle_write:
 * @itdb: the #Itdb_iTunesDB to write to disk
 * @error: return location for a #GError or NULL
 *
 * Write out an iTunesSD for the Shuffle.
 * First reassigns unique IDs to all tracks.
 * An existing "Play Counts" file is renamed to "Play Counts.bak" if
 * the export was successful.
 * An existing "OTGPlaylistInfo" file is removed if the export was
 * successful.
 * @itdb->mountpoint must point to the mount point of the iPod,
 * e.g. "/mnt/ipod" and be in local encoding.
 *
 * Return value: TRUE on success, FALSE on error, in which case @error is
 * set accordingly.
 **/
gboolean itdb_shuffle_write (Itdb_iTunesDB *itdb, GError **error)
{
    gchar *itunes_filename, *itunes_path;
    gboolean result = FALSE;

    g_return_val_if_fail (itdb, FALSE);
    g_return_val_if_fail (itdb_get_mountpoint (itdb), FALSE);

    itunes_path = itdb_get_itunes_dir (itdb_get_mountpoint (itdb));
    
    if(!itunes_path)
    {
	gchar *str = g_build_filename (itdb_get_mountpoint (itdb),
				       "iPod_Control", "iTunes", NULL);
	g_set_error (error,
		     ITDB_FILE_ERROR,
		     ITDB_FILE_ERROR_NOTFOUND,
		     _("Path not found: '%s' (or similar)."),
		     str);
	g_free (str);
	return FALSE;
    }

    itunes_filename = g_build_filename (itunes_path, "iTunesSD", NULL);

    result = itdb_shuffle_write_file (itdb, itunes_filename, error);

    g_free(itunes_filename);
    g_free(itunes_path);

    if (result == TRUE)
	result = itdb_rename_files (itdb_get_mountpoint (itdb), error);

    /* make sure all buffers are flushed as some people tend to
       disconnect as soon as gtkpod returns */
    sync ();

    return result;
}


/**
 * itdb_shuffle_write_file:
 * @itdb: the #Itdb_iTunesDB to write to disk
 * @filename: file to write to, cannot be NULL
 * @error: return location for a #GError or NULL
 *
 * Do the actual writing to the iTunesSD 
 *
 * Return value: TRUE on success, FALSE on error, in which case @error is
 * set accordingly.
 **/
gboolean itdb_shuffle_write_file (Itdb_iTunesDB *itdb,
				  const gchar *filename, GError **error)
{
    auto gboolean haystack (gchar *filetype, gchar **desclist);
    gboolean haystack (gchar *filetype, gchar **desclist)
    {
	gchar **dlp;
	if (!filetype || !desclist) return FALSE;
	for (dlp=desclist; *dlp; ++dlp)
	{
	    if (strstr (filetype, *dlp)) return TRUE;
	}
	return FALSE;
    }

    FExport *fexp;
    GList *gl;
    WContents *cts;
    gboolean result = TRUE;;

    g_return_val_if_fail (itdb, FALSE);
    g_return_val_if_fail (filename, FALSE);

    fexp = g_new0 (FExport, 1);
    fexp->itdb = itdb;
    fexp->wcontents = wcontents_new (filename);
    cts = fexp->wcontents;

    prepare_itdb_for_write (fexp);

    put24bint (cts, itdb_tracks_number (itdb));
    put24bint (cts, 0x010600);
    put24bint (cts, 0x12);	/* size of header */
    put24bint (cts, 0x0);	/* padding? */
    put24bint (cts, 0x0);
    put24bint (cts, 0x0);

    for (gl=itdb->tracks; gl; gl=gl->next)
    {
	Itdb_Track *tr = gl->data;
	gchar *path;
	gunichar2 *path_utf16;
	glong pathlen;
	gchar *mp3_desc[] = {"MPEG", "MP3", "mpeg", "mp3", NULL};
	gchar *mp4_desc[] = {"AAC", "MP4", "aac", "mp4", NULL};
	gchar *wav_desc[] = {"WAV", "wav", NULL};

	g_return_val_if_fail (tr, FALSE);

	put24bint (cts, 0x00022e);
	put24bint (cts, 0x5aa501);
	/* starttime is in 256 ms incr. for shuffle */
	put24bint (cts, tr->starttime / 256);
	put24bint (cts, 0);
	put24bint (cts, 0);
	put24bint (cts, tr->stoptime / 256);
	put24bint (cts, 0);
	put24bint (cts, 0);
	/* track->volume ranges from -255 to +255 */
	/* we want 0 - 200 */
	put24bint (cts, ((tr->volume + 255) * 201) / 511);

	/* The next one should be 0x01 for MP3,
	** 0x02 for AAC, and 0x04 for WAV, but I can't find
	** a suitable indicator within the track structure? */
	/* JCS: let's do heuristic on tr->filetype which would contain
	   "MPEG audio file", "AAC audio file", "Protected AAC audio
	   file", "AAC audio book file", "WAV audio file" (or similar
	   if not written by gtkpod) */

	if (haystack (tr->filetype, mp3_desc))
	    put24bint (cts, 0x01);
	else if (haystack (tr->filetype, mp4_desc))
	    put24bint (cts, 0x02);
	else if (haystack (tr->filetype, wav_desc))
	    put24bint (cts, 0x04);
	else
	    put24bint (cts, 0x01);  /* default to mp3 */

	put24bint (cts, 0x200);
		
	/* shuffle uses forward slash separator, not colon */
	path = g_strdup (tr->ipod_path);
	itdb_filename_ipod2fs (path);
	path_utf16 = g_utf8_to_utf16 (path, -1, NULL, &pathlen, NULL);
	if (pathlen > 261) pathlen = 261;
	fixup_little_utf16 (path_utf16);
	put_data (cts, (gchar *)path_utf16, sizeof (gunichar2)*pathlen);
	/* pad to 522 bytes */
	put16_n0 (cts, 261-pathlen);
	g_free(path);
	g_free(path_utf16);

	/* XXX FIXME: should depend on something, not hardcoded */
	put8int (cts, 0x1); /* song used in shuffle mode */
	put8int (cts, 0);   /* song will not be bookmarkable */
	put8int (cts, 0);
    }
    if (!fexp->error)
    {
	if (!wcontents_write (cts))
	    g_propagate_error (&fexp->error, cts->error);
    }
    if (fexp->error)
    {
	g_propagate_error (error, fexp->error);
	result = FALSE;
    }
    wcontents_free (cts);
    g_free (fexp);

    /* make sure all buffers are flushed as some people tend to
       disconnect as soon as gtkpod returns */
    sync ();

    return result;
}











/*------------------------------------------------------------------*\
 *                                                                  *
 *                  Other file/filename stuff                       *
 *                                                                  *
\*------------------------------------------------------------------*/


/**
 * itdb_rename_files:
 * @mp: mount point of the iPod
 * @error: return location for a #GError or NULL
 *
 * Renames/removes some files on the iPod (Playcounts, OTG
 * semaphore). May have to be called if you write the iTunesDB not
 * directly to the iPod but to some other location and then manually
 * copy the file from there to the iPod. 
 *
 * Return value: FALSE on error and sets @error accordingly
 **/
gboolean itdb_rename_files (const gchar *mp, GError **error)
{
    const gchar *db_plc_o[] = {"Play Counts", NULL};
    const gchar *db_otg[] = {"OTGPlaylistInfo", NULL};
    const gchar *db_shu[] = {"iTunesShuffle", NULL};
    gchar *itunesdir;
    gchar *plcname_o;
    gchar *plcname_n;
    gchar *otgname;
    gchar *shuname;
    gboolean result = TRUE;

    g_return_val_if_fail (mp, FALSE);

    itunesdir = itdb_get_itunes_dir (mp);

    if(!itunesdir)
    {
	error_no_itunes_dir (mp, error);
	return FALSE;
    }

    plcname_o = itdb_resolve_path (itunesdir, db_plc_o);
    plcname_n = g_build_filename (itunesdir, 
					 "Play Counts.bak", NULL);
    otgname = itdb_resolve_path (itunesdir, db_otg);
    shuname = itdb_resolve_path (itunesdir, db_shu);

    /* rename "Play Counts" to "Play Counts.bak" */
    if (plcname_o)
    {
	if (rename (plcname_o, plcname_n) == -1)
	{   /* an error occured */
	    g_set_error (error,
			 G_FILE_ERROR,
			 g_file_error_from_errno (errno),
			 _("Error renaming '%s' to '%s' (%s)."),
			 plcname_o, plcname_n, g_strerror (errno));
	    result = FALSE;
	}
    }

    /* remove "OTGPlaylistInfo" (the iPod will remove the remaining
     * files */
    if (otgname)
    {
	if (unlink (otgname) == -1)
	{
	    if (error && !*error)
	    {   /* don't overwrite previous error */
	    g_set_error (error,
			 G_FILE_ERROR,
			 g_file_error_from_errno (errno),
			 _("Error removing '%s' (%s)."),
			 otgname, g_strerror (errno));
	    }
	    result = FALSE;
	}
    }

    /* remove some Shuffle files */
    if (shuname)
    {
	if (unlink (shuname) == -1)
	{
	    if (error && !*error)
	    {   /* don't overwrite previous error */
	    g_set_error (error,
			 G_FILE_ERROR,
			 g_file_error_from_errno (errno),
			 _("Error removing '%s' (%s)."),
			 shuname, g_strerror (errno));
	    }
	    result = FALSE;
	}
    }

    g_free (plcname_o);
    g_free (plcname_n);
    g_free (otgname);
    g_free (shuname);
    g_free (itunesdir);

    return result;
}


/**
 * itdb_filename_fs2ipod:
 * @filename: a filename 'PC-style' (eg /iPod_Control/Music/f00/test.mp3)
 *
 * Convert string from casual PC file name to iPod iTunesDB format using ':' 
 * instead of G_DIR_SEPARATOR_S (ie slashes on Unix-like systems). @ipod_file
 * is modified in place.
 **/
void itdb_filename_fs2ipod (gchar *ipod_file)
{
    g_strdelimit (ipod_file, G_DIR_SEPARATOR_S, ':');
}

/**
 * itdb_filename_ipod2fs:
 * @ipod_file: a filename 'PC-style' (eg /iPod_Control/Music/f00/test.mp3)
 *
 * Convert string from from iPod iTunesDB format to casual PC file name
 * using G_DIR_SEPARATOR (ie slashes on Unix-like systems) instead of ':'.
 * @ipod_file is modified in place.
 **/
void itdb_filename_ipod2fs (gchar *ipod_file)
{
    g_strdelimit (ipod_file, ":", G_DIR_SEPARATOR);
}



/**
 * itdb_set_mountpoint:
 * @itdb: an #Itdb_iTunesDB
 * @mp: new mount point
 *
 * Sets the mountpoint of @db. Always use this function to set the mountpoint
 * of an #Itdb_iTunesDB as it will reset the number of available 
 * /iPod_Control/Music/F.. dirs. It doesn't attempt to parse an iPod database
 * that may be present on the iPod at @mp
 **/
void itdb_set_mountpoint (Itdb_iTunesDB *itdb, const gchar *mp)
{
    g_return_if_fail (itdb);
    g_return_if_fail (itdb->device);

    itdb_device_set_mountpoint (itdb->device, mp);
    itdb->device->musicdirs = 0;
}

/**
 * itdb_get_mountpoint:
 * @itdb: an #Itdb_iTunesDB
 *
 * Retrieve a reference to the mountpoint of @itdb
 *
 * Return value: the @itdb mountpoint, this string shouldn't be freed nor 
 * modified
 **/
const gchar *itdb_get_mountpoint (Itdb_iTunesDB *itdb)
{
    g_return_val_if_fail (itdb, NULL);
    g_return_val_if_fail (itdb->device, NULL);
    return itdb->device->mountpoint;
}

/* Retrieve a reference to the mountpoint */
const gchar *itdb_photodb_get_mountpoint (Itdb_PhotoDB *photodb)
{
    g_return_val_if_fail (photodb, NULL);
    g_return_val_if_fail (photodb->device, NULL);
    return photodb->device->mountpoint;
}

/**
 * itdb_musicdirs_number:
 * @itdb: an #Itdb_iTunesDB
 *
 * Determine the number of F.. directories in iPod_Control/Music.
 *
 * If itdb->musicdirs is already set, simply return the previously
 * determined number. Otherwise count the directories first and set
 * itdb->musicdirs. 
 *
 * Return value: max number of directories in iPod_Control/Music
 **/
gint itdb_musicdirs_number (Itdb_iTunesDB *itdb)
{
    g_return_val_if_fail (itdb, 0);
    g_return_val_if_fail (itdb->device, 0);

    return itdb_device_musicdirs_number (itdb->device);
}

/**
 * itdb_cp_get_dest_filename:
 * @track: track to transfer or NULL
 * @mountpoint: mountpoint of your iPod or NULL
 * @filename: the source file
 * @error: return location for a #GError or NULL
 *
 * Creates a valid filename on the iPod where to copy @filename.
 *
 * You must either provide @track or @mountpoint. Providing @track is
 * not thread-safe (accesses track->itdb->device and may even write to
 * track->itdb->device). Providing @mountpoint is thread-safe but
 * slightly slower because the number of music directories is counted
 * each time the function is called.
 *
 * You can use #itdb_cp() to copy the track to the iPod or implement
 * your own copy function. After the file was copied you have to call
 * #itdb_cp_finalize() to obtain relevant update information for
 * #Itdb_Track.
 *
 * Return value: a valid filename on the iPod to where @filename can
 * be copied or NULL in case of an error. In that case @error is set
 * accordingly. You must free the filename when it is no longer
 * needed.
 **/
gchar *itdb_cp_get_dest_filename (Itdb_Track *track,
                                  const gchar *mountpoint,
				  const gchar *filename,
				  GError **error)
{
    gchar *ipod_fullfile = NULL;

    /* either supply mountpoint or track */
    g_return_val_if_fail (mountpoint || track, NULL);
    /* if mountpoint is not set, track->itdb is required */
    g_return_val_if_fail (mountpoint || track->itdb, NULL);
    g_return_val_if_fail (filename, NULL);

    if (!mountpoint)
    {
	mountpoint = itdb_get_mountpoint (track->itdb);
    }

    if (!mountpoint)
    {
	g_set_error (error,
		     ITDB_FILE_ERROR,
		     ITDB_FILE_ERROR_NOTFOUND,
		     _("Mountpoint not set."));
	return NULL;
    }

    /* If track->ipod_path exists, we use that one instead. */
    if (track)
    {
	ipod_fullfile = itdb_filename_on_ipod (track);
    }

    if (!ipod_fullfile)
    {
	gint dir_num, musicdirs_number;
	gchar *dest_components[] = {NULL, NULL, NULL};
	gchar *parent_dir_filename, *music_dir;
	gchar *original_suffix;
	gchar dir_num_str[6];
	gint32 oops = 0;
	gint32 rand = g_random_int_range (0, 899999); /* 0 to 900000 */

	music_dir = itdb_get_music_dir (mountpoint);
	if (!music_dir)
	{
	    error_no_music_dir (mountpoint, error);
	    return NULL;
	}

	if (track)
	{
	    musicdirs_number = itdb_musicdirs_number (track->itdb);
	}
	else
	{
	    musicdirs_number = itdb_musicdirs_number_by_mountpoint (mountpoint);
	}
	if (musicdirs_number <= 0)
	{
	    g_set_error (error,
			 ITDB_FILE_ERROR,
			 ITDB_FILE_ERROR_NOTFOUND,
			 _("No 'F..' directories found in '%s'."),
			 music_dir);
	    g_free (music_dir);
	    return NULL;
	}

	dir_num = g_random_int_range (0, musicdirs_number);

	g_snprintf (dir_num_str, 6, "F%02d", dir_num);
	dest_components[0] = dir_num_str;
  
	parent_dir_filename =
	    itdb_resolve_path (music_dir, (const gchar **)dest_components);
	if(parent_dir_filename == NULL)
	{
	    /* Can't find the F%02d directory */
	    gchar *str = g_build_filename (music_dir,
					   dest_components[0], NULL);
	    g_set_error (error,
			 ITDB_FILE_ERROR,
			 ITDB_FILE_ERROR_NOTFOUND,
			 _("Path not found: '%s'."),
			 str);
	    g_free (str);
	    g_free (music_dir);
	    return NULL;
	}

	/* we need the original suffix of pcfile to construct a correct ipod
	   filename */
	original_suffix = strrchr (filename, '.');
	/* If there is no ".mp3", ".m4a" etc, set original_suffix to empty
	   string. Note: the iPod will most certainly ignore this file... */
	if (!original_suffix) original_suffix = "";

	/* use lower-case version of extension as some iPods seem to
	   choke on upper-case extension. */
	original_suffix = g_ascii_strdown (original_suffix, -1);

	do
	{   /* we need to loop until we find an unused filename */
	    dest_components[1] = 
		g_strdup_printf("gtkpod%06d%s",
				rand + oops, original_suffix);
	    ipod_fullfile = itdb_resolve_path (
		parent_dir_filename,
		(const gchar **)&dest_components[1]);
	    if(ipod_fullfile)
	    {   /* already exists -- try next */
		g_free(ipod_fullfile);
		ipod_fullfile = NULL;
	    }
	    else
	    {   /* found unused file -- build filename */
		ipod_fullfile = g_build_filename (parent_dir_filename,
						  dest_components[1], NULL);
	    }
	    g_free (dest_components[1]);
	    ++oops;
	} while (!ipod_fullfile);
	g_free(parent_dir_filename);
	g_free (music_dir);
	g_free (original_suffix);
    }

    return ipod_fullfile;
}


/**
 * itdb_cp_finalize:
 * @track: track to update or NULL
 * @mountpoint: mountpoint of your iPod or NULL
 * @dest_filename: the name of the file on the iPod copied to
 * @error: return location for a #GError or NULL
 *
 * Updates information in @track necessary for the iPod. You must
 * either supply @track or @mountpoint. If @track == NULL, a new track
 * structure is created that must be freed with #itdb_track_free()
 * when it is no longer needed.
 *
 * The following fields are updated:
 *
 * - ipod_path
 * - filetype_marker
 * - transferred
 * - size
 *
 * Return value: on success a pointer to the #Itdb_Track item passed
 * or a new #Itdb_Track item if @track was NULL. In the latter case
 * you must free the memory using #itdb_track_free() when the item is
 * no longer used. If an error occurs NULL is returned and @error is
 * set accordingly. Errors occur when @dest_filename cannot be
 * accessed or the mountpoint is not set.
 **/
Itdb_Track *itdb_cp_finalize (Itdb_Track *track,
			      const gchar *mountpoint,
			      const gchar *dest_filename,
			      GError **error)
{
    const gchar *suffix;
    Itdb_Track *use_track;
    gint i, mplen;
    struct stat statbuf;

    /* either supply mountpoint or track */
    g_return_val_if_fail (mountpoint || track, NULL);
    /* if mountpoint is not set, track->itdb is required */
    g_return_val_if_fail (mountpoint || track->itdb, NULL);
    g_return_val_if_fail (dest_filename, NULL);

    if (!mountpoint)
    {
	mountpoint = itdb_get_mountpoint (track->itdb);
    }

    if (!mountpoint)
    {
	g_set_error (error,
		     ITDB_FILE_ERROR,
		     ITDB_FILE_ERROR_NOTFOUND,
		     _("Mountpoint not set."));
	return NULL;
    }

    if (stat (dest_filename, &statbuf) == -1)
    {
	g_set_error (error,
		     G_FILE_ERROR,
		     g_file_error_from_errno (errno),
		     _("'%s' could not be accessed (%s)."),
		     dest_filename, g_strerror (errno));
	return NULL;
    }

    if (strlen (mountpoint) >= strlen (dest_filename))
    {
	g_set_error (error,
		     ITDB_FILE_ERROR,
		     ITDB_FILE_ERROR_CORRUPT,
		     _("Destination file '%s' does not appear to be on the iPod mounted at '%s'."),
		     dest_filename, mountpoint);
	return NULL;
    }

    if (!track)
    {
	use_track = itdb_track_new ();
    }
    else
    {
	use_track = track;
    }

    use_track->transferred = TRUE;
    use_track->size = statbuf.st_size;

    /* we need the original suffix of pcfile to construct a correct ipod
       filename */
    suffix = strrchr (dest_filename, '.');
    /* If there is no ".mp3", ".m4a" etc, set original_suffix to empty
       string. Note: the iPod will most certainly ignore this file... */
    if (!suffix) suffix = ".";

    /* set filetype from the suffix, e.g. '.mp3' -> 'MP3 ' */
    use_track->filetype_marker = 0;
    for (i=1; i<=4; ++i)   /* start with i=1 to skip the '.' */
    {
	use_track->filetype_marker = use_track->filetype_marker << 8;
	if (strlen (suffix) > i)
	    use_track->filetype_marker |= g_ascii_toupper (suffix[i]);
	else
	    use_track->filetype_marker |= ' ';
    }

    /* now extract filepath for use_track->ipod_path from ipod_fullfile */
    /* ipod_path must begin with a '/' */
    g_free (use_track->ipod_path);
    mplen = strlen (mountpoint); /* length of mountpoint in bytes */
    if (dest_filename[mplen] == G_DIR_SEPARATOR)
    {
	use_track->ipod_path = g_strdup (&dest_filename[mplen]);
    }
    else
    {
	use_track->ipod_path = g_strdup_printf ("%c%s", G_DIR_SEPARATOR,
						&dest_filename[mplen]);
    }
    /* convert to iPod type */
    itdb_filename_fs2ipod (use_track->ipod_path);

    return use_track;
}


/**
 * itdb_cp_track_to_ipod:
 * @track: the #Itdb_Track to copy (containing @filename metadata)
 * @filename: the source file
 * @error: return location for a #GError or NULL
 * 
 * Copy one track to the iPod. The PC filename is @filename
 * and is taken literally.
 *
 * The mountpoint of the iPod (in local encoding) must have been set
 * with itdb_set_mountpoint() (done automatically when reading an
 * iTunesDB).
 *
 * If @track-&gt;transferred is set to TRUE, nothing is done. Upon
 * successful transfer @track-&gt;transferred is set to TRUE.
 *
 * For storage, the directories "f00 ... fnn" will be used randomly.
 *
 * The filename is constructed as "gtkpod"&lt;random number&gt; and copied
 * to @track-&gt;ipod_path. If this file already exists, &lt;random number&gt;
 * is adjusted until an unused filename is found.
 *
 * If @track-&gt;ipod_path is already set, this one will be used
 * instead. If a file with this name already exists, it will be
 * overwritten.
 *
 * @track-&gt;filetype_marker is set according to the filename extension
 *
 * Return value: TRUE on success, FALSE on error, in which case @error is
 * set accordingly.
 **/
gboolean itdb_cp_track_to_ipod (Itdb_Track *track,
				const gchar *filename, GError **error)
{
    gchar *dest_filename;
    gboolean result = FALSE;

    g_return_val_if_fail (track, FALSE);
    g_return_val_if_fail (track->itdb, FALSE);
    g_return_val_if_fail (itdb_get_mountpoint (track->itdb), FALSE);
    g_return_val_if_fail (filename, FALSE);

    if(track->transferred)  return TRUE; /* nothing to do */ 

    dest_filename = itdb_cp_get_dest_filename (track, NULL, filename, error);

    if (dest_filename)
    {
	if (itdb_cp (filename, dest_filename, error))
	{
	    if (itdb_cp_finalize (track, NULL, dest_filename, error))
	    {
		result = TRUE;
	    }
	}
	g_free (dest_filename);
    }

    return result;
}



/**
 * itdb_filename_on_ipod:
 * @track: an #Itdb_Track
 *
 * Return the full iPod filename as stored in @track.
 *
 * NOTE: NULL is returned when the file does not exist.
 *
 * NOTE: this code works around a problem on some systems (see
 * itdb_resolve_path() ) and might return a filename with different
 * case than the original filename. Don't copy it back to @track
 * unless you must 
 *
 * Return value: full filename to @track on the iPod or NULL if no
 * filename is set in @track. Must be freed with g_free() after use.
 **/
gchar *itdb_filename_on_ipod (Itdb_Track *track)
{
    gchar *result = NULL;
    gchar *buf;
    const gchar *mp;