File: file.c

package info (click to toggle)
gtkpod 0.99.14-3
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 7,716 kB
  • ctags: 3,266
  • sloc: ansic: 43,120; sh: 4,837; xml: 1,316; lex: 637; perl: 264; makefile: 236; awk: 73; python: 35
file content (2745 lines) | stat: -rw-r--r-- 77,768 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
/*
|  Copyright (C) 2002-2005 Jorg Schuler <jcsjcs at users sourceforge net>
|  Part of the gtkpod project.
| 
|  URL: http://www.gtkpod.org/
|  URL: http://gtkpod.sourceforge.net/
|
|  This program is free software; you can redistribute it and/or modify
|  it under the terms of the GNU General Public License as published by
|  the Free Software Foundation; either version 2 of the License, or
|  (at your option) any later version.
|
|  This program 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 General Public License for more details.
|
|  You should have received a copy of the GNU General Public License
|  along with this program; 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: file.c 2185 2008-12-31 22:30:36Z jcsjcs $
*/

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

#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <glib.h>
#include <glib/gstdio.h>


#include "charset.h"
#include "clientserver.h"
#include "confirmation.h"
#include "info.h"
#include "file.h"
#include "file_convert.h"
#include "itdb.h"
#include "sha1.h"
#include "misc.h"
#include "misc_track.h"
#include "mp3file.h"
#include "mp4file.h"
#include "prefs.h"
#include "wavfile.h"
#include "oggfile.h"
#include "flacfile.h"

/* The uppercase version of these extensions is tried as well. */
static const gchar *imageext[] =
{".jpg", ".jpeg", ".png", ".pbm", ".pgm", ".ppm", ".tif", ".tiff",
 ".gif", NULL};


/*------------------------------------------------------------------*\
 *                                                                  *
 *      Temporary Video stuff -- move to appropriate files when     *
 *      properly supported.                                         *
 *                                                                  *
\*------------------------------------------------------------------*/

Track *video_get_file_info (gchar *filename)
{
    Track *track;
    track = gp_track_new ();
    switch (determine_file_type (filename))
    {
    case FILE_TYPE_M4V:
	track->filetype = g_strdup ("M4V video file");
	break;
    case FILE_TYPE_MP4:
	track->filetype = g_strdup ("MP4 video file");
	break;
    case FILE_TYPE_MOV:
	track->filetype = g_strdup ("MOV video file");
	break;
    case FILE_TYPE_MPG:
	track->filetype = g_strdup ("MPG video file");
	break;
    case FILE_TYPE_UNKNOWN:
    case FILE_TYPE_MP3:
    case FILE_TYPE_M4A:
    case FILE_TYPE_M4P:
    case FILE_TYPE_M4B:
    case FILE_TYPE_WAV:
    case FILE_TYPE_M3U:
    case FILE_TYPE_PLS:
    case FILE_TYPE_IMAGE:
    case FILE_TYPE_DIRECTORY:
    case FILE_TYPE_OGG:
    case FILE_TYPE_FLAC:
	g_free (track);
	g_return_val_if_reached (NULL);
    }
    return track;
}


/* Determine the type of a file. 
 *
 * Currently this is done by checking the suffix of the filename. An improved
 * version should probably only fall back to that method if everything else
 * fails.
 * -jlt
 */

FileType determine_file_type (const gchar *path)
{
    gchar *path_utf8, *suf;
    FileType type = FILE_TYPE_UNKNOWN;
	
    g_return_val_if_fail (path, type);

    if (g_file_test (path, G_FILE_TEST_IS_DIR))
	return FILE_TYPE_DIRECTORY;

    path_utf8 = charset_to_utf8 (path);
    suf = strrchr (path_utf8, '.');
    if (suf)
    {
	if (g_strcasecmp (suf, ".mp3") == 0) type = FILE_TYPE_MP3;
	else if (g_strcasecmp (suf, ".m4a") == 0) type = FILE_TYPE_M4A;
	else if (g_strcasecmp (suf, ".m4p") == 0) type = FILE_TYPE_M4P;
	else if (g_strcasecmp (suf, ".m4b") == 0) type = FILE_TYPE_M4B;
	else if (g_strcasecmp (suf, ".wav") == 0) type = FILE_TYPE_WAV;

	else if (g_strcasecmp (suf, ".m4v") == 0) type = FILE_TYPE_M4V;
	else if (g_strcasecmp (suf, ".mp4") == 0) type = FILE_TYPE_MP4;
	else if (g_strcasecmp (suf, ".mov") == 0) type = FILE_TYPE_MOV;
	else if (g_strcasecmp (suf, ".mpg") == 0) type = FILE_TYPE_MPG;
	else if (g_strcasecmp (suf, ".mpeg") == 0) type = FILE_TYPE_MPG;

	else if (g_strcasecmp (suf, ".m3u") == 0) type = FILE_TYPE_M3U;
	else if (g_strcasecmp (suf, ".pls") == 0) type = FILE_TYPE_PLS;
        else if (g_strcasecmp (suf, ".ogg") == 0) type = FILE_TYPE_OGG;
        else if (g_strcasecmp (suf, ".flac") == 0) type = FILE_TYPE_FLAC;

	else
	{
	    const gchar **extp=imageext;
	    while (*extp)
	    {
		if (g_strcasecmp (suf, *extp) == 0)
		{
		    type = FILE_TYPE_IMAGE;
		    break;
		}
		++extp;
	    }
	}
    }

    g_free(path_utf8);
    return type;
}


/** check a filename against the "excludes file mask" from the preferences
 *  and return TRUE if it should be excluded based on the mask
 */
static gboolean excludefile (gchar *filename)
{
    gboolean matched = FALSE;
    gchar **masks, *prefs_masks;

    prefs_masks = prefs_get_string ("exclude_file_mask");
    
    if (prefs_masks == NULL) 
        return FALSE;
    
    masks = g_strsplit (prefs_masks, ";", -1);

    if (masks != NULL)
    {
	gint i;
        for(i=0; !matched && masks[i]; i++)
	{
	    matched = g_pattern_match_simple (g_strstrip(masks[i]), filename);
	}
        g_strfreev (masks);
    }
    
    g_free(prefs_masks);
    
    return matched;
}


/*------------------------------------------------------------------*\
 *                                                                  *
 *      Add Playlists                                               *
 *                                                                  *
\*------------------------------------------------------------------*/


/* Add all files specified in playlist @plfile. Will create a new
 * playlist with the name "basename (plfile)", even if one of the same
 * name already exists (if @plitem is != NULL, all tracks will be added
 * to @plitem and no new playlist will be created).
 * It will then add all tracks listed in @plfile. If set in the prefs,
 * duplicates will be detected (and the track already present in the
 * database will be added to the playlist instead). */
/* @addtrackfunc: if != NULL this will be called instead of
   "add_track_to_playlist () -- used for dropping tracks at a specific
   position in the track view */
/* Return value: playlist to which the files were added to or NULL on
 * error */
Playlist *
add_playlist_by_filename (iTunesDB *itdb, gchar *plfile,
			  Playlist *plitem, gint plitem_pos,
			  AddTrackFunc addtrackfunc, gpointer data)
{
    gchar *bufp, *plfile_utf8;
    gchar *dirname = NULL, *plname = NULL;
    gchar buf[PATH_MAX];
    FileType type = FILE_TYPE_UNKNOWN; /* type of playlist file */
    gint line, tracks;
    FILE *fp;
    gboolean error;

    g_return_val_if_fail (plfile, FALSE);
    g_return_val_if_fail (itdb, FALSE);

    if (g_file_test (plfile, G_FILE_TEST_IS_DIR))
    {
	gtkpod_warning (_("'%s' is a directory, not a playlist file.\n\n"),
			plfile);
	return FALSE;  /* definitely not! */
    }

    plfile_utf8 = charset_to_utf8 (plfile);

    plname = g_path_get_basename (plfile_utf8);
    g_free (plfile_utf8);

    bufp = g_strrstr (plname, "."); /* find last occurence of '.' */
    if (bufp)
    {
	*bufp = 0;          /* truncate playlist name */
	type = determine_file_type(plfile);
	switch (type)
	{
	case FILE_TYPE_MP3:
	case FILE_TYPE_M4A:
	case FILE_TYPE_M4P:
	case FILE_TYPE_M4B:
	case FILE_TYPE_WAV:
	case FILE_TYPE_M4V:
	case FILE_TYPE_MP4:
	case FILE_TYPE_MOV:
	case FILE_TYPE_MPG:
        case FILE_TYPE_OGG:
        case FILE_TYPE_FLAC:
	case FILE_TYPE_IMAGE:
	case FILE_TYPE_DIRECTORY:
	    gtkpod_warning (_("'%s' is a not a known playlist file.\n\n"),
			      plfile);
	    g_free(plname);
	    return FALSE;
	case FILE_TYPE_M3U:
	case FILE_TYPE_PLS:
	    break;
	case FILE_TYPE_UNKNOWN:
	    /* assume MISC (M3U like) style */
	    type = -2;
	    break;
	}
    }

    /* attempt to open playlist file */
    if (!(fp = fopen (plfile, "r")))
    {
	gtkpod_warning (_("Could not open '%s' for reading.\n"), plfile);
	g_free (plname);
	return FALSE;  /* definitely not! */
    }
    /* create playlist (if none is specified) */
    if (!plitem)  plitem = gp_playlist_add_new (itdb, plname,
						FALSE, plitem_pos);
    C_FREE (plname);
    g_return_val_if_fail (plitem, NULL);

    /* need dirname if playlist file contains relative paths */
    dirname = g_path_get_dirname (plfile);

    /* for now assume that all playlist files will be line-based
       all of these are line based -- add different code for different
       playlist files */
    line = -1; /* nr of line being read */
    tracks = 0; /* nr of tracks added */
    error = FALSE;
    while (!error && fgets (buf, PATH_MAX, fp))
    {
	gchar *bufp = buf;
	gchar *filename = NULL;
	gint len = strlen (bufp); /* remove newline */

	++line;
	if (len == 0) continue;   /* skip empty lines */
	if (bufp[len-1] == 0x0a)  bufp[len-1] = 0;
	if (type == -2)
	{
	    /* skip whitespace */
	    while (isspace (*bufp)) ++bufp;
	    /* assume comments start with ';' or '#' */
	    if ((*bufp == ';') || (*bufp == '#')) break;
	    /* assume the rest of the line is a filename */
	    filename = concat_dir_if_relative (dirname, bufp);
	    break;
	}
	else switch (type)
	{
	case FILE_TYPE_M3U:
	    /* comments start with '#' */
	    if (*bufp == '#') break;
	    /* assume the rest of the line is a filename */
	    filename = concat_dir_if_relative (dirname, bufp);
	    break;
	case FILE_TYPE_PLS:
	    /* I don't know anything about pls playlist files and just
	       looked at one example produced by xmms -- please
	       correct the code if you know more */
	    if (line == 0)
	    { /* check for "[playlist]" */
		if (strncasecmp (bufp, "[playlist]", 10) != 0)
		    error = TRUE;
	    }
	    else if (strncasecmp (bufp, "File", 4) == 0)
	    { /* looks like a file entry */
		bufp = strchr (bufp, '=');
		if (bufp)
		{
		    ++bufp;
		    filename = concat_dir_if_relative (dirname, bufp);
		}
	    }
	    break;
	case FILE_TYPE_UNKNOWN:
	case FILE_TYPE_DIRECTORY:
	case FILE_TYPE_MP3:
	case FILE_TYPE_M4A:
	case FILE_TYPE_M4P:
	case FILE_TYPE_M4B:
	case FILE_TYPE_WAV:
	case FILE_TYPE_M4V:
	case FILE_TYPE_MP4:
	case FILE_TYPE_MOV:
	case FILE_TYPE_MPG:
	case FILE_TYPE_OGG:
        case FILE_TYPE_FLAC:
	case FILE_TYPE_IMAGE:
	    break;
	}
	if (filename)
	{
	    /* do not allow to add directories! */
	    if (g_file_test (filename, G_FILE_TEST_IS_DIR))
	    {
		gtkpod_warning (_("Skipping '%s' because it is a directory.\n"), filename);
	    }
	    /* do not allow to add playlist file recursively */
	    else if (strcmp (plfile, filename) == 0)
	    {
		gtkpod_warning (_("Skipping '%s' to avoid adding playlist file recursively\n"), filename);
	    }
	    else if (add_track_by_filename (itdb, filename, plitem,
					    prefs_get_int("add_recursively"),
					    addtrackfunc, data))
	    {
		++tracks;
	    }
	    g_free (filename);
	}
    }
    fclose (fp);
    C_FREE (dirname);

    /* I don't think it's too interesting to pop up the list of
       duplicates -- but we should reset the list. */
    gp_duplicate_remove (NULL, (void *)-1);

    if (!error) return plitem;
    return NULL;
}



/*------------------------------------------------------------------*\
 *                                                                  *
 *      Add Dir                                                     *
 *                                                                  *
\*------------------------------------------------------------------*/

/* Add all files in directory and subdirectories.
   If @name is a regular file, just add that.
   If @plitem != NULL, add tracks also to Playlist @plitem
   @descend: TRUE: add recursively
             FALSE: don't enter subdirectories */
/* Not nice: the return value has not much meaning. TRUE: all files
 * were added successfully. FALSE: some files could not be
   added (e.g: duplicates)  */
/* @addtrackfunc: if != NULL this will be called instead of
   "add_track_to_playlist () -- used for dropping tracks at a specific
   position in the track view */
gboolean add_directory_by_name (iTunesDB *itdb, gchar *name,
				Playlist *plitem, gboolean descend,
				AddTrackFunc addtrackfunc, gpointer data)
{
  gboolean result = TRUE;

  g_return_val_if_fail (itdb, FALSE);
  g_return_val_if_fail (name, FALSE);

  if (g_file_test (name, G_FILE_TEST_IS_DIR))
  {
      GDir *dir = g_dir_open (name, 0, NULL);
      block_widgets ();
      if (dir != NULL) {
	  G_CONST_RETURN gchar *next;
	  do {
	      next = g_dir_read_name (dir);
	      if (next != NULL)
	      {
		  gchar *nextfull = g_build_filename (name, next, NULL);
		  if (descend ||
		      !g_file_test (nextfull, G_FILE_TEST_IS_DIR))
		      result &= add_directory_by_name (
			  itdb, nextfull, plitem,
			  descend, addtrackfunc, data);
		  g_free (nextfull);
	      }
	  } while (next != NULL);
	  g_dir_close (dir);
      }
      release_widgets ();
  }
  else
  {
      result = add_track_by_filename (itdb, name, plitem,
				      descend, addtrackfunc, data);
  }
  return result;
}



/*------------------------------------------------------------------*\
 *                                                                  *
 *      Fill in track struct with data from file                     *
 *                                                                  *
\*------------------------------------------------------------------*/

/* parse the file with name @filename (UTF8) and fill extract the tags
 * to @trackas specified in @template. @track can be NULL if you just
 * want to verify the template */
static gboolean parse_filename_with_template (Track *track,
					      gchar *filename,
					      const gchar *template)
{
    GList *tokens=NULL, *gl;
    gchar *tpl, *fn;
    gchar *sps, *sp, *str;
    gboolean parse_error = FALSE;

    if (!template || !filename) return FALSE;

#ifdef DEBUG
    printf ("fn: '%s', tpl: '%s'\n", filename, template);
#endif

    /* If the template starts with a '%.' (except for '%%') we add a
       '/' in front so that the field has a boundary */
    if ((template[0] == '%') && (template[1] != '%'))
	 tpl = g_strdup_printf ("%c%s", G_DIR_SEPARATOR, template);
    else tpl = g_strdup (template);

    fn = g_strdup (filename);

    /* We split the template into tokens. Each token starting with a
       '%' and two chars long specifies a field ('%.'), otherwise it's
       normal text (used to separate two fields).
       "/%a - %t.mp3" would become ".mp3"  "%t"  " - "  "%a"  "/" */
    sps = tpl;
    while ((sp = strchr (sps, '%')))
    {
	if (sps != sp)
	    tokens = g_list_prepend (tokens, g_strndup (sps, sp-sps));
	if (sp[1] != '%')
	{
	    tokens = g_list_prepend (tokens, g_strndup (sp, 2));
	}
	else
	{
	    tokens = g_list_prepend (tokens, g_strdup ("%"));
	}
	if (!sp[1]) break;
	sps = sp+2;
    }
    /* add what's left */
    if (sps[0] != 0)
	tokens = g_list_prepend (tokens, g_strdup (sps));

    /* If the "last" token does not contain a '.' (like in ".mp3"),
       remove the filename extension ("somefile.mp3" -> "somefile")
       because no extension was given in the template */
    str = g_list_nth_data (tokens, 0);
    if (str && (strchr (str, '.') == NULL))
    {
	gchar *str = strrchr (fn, '.');
	if (str) str[0] = 0;
    }

#ifdef DEBUG
    puts (tpl);
    for (gl=tokens; gl; gl=gl->next)
	puts (gl->data);
    puts (fn);
#endif

    /* use the tokens to parse the filename */
    gl = tokens;
    while (gl)
    {
	gchar *token = gl->data;
	/* remember: all tokens starting with '%' and two chars long
	   specify a field */
	if ((token[0] == '%') && (strlen (token) == 2))
	{   /* handle tag item */
	    GList *gln = gl->next;
	    if (gln)
	    {
		gchar *itm;
		gchar *next_token = gln->data;
		/* find next token so we can determine where the
		   current field ends */
		gchar *fnp = g_strrstr (fn, next_token);

		if (!fnp)
		{
		    parse_error = TRUE;
		    break;
		}

		/* truncate the filename (for the next token) */
		fnp[0] = 0;
		/* adjust fnp to point to the start of the field */
		fnp = fnp + strlen (next_token);
#ifdef DEBUG
		printf ("%s: '%s'\n", token, fnp);
#endif
		itm = g_strstrip (g_strdup (fnp));
		switch (token[1])
		{
		case 'a': /* artist */
		    if (track &&
			(!track->artist || prefs_get_int("parsetags_overwrite")))
		    {
			g_free (track->artist);
			track->artist = itm;
		    }
		    break;
		case 'A': /* album */
		    if (track &&
			(!track->album || prefs_get_int("parsetags_overwrite")))
		    {
			g_free (track->album);
			track->album = itm;
		    }
		    break;
		case 'c': /* composer */
		    if (track &&
			(!track->composer || prefs_get_int("parsetags_overwrite")))
		    {
			g_free (track->composer);
			track->composer = itm;
		    }
		    break;
		case 't': /* title */
		    if (track &&
			(!track->title || prefs_get_int("parsetags_overwrite")))
		    {
			g_free (track->title);
			track->title = itm;
		    }
		    break;
		case 'g': /* genre */
		case 'G': /* genre */
		    if (track &&
			(!track->genre || prefs_get_int("parsetags_overwrite")))
		    {
			g_free (track->genre);
			track->genre = itm;
		    }
		    break;
		case 'T': /* track */
		    if (track &&
			((track->track_nr == 0) ||
			 prefs_get_int("parsetags_overwrite")))
			track->track_nr = atoi (itm);
		    g_free (itm);
		    break;
		case 'C': /* CD */
		    if (track &&
			(track->cd_nr == 0 || prefs_get_int("parsetags_overwrite")))
			track->cd_nr = atoi (itm);
		    g_free (itm);
		    break;
		case 'Y': /* year */
		    if (track &&
			(track->year == 0 || prefs_get_int("parsetags_overwrite")))
			track->year = atoi (itm);
		    g_free (itm);
		    break;
		case '*': /* placeholder to skip a field */
		    g_free (itm);
		    break;
		default:
		    g_free (itm);
		    gtkpod_warning (_("Unknown token '%s' in template '%s'\n"),
				    token, template);
		    parse_error = TRUE;
		    break;
		}
		if (parse_error) break;
		gl = gln->next;
	    }
	    else
	    { /* if (gln)...else... */
		break;
	    }
	}
	else
	{   /* skip text */
	    gchar *fnp = g_strrstr (fn, token);
	    if (!fnp)
	    {
		parse_error = TRUE;
		break;  /* could not match */
	    }
	    if (fnp - fn + strlen (fnp) != strlen (fn))
	    {
		parse_error = TRUE;
		break; /* not at the last position */
	    }
	    fnp[0] = 0;
	    gl = gl->next;
	}
    }

    g_free (fn);
    g_free (tpl);
    g_list_foreach (tokens, (GFunc)g_free, NULL);
    g_list_free (tokens);
    return (!parse_error);
}

/* parse the filename of @track and extract the tags as specified in
   prefs_get_string("parsetags_template"). Several templates can be separated
   with the "," character. */
static void parse_filename (Track *track)
{
    ExtraTrackData *etr;
    gchar *template;
    gchar **templates, **tplp;

    g_return_if_fail (track);
    etr = track->userdata;
    g_return_if_fail (etr);

    template = prefs_get_string("parsetags_template");
    if (!template) return;
    templates = g_strsplit (template, ";", 0);
    tplp = templates;
    while (*tplp)
    {
	if (parse_filename_with_template (NULL, etr->pc_path_utf8, *tplp))
	    break;
	++tplp;
    }
    if (*tplp)  parse_filename_with_template (track, etr->pc_path_utf8, *tplp);
    g_strfreev (templates);
    g_free(template);
}

/* Set entry "column" (TM_COLUMN_TITLE etc) according to filename */
/* TODO: make the TAG extraction more intelligent -- if possible, this
   should be user configurable. */
static void set_entry_from_filename (Track *track, gint column)
{
    ExtraTrackData *etr;

    g_return_if_fail (track);
    etr = track->userdata;
    g_return_if_fail (etr);

    if (prefs_get_int_index("tag_autoset", column) &&
	etr->pc_path_utf8 && strlen (etr->pc_path_utf8))
    {
	switch (column)
	{
	case TM_COLUMN_TITLE:
	    g_free (track->title);
	    track->title = g_path_get_basename (etr->pc_path_utf8);
	    break;
	case TM_COLUMN_ALBUM:
	    g_free (track->album);
	    track->album = g_path_get_basename (etr->pc_path_utf8);
	    break;
	case TM_COLUMN_ARTIST:
	    g_free (track->artist);
	    track->artist = g_path_get_basename (etr->pc_path_utf8);
	    break;
	case TM_COLUMN_GENRE:
	    g_free (track->genre);
	    track->genre = g_path_get_basename (etr->pc_path_utf8);
	    break;
	case TM_COLUMN_COMPOSER:
	    g_free (track->composer);
	    track->composer = g_path_get_basename (etr->pc_path_utf8);
	    break;
	}
    }
}


static void set_unset_entries_from_filename (Track *track)
{
    /* try to fill tags from filename */
    if (prefs_get_int("parsetags"))
			parse_filename (track);
    /* fill up what is left unset */
    if (!track->album && prefs_get_int_index("tag_autoset", TM_COLUMN_ALBUM))
			set_entry_from_filename (track, TM_COLUMN_ALBUM);
    if (!track->artist && prefs_get_int_index("tag_autoset", TM_COLUMN_ARTIST))
			set_entry_from_filename (track, TM_COLUMN_ARTIST);
    if (!track->title && prefs_get_int_index("tag_autoset", TM_COLUMN_TITLE))
			set_entry_from_filename (track, TM_COLUMN_TITLE);
    if (!track->genre && prefs_get_int_index("tag_autoset", TM_COLUMN_GENRE))
			set_entry_from_filename (track, TM_COLUMN_GENRE);
    if (!track->composer && prefs_get_int_index("tag_autoset", 
																								TM_COLUMN_COMPOSER))
		{
			set_entry_from_filename (track, TM_COLUMN_COMPOSER);
		}
}


/* update the track->charset info with the currently used charset */
void update_charset_info (Track *track)
{
    const gchar *charset = prefs_get_string("charset");
    ExtraTrackData *etr;

    g_return_if_fail (track);
    etr = track->userdata;
    g_return_if_fail (etr);

    C_FREE (etr->charset);
    if (!charset || !strlen (charset))
    {    /* use standard locale charset */
	g_get_charset (&charset);
    }
    /* only set charset if it's not GTKPOD_JAPAN_AUTOMATIC */
    if (charset && (strcmp (charset, GTKPOD_JAPAN_AUTOMATIC) != 0))
    {
	etr->charset = g_strdup (charset);
    }
}


/* Copy "new" info read from file to an old Track structure. */
/* Return value: TRUE: at least one item was changed. FALSE: track was
   unchanged */
static gboolean copy_new_info (Track *from, Track *to)
{
    ExtraTrackData *efrom, *eto;
    T_item item;
    gboolean changed = FALSE;

    g_return_val_if_fail (from, FALSE);
    g_return_val_if_fail (to, FALSE);
    efrom = from->userdata;
    eto = to->userdata;
    g_return_val_if_fail (efrom, FALSE);
    g_return_val_if_fail (eto, FALSE);

    for (item=0; item<T_ITEM_NUM; ++item)
    {
	switch (item)
	{
	case T_ALBUM:
	case T_ARTIST:
	case T_TITLE:
	case T_GENRE:
	case T_COMMENT:
	case T_COMPOSER:
	case T_FILETYPE:
	case T_DESCRIPTION:
	case T_PODCASTURL:
	case T_PODCASTRSS:
	case T_SUBTITLE:
	case T_TV_SHOW:
	case T_TV_EPISODE:
	case T_TV_NETWORK:
	case T_THUMB_PATH:
	case T_PC_PATH:
	case T_ALBUMARTIST:
	case T_SORT_ARTIST:
	case T_SORT_TITLE:
	case T_SORT_ALBUM:
	case T_SORT_ALBUMARTIST:
	case T_SORT_COMPOSER:
	case T_SORT_TVSHOW:
	case T_YEAR:
	case T_TRACK_NR:
	case T_TRACKLEN:
	case T_STARTTIME:
	case T_STOPTIME:
	case T_SIZE:
	case T_BITRATE:
	case T_SAMPLERATE:
	case T_BPM:
	case T_TIME_ADDED:
	case T_TIME_MODIFIED:
	case T_TIME_RELEASED:
	case T_SOUNDCHECK:
	case T_CD_NR:
	case T_COMPILATION:
	case T_MEDIA_TYPE:
	case T_SEASON_NR:
	case T_EPISODE_NR:
	case T_GROUPING:
	case T_LYRICS:
	    changed |= track_copy_item (from, to, item);
	    break;
	case T_CATEGORY:
	    /* not implemented from tags */
	    break;
	case T_RATING:
	case T_REMEMBER_PLAYBACK_POSITION:
	case T_SKIP_WHEN_SHUFFLING:
	case T_CHECKED:
	case T_TIME_PLAYED:
	case T_IPOD_PATH:
	case T_ALL:
	case T_IPOD_ID:
	case T_TRANSFERRED:
	case T_PLAYCOUNT:
	case T_VOLUME:
	case T_GAPLESS_TRACK_FLAG:
	    /* not applicable */
	    break;
	case T_ITEM_NUM:
	    g_return_val_if_reached (FALSE);
	}
    }

    if ((eto->charset == NULL) || (strcmp (efrom->charset, eto->charset) != 0))
    {
	g_free (eto->charset);
	eto->charset = g_strdup (efrom->charset);
	changed = TRUE;
    }

    if (from->chapterdata)
    {
	itdb_chapterdata_free (to->chapterdata);
	to->chapterdata = itdb_chapterdata_duplicate (from->chapterdata);
	changed = TRUE; /* FIXME: probably should actually compare chapters for changes */
    }

    itdb_artwork_free (to->artwork);
    to->artwork = itdb_artwork_duplicate (from->artwork);
    if ((to->artwork_size != from->artwork_size) ||
	(to->artwork_count != from->artwork_count) ||
	(to->has_artwork != from->has_artwork))
    {   /* FIXME -- artwork might have changed nevertheless */
	changed = TRUE;
	to->artwork_size = from->artwork_size;
	to->artwork_count = from->artwork_count;
	to->has_artwork = from->has_artwork;
    }

    if ((to->lyrics_flag != from->lyrics_flag) ||
	(to->movie_flag != from->movie_flag))
    {
	changed = TRUE;
	to->lyrics_flag = from->lyrics_flag;
	to->movie_flag = from->movie_flag;
    }

    if ((to->pregap != from->pregap) ||
	(to->postgap != from->postgap) ||
	(to->samplecount != from->samplecount) ||
	(to->gapless_data != from->gapless_data) ||
	(to->gapless_track_flag != from->gapless_track_flag))
    {
	changed = TRUE;
	to->pregap = from->pregap;
	to->postgap = from->postgap;
	to->samplecount = from->samplecount;
	to->gapless_data = from->gapless_data;
	to->gapless_track_flag = from->gapless_track_flag;
    }

    if (eto->mtime != efrom->mtime)
    {
	changed = TRUE;
	eto->mtime = efrom->mtime;
    }

    return changed;
}

/* Updates mserv data (rating only) of @track using filename @name to
   look up mserv information.
   Return TRUE if successfully updated (or disabled), FALSE if not */
gboolean update_mserv_data_from_file (gchar *name, Track *track)
{
    gboolean success=TRUE;

    if (!name || !track) return FALSE;

    if (g_file_test (name, G_FILE_TEST_IS_DIR)) return FALSE;
    if (!g_file_test (name, G_FILE_TEST_EXISTS))
    {
	gchar *buf = g_strdup_printf (_("Local filename not valid (%s)"), name);
	display_mserv_problems (track, buf);
	g_free (buf);
	return FALSE;
    }

    if (prefs_get_int("mserv_use"))
    {
	/* try getting the user's rating from the mserv db */
	gchar *music_root = prefs_get_string ("path_mserv_music_root");
	gchar *trackinfo_root = prefs_get_string ("path_mserv_trackinfo_root");

	/* we expect music_root and trackinfo_root to be initialized */
	if (!music_root)
	    music_root = g_strdup ("");
	if (!trackinfo_root)
	    trackinfo_root = g_strdup ("");
	
	success = FALSE;
        /* printf("mroot %s troot %s fname %s\n", music_root, trackinfo_root, name); */

        /* first, check if the file is in the mserv music directory */
	if (*music_root == 0 || strstr(name, music_root))
	{
	    gchar *infoname = g_strdup_printf ("%s%c%s.trk",
					   trackinfo_root,
					   G_DIR_SEPARATOR,
					   &(name[strlen(music_root)]));
	    /* printf("trying %s\n", infoname); */
	    FILE *fp = fopen (infoname, "r");
	    if (fp)
	    {
		/* printf("opened\n");*/
		gchar buff[PATH_MAX];
		gchar *username = prefs_get_string("mserv_username");
		guint usernamelen;
		g_return_val_if_fail (username, (fclose (fp), FALSE));
		usernamelen = strlen (username);
		while (fgets(buff, PATH_MAX, fp))
		{
		    /* printf("username %s (%d) read %s\n",
		     * prefs_get_string("mserv_username"), usernamelen,
		     * buff);*/
		    if (strncmp(buff, username, usernamelen) == 0
			&& buff[usernamelen] == (gchar)'=')
		    {
			/* found it */
			track->rating = atoi(&buff[usernamelen+1]) * ITDB_RATING_STEP;
			/* printf("found it, = %d\n",
			   orig_track->rating/ITDB_RATING_STEP); */
			success = TRUE;
			break; /* while(fgets(... */
		    }
		}
		fclose(fp);
		g_free(username);
		if (!success)
		{
		    gchar *username = prefs_get_string("mserv_username");
		    gchar *buf = g_strdup_printf (_("No information found for user '%s' in '%s'"), 
						  username, infoname);
		    display_mserv_problems (track, buf);
		    g_free (buf);
		    g_free(username);
		}
	    }
	    else
	    {
		gchar *buf = g_strdup_printf (_("mserv data file (%s) not available for track (%s)"), infoname, name);
		display_mserv_problems (track, buf);
		g_free (buf);
	    }
	    g_free (infoname);
	}
	else
	{
	    gchar *buf = g_strdup_printf (_("Track (%s) not in mserv music root directory (%s)"), name, music_root);
	    display_mserv_problems (track, buf);
	    g_free (buf);
	}
	g_free (music_root);
	g_free (trackinfo_root);
    }

    while (widgets_blocked && gtk_events_pending ())
	gtk_main_iteration ();

    return success;
}

/* ensure that a cache directory is available for video thumbnail generation.
 * largely copied from conversion_setup_cachedir, only slightly simplified
 * and modified to return the path to the caller for convenience.
 */
static gchar* video_thumbnail_setup_cache() 
{
	gchar *cachedir = NULL;
	gchar *cfgdir = prefs_get_cfgdir();

	if (!cfgdir)
        return NULL;
    
    cachedir = g_build_filename (cfgdir, "video_thumbnail_cache", NULL);
    g_free (cfgdir);

    if (!g_file_test (cachedir, G_FILE_TEST_IS_DIR) && (g_mkdir (cachedir, 0777) == -1))
    {
        gtkpod_warning (_("Could not create '%s'"), cachedir);
	g_free (cachedir);
	cachedir = NULL;
    }

    return cachedir;
}

/*
 * automatically generate a thumbnail for video input files using
 * an external program (the totem thumbnailer by default).
 * @input is the path of the video file to be thumbnailed.
 * Returns a path to a temporary file containing the thumbnail.  The
 * temporary file is stored in a dedicated cache directory.
 */
static gchar* create_video_thumbnail (gchar* input)
{
	GString *cmd = NULL;
	GError *err = NULL;
	int fd, retval, forkstatus;
	gchar *thumbnailer = NULL, *tmp_fn = NULL, *tmp = NULL, *p = NULL;
	/* find (and set up if necessary) the thumbnail cache dir */
    gchar *tdir = video_thumbnail_setup_cache();

	if (!tdir)
	{
		return NULL;
	}
    
	/* safely generate a temporary file.  we don't actually need the fd
	 * so we close it on succesful generation */
	tmp_fn = g_build_filename (tdir, "thumb.XXXXXX", NULL);
	g_free(tdir);
	tdir = NULL;

	if ((fd = g_mkstemp(tmp_fn)) == -1 || close(fd))
	{
		gtkpod_warning (_("Error creating thumbnail file"));
		g_free (tmp_fn);
		return NULL;
	}
    
	/* get the string containing the (template) command for thumbnailing */
	thumbnailer = prefs_get_string("video_thumbnailer_prog");
	/* copy it into cmd, expanding any format characters */
	cmd = g_string_new("");
	p = thumbnailer;
    
	while (*p)
    {
		if (*p == '%') 
		{
			++p;
            
			switch (*p)
            {
			/* %f: input file */
			case 'f':
				tmp = g_shell_quote(input);
				break;
			/* %o: temporary output file */
			case 'o':
				tmp = g_shell_quote(tmp_fn);
				break;
			case '%':
				cmd = g_string_append_c (cmd, '%');
				break;
			default:
				gtkpod_warning (_("Unknown token '%%%c' in template '%s'"),
			                    *p, thumbnailer);
				break;
			}
            
			if (tmp)
			{
				cmd = g_string_append (cmd, tmp);
				g_free (tmp);
				tmp = NULL;
			}
		}
		else
		{
			cmd = g_string_append_c (cmd, *p);
		}
        
		++p;
	}
	/* run the thumbnailing program */
	forkstatus = g_spawn_command_line_sync(cmd->str, NULL, NULL, &retval, &err);
    
	if(!forkstatus)
	{
		gtkpod_warning (_("Unable to start video thumbnail generator\n(command line was: '%s')"), cmd->str);
	} 
	else if(retval)
	{
		gtkpod_warning (_("Thumbnail generator returned status %d"), retval);
	}
    
	g_string_free(cmd, TRUE);
	/* thumbnail is in tmp_fn */
	return tmp_fn;
}

/* look for a picture specified by coverart_template  */
static void add_coverart (Track *tr)
{
    ExtraTrackData *etr;
    gchar *full_template;
    gchar **templates, **tplp;
    gchar *dirname;
    gchar *filename_local = NULL;
    FileType type;
    gint vid_thumbnailer;

    g_return_if_fail (tr);
    etr = tr->userdata;
    g_return_if_fail (etr);

    dirname = g_path_get_dirname (etr->pc_path_utf8);
    type = determine_file_type(etr->pc_path_utf8);

    full_template = prefs_get_string("coverart_template");
    vid_thumbnailer = prefs_get_int("video_thumbnailer");

    templates = g_strsplit (full_template, ";", 0);
    tplp = templates;
    while (*tplp && !filename_local)
    {
	gchar *filename_utf8;
	gchar *fname = get_string_from_template (tr, *tplp, FALSE, FALSE);
	if (fname)
	{
	    if (strchr (*tplp, '.') != NULL)
	    {   /* if template has an extension, try if it is valid */
		if (fname[0] == '/')  /* allow absolute paths in template */
		    filename_utf8 = g_build_filename ("", fname, NULL);
		else
		    filename_utf8 = g_build_filename (dirname, fname, NULL);
		filename_local = charset_from_utf8 (filename_utf8);
		g_free (filename_utf8);
		if (!g_file_test (filename_local, G_FILE_TEST_EXISTS))
		{
		    g_free (filename_local);
		    filename_local = NULL;
		}
	    }
	    if (!filename_local)
	    {   /* if no filename is found try out different extensions */
		const gchar **extp = imageext;
		while (*extp && !filename_local)
		{
		    gchar *ffname = g_strconcat (fname, *extp, NULL);
		    if (ffname[0] == '/')  /* allow absolute paths in template */
			filename_utf8 = g_build_filename ("", ffname, NULL);
		    else
			filename_utf8 = g_build_filename (dirname, ffname,
			    NULL);
		    g_free (ffname);
		    filename_local = charset_from_utf8 (filename_utf8);
		    g_free (filename_utf8);
		    if (!g_file_test (filename_local, G_FILE_TEST_EXISTS))
		    {
			g_free (filename_local);
			filename_local = NULL;
		    }
		    ++extp;
		}
		extp = imageext;
		while (*extp && !filename_local)
		{   /* try uppercase version of extension */
		    gchar *upper_ext = g_ascii_strup (*extp, -1);
		    gchar *ffname = g_strconcat (fname, upper_ext, NULL);
		    g_free (upper_ext);
		    if (ffname[0] == '/')  /* allow absolute paths in template */
			filename_utf8 = g_build_filename ("", ffname, NULL);
		    else
			filename_utf8 = g_build_filename (dirname, ffname,
			    NULL);
		    g_free (ffname);
		    filename_local = charset_from_utf8 (filename_utf8);
		    g_free (filename_utf8);
		    if (!g_file_test (filename_local, G_FILE_TEST_EXISTS))
		    {
			g_free (filename_local);
			filename_local = NULL;
		    }
		    ++extp;
		}
	    }
	}
	g_free (fname);
	++tplp;
    }

    if (filename_local)
    {
	gp_track_set_thumbnails (tr, filename_local);
    }
    else if(vid_thumbnailer)
    {
        /* if a template match was not made, and we're dealing with a video 
         * file, generate an arbitrary thumbnail if appropriate */
        switch(type)
        {
            case FILE_TYPE_M4V:
            case FILE_TYPE_MP4:
            case FILE_TYPE_MOV:
            case FILE_TYPE_MPG:
                filename_local = create_video_thumbnail (etr->pc_path_utf8);
                gp_track_set_thumbnails (tr, filename_local);
                break;
            default:
                break;
        }
    }

    g_strfreev (templates);
    g_free (full_template);
    g_free (dirname);
}



/* Fills the supplied @orig_track with data from the file @name. If
 * @orig_track is NULL, a new track struct is created. The entries
 * pc_path_utf8 and pc_path_locale are not changed if an entry already
 * exists. time_added is not modified if already set. */
/* Returns NULL on error, a pointer to the Track otherwise */
static Track *get_track_info_from_file (gchar *name, Track *orig_track)
{
    Track *track = NULL;
    Track *nti = NULL;
    FileType filetype;
    gint len;
    gchar *name_utf8 = NULL;

    g_return_val_if_fail (name, NULL);

    if (g_file_test (name, G_FILE_TEST_IS_DIR)) return NULL;

    name_utf8 = charset_to_utf8 (name);

    if (!g_file_test (name, G_FILE_TEST_EXISTS))
    {
	gtkpod_warning (_("The following track could not be processed (file does not exist): '%s'\n"), name_utf8);
	g_free (name_utf8);
	return NULL;
    }

    /* reset the auto detection charset (see explanation in charset.c) */
    charset_reset_auto ();

    /* check for filetype */
    len = strlen (name);
    if (len < 4) return NULL;

    filetype = determine_file_type(name);
    switch (filetype)
    {
    case FILE_TYPE_MP3:
	nti = mp3_get_file_info (name);
	/* Set mediatype to audio */
	if (nti) nti->mediatype = ITDB_MEDIATYPE_AUDIO;
	break;
    case FILE_TYPE_M4A:
    case FILE_TYPE_M4P:
	nti = mp4_get_file_info (name);
	/* Set mediatype to audio */
	if (nti)
	{
	    nti->mediatype = ITDB_MEDIATYPE_AUDIO;
	}
	break;
    case FILE_TYPE_M4B:
	nti = mp4_get_file_info (name);
	/* Set mediatype to audiobook */
	if (nti)
	{
	    nti->mediatype = ITDB_MEDIATYPE_AUDIOBOOK;
	}
	break;
    case FILE_TYPE_WAV:
	nti = wav_get_file_info (name);
	/* Set mediatype to audio */
	if (nti)
	{
	    nti->mediatype = ITDB_MEDIATYPE_AUDIO;
	}
	break;
    case FILE_TYPE_OGG:
        nti = ogg_get_file_info (name);
        /* Set mediatype to audio */
        if (nti)
        {
            nti->mediatype = ITDB_MEDIATYPE_AUDIO;
        }
        break;
    case FILE_TYPE_FLAC:
        nti = flac_get_file_info (name);
        /* Set mediatype to audio */
        if (nti)
        {
            nti->mediatype = ITDB_MEDIATYPE_AUDIO;
        }
        break;
    case FILE_TYPE_M4V:
    case FILE_TYPE_MP4:
	/* I don't know if .m4v and .mp4 can simply be handled like
	   this. Let's see if someone complains. */
	nti = mp4_get_file_info (name);
	if (!nti) video_get_file_info (name);
	/* Set mediatype to video */
	if (nti)
	{
	    nti->mediatype = ITDB_MEDIATYPE_MOVIE;
	    nti->movie_flag = 0x01;
	}	
	break;
    case FILE_TYPE_MOV:
    case FILE_TYPE_MPG:
	/* for now treat all the same */
	nti = video_get_file_info (name);
	/* Set mediatype to video */
	if (nti)
	{
	    nti->mediatype = ITDB_MEDIATYPE_MOVIE;
	    nti->movie_flag = 0x01;
	}
	break;
    case FILE_TYPE_UNKNOWN:
	gtkpod_warning (_("The following track could not be processed (filetype unknown): '%s'\n"), name_utf8);
	g_free (name_utf8);
	return NULL;
    case FILE_TYPE_IMAGE:
    case FILE_TYPE_DIRECTORY:
    case FILE_TYPE_M3U:
    case FILE_TYPE_PLS:
	break;
    }

    if (nti)
    {
	ExtraTrackData *enti=nti->userdata;
	struct stat filestat;

	g_return_val_if_fail (enti, NULL);

	if (enti->charset == NULL)
	{   /* Fill in currently used charset. Try if auto_charset is
	     * set first. If not, use the currently set charset. */
	    enti->charset = charset_get_auto ();
	    if (enti->charset == NULL)
		update_charset_info (nti);
	}
	/* set path file information */
	enti->pc_path_utf8 = charset_to_utf8 (name);
	enti->pc_path_locale = g_strdup (name);
	enti->lyrics=NULL;
	/* set length of file */
	stat (name, &filestat);
	nti->size = filestat.st_size; /* get the filesize in bytes */
	enti->mtime = filestat.st_mtime; /* get the modification date */
	if (nti->bitrate == 0)
	{  /* estimate bitrate */
	    if (nti->tracklen)
		nti->bitrate = nti->size * 8 / nti->tracklen;
	}
	/* Set unset strings (album...) from filename */
	set_unset_entries_from_filename (nti);

	/* Set coverart */
	if (prefs_get_int("coverart_file"))
	{
	    /* APIC data takes precedence */
	    if (! itdb_track_has_thumbnails (nti))
		add_coverart (nti);
	}

	/* Set modification date to the files modified date */
	nti->time_modified = enti->mtime;
	/* Set added date to *now* (unless orig_track is present) */
	if (orig_track)
	{
	    nti->time_added = orig_track->time_added;
	}
	else
	{
	    nti->time_added = time (NULL);
	}

	/* Make sure all strings are initialized -- that way we don't
	   have to worry about it when we are handling the
	   strings. Also, validate_entries() will fill in the utf16
	   strings if that hasn't already been done. */
	/* exception: sha1_hash, charset and hostname: these may be
	 * NULL. */

	gp_track_validate_entries (nti);

	if (orig_track)
	{ /* we need to copy all information over to the original
	   * track */
	    ExtraTrackData *eorigtr=orig_track->userdata;

	    g_return_val_if_fail (eorigtr, NULL);

	    eorigtr->tchanged = copy_new_info (nti, orig_track);

	    track = orig_track;
	    itdb_track_free (nti);
	    nti = NULL;
	}
	else
	{ /* just use nti */
	    track = nti;
	    nti = NULL;
	}

	update_mserv_data_from_file (name, track);
    }
    else
    {
	switch (filetype)
	{
	case FILE_TYPE_IMAGE:
	case FILE_TYPE_M3U:
	case FILE_TYPE_PLS:
	    break;
	default:
	    gtkpod_warning (_("The following track could not be processed (filetype is known but analysis failed): '%s'\n"), name_utf8);
	    break;
	}
    }

    while (widgets_blocked && gtk_events_pending ())
	gtk_main_iteration ();

    g_free (name_utf8);

    return track;
}


/*------------------------------------------------------------------*\
 *                                                                  *
 *      Update Track Data from File                                  *
 *                                                                  *
\*------------------------------------------------------------------*/


/* reads info from file and updates the ID3 tags of
   @selected_tracks. */
void update_tracks (GList *selected_tracks)
{
    GList *gl;
    iTunesDB *itdb = NULL;

    if (selected_tracks == NULL)
    {
	gtkpod_statusbar_message(_("Nothing to update"));
	return;
    }

    block_widgets ();
    for (gl=selected_tracks; gl; gl=gl->next)
    {
	Track *track = gl->data;
	g_return_if_fail (track);

	/* update_track_from_file() may possibly remove tracks from
	   the database, so we need to check if the track we are
	   referencing to is still valid. To do so we first have to
	   secure a valid pointer to an itdb. Since the first track in
	   selected_tracks is always valid, we take that one. */
	if (!itdb)
	    itdb = track->itdb;
	g_return_if_fail (itdb);
	if (g_list_find (itdb->tracks, track))
	{
	    gchar *buf = get_track_info (track, TRUE);
	    gtkpod_statusbar_message (_("Updating %s"), buf);
	    g_free (buf);
	    update_track_from_file (track->itdb, track);
	}
    }
    release_widgets ();
    /* display log of non-updated tracks */
    display_non_updated (NULL, NULL);
    /* display log of updated tracks */
    display_updated (NULL, NULL);
    /* display log of problems with mserv data */
    display_mserv_problems (NULL, NULL);
    /* display log of detected duplicates */
    gp_duplicate_remove (NULL, NULL);
    gtkpod_statusbar_message(_("Updated selected tracks with info from file."));
}


/*------------------------------------------------------------------*\
 *                                                                  *
 *      Update mserv Data from File                                 *
 *                                                                  *
\*------------------------------------------------------------------*/


/* reads info from file and updates the ID3 tags of
   @selected_tracks. */
void mserv_from_file_tracks (GList *selected_tracks)
{
    GList *gl;

    if (selected_tracks == NULL)
    {
	gtkpod_statusbar_message(_("Nothing to update"));
	return;
    }

    block_widgets ();
    for (gl = selected_tracks; gl; gl=gl->next)
    {
	ExtraTrackData *etr;
	Track *track = gl->data;
	gchar *buf;
	g_return_if_fail (track);
	etr = track->userdata;
	g_return_if_fail (etr);

	buf = get_track_info (track, TRUE);
	gtkpod_statusbar_message (_("Retrieving mserv data %s"), buf);
	g_free (buf);
	if (etr->pc_path_locale && *etr->pc_path_locale)
	    update_mserv_data_from_file (etr->pc_path_locale, track);
	else
	    display_mserv_problems (track, _("no filename available"));
    }
    release_widgets ();
    /* display log of problems with mserv data */
    display_mserv_problems (NULL, NULL);
    gtkpod_statusbar_message(_("Updated selected tracks with data from mserv."));
}



/* Logs tracks (@track) that could not be updated from file for some
   reason. Pop up a window with the log by calling with @track = NULL,
   or remove the log by calling with @track = -1.
   @txt (if available)w is added as an explanation as to why it was
   impossible to update the track */
void display_non_updated (Track *track, gchar *txt)
{
   gchar *buf;
   static gint track_nr = 0;
   static GString *str = NULL;

   if ((track == NULL) && str)
   {
       if (prefs_get_int("show_non_updated") && str->len)
       { /* Some tracks have not been updated. Print a notice */
	   buf = g_strdup_printf (
	       ngettext ("The following track could not be updated",
			 "The following %d tracks could not be updated",
			 track_nr), track_nr);
	   gtkpod_confirmation
	       (-1,                 /* gint id, */
		FALSE,              /* gboolean modal, */
		_("Failed Track Update"),   /* title */
		buf,                /* label */
		str->str,           /* scrolled text */
		NULL, 0, NULL,          /* option 1 */
		NULL, 0, NULL,          /* option 2 */
		TRUE,               /* gboolean confirm_again, */
		"show_non_updated",/* confirm_again_key,*/
		CONF_NULL_HANDLER,  /* ConfHandler ok_handler,*/
		NULL,               /* don't show "Apply" button */
		NULL,               /* cancel_handler,*/
		NULL,               /* gpointer user_data1,*/
		NULL);              /* gpointer user_data2,*/
	   g_free (buf);
       }
       display_non_updated ((void *)-1, NULL);
   }

   if (track == (void *)-1)
   { /* clean up */
       if (str)       g_string_free (str, TRUE);
       str = NULL;
       track_nr = 0;
       gtkpod_tracks_statusbar_update();
   }
   else if (prefs_get_int("show_non_updated") && track)
   {
       /* add info about it to str */
       buf = get_track_info (track, TRUE);
       if (!str)
       {
	   track_nr = 0;
	   str = g_string_sized_new (2000); /* used to keep record of
					     * non-updated tracks */
       }
       if (txt) g_string_append_printf (str, "%s (%s)\n", buf, txt);
       else     g_string_append_printf (str, "%s\n", buf);
       g_free (buf);
       ++track_nr; /* count tracks */
   }
}


/* Logs tracks (@track) that could be updated from file. Pop up a window
   with the log by calling with @track = NULL, or remove the log by
   calling with @track = -1.
   @txt (if available)w is added as an explanation as to why it was
   impossible to update the track */
void display_updated (Track *track, gchar *txt)
{
   gchar *buf;
   static gint track_nr = 0;
   static GString *str = NULL;

   if (prefs_get_int("show_updated") && (track == NULL) && str)
   {
       if (str->len)
       { /* Some tracks have been updated. Print a notice */
	   buf = g_strdup_printf (
	       ngettext ("The following track has been updated",
			 "The following %d tracks have been updated",
			 track_nr), track_nr);
	   gtkpod_confirmation
	       (-1,                 /* gint id, */
		FALSE,              /* gboolean modal, */
		_("Successful Track Update"),   /* title */
		buf,                /* label */
		str->str,           /* scrolled text */
		NULL, 0, NULL,          /* option 1 */
		NULL, 0, NULL,          /* option 2 */
		TRUE,               /* gboolean confirm_again, */
		"show_updated",/* confirm_again_key,*/
		CONF_NULL_HANDLER,  /* ConfHandler ok_handler,*/
		NULL,               /* don't show "Apply" button */
		NULL,               /* cancel_handler,*/
		NULL,               /* gpointer user_data1,*/
		NULL);              /* gpointer user_data2,*/
	   g_free (buf);
       }
       display_updated ((void *)-1, NULL);
   }

   if (track == (void *)-1)
   { /* clean up */
       if (str)       g_string_free (str, TRUE);
       str = NULL;
       track_nr = 0;
       gtkpod_tracks_statusbar_update();
   }
   else if (prefs_get_int("show_updated") && track)
   {
       /* add info about it to str */
       buf = get_track_info (track, TRUE);
       if (!str)
       {
	   track_nr = 0;
	   str = g_string_sized_new (2000); /* used to keep record of
					     * non-updated tracks */
       }
       if (txt) g_string_append_printf (str, "%s (%s)\n", buf, txt);
       else     g_string_append_printf (str, "%s\n", buf);
       g_free (buf);
       ++track_nr; /* count tracks */
   }
}


/* Logs tracks (@track) that could not be updated with info from mserv
   database for some reason. Pop up a window with the log by calling
   with @track = NULL, or remove the log by calling with @track = -1.
   @txt (if available) is added as an explanation as to why it was
   impossible to retrieve mserv information */
void display_mserv_problems (Track *track, gchar *txt)
{
   gchar *buf;
   static gint track_nr = 0;
   static GString *str = NULL;

   if ((track == NULL) && str)
   {
       if (prefs_get_int("mserv_use") &&
	   prefs_get_int("mserv_report_probs") && str->len)
       { /* Some tracks have had problems. Print a notice */
	   buf = g_strdup_printf (
	       ngettext ("No mserv information could be retrieved for the following track",
			 "No mserv information could be retrieved for the following %d tracks",
			 track_nr), track_nr);
	   gtkpod_confirmation
	       (-1,                 /* gint id, */
		FALSE,              /* gboolean modal, */
		_("mserv data retrieval problem"),   /* title */
		buf,                /* label */
		str->str,           /* scrolled text */
		NULL, 0, NULL,          /* option 1 */
		NULL, 0, NULL,          /* option 2 */
		TRUE,               /* gboolean confirm_again, */
		"mserv_report_probs",/* confirm_again_key,*/
		CONF_NULL_HANDLER,  /* ConfHandler ok_handler,*/
		NULL,               /* don't show "Apply" button */
		NULL,               /* cancel_handler,*/
		NULL,               /* gpointer user_data1,*/
		NULL);              /* gpointer user_data2,*/
	   g_free (buf);
       }
       display_mserv_problems ((void *)-1, NULL);
   }

   if (track == (void *)-1)
   { /* clean up */
       if (str)       g_string_free (str, TRUE);
       str = NULL;
       track_nr = 0;
       gtkpod_tracks_statusbar_update();
   }
   else if (prefs_get_int("mserv_use") &&
	    prefs_get_int("mserv_report_probs") && track)
   {
       /* add info about it to str */
       buf = get_track_info (track, TRUE);
       if (!str)
       {
	   track_nr = 0;
	   str = g_string_sized_new (2000); /* used to keep record */
       }
       if (txt) g_string_append_printf (str, "%s (%s)\n", buf, txt);
       else     g_string_append_printf (str, "%s\n", buf);
       g_free (buf);
       ++track_nr; /* count tracks */
   }
}


/* Update information of @track from data in original file. If the
 * original filename is not available, information will be updated
 * from the copy on the iPod and a warning is printed.

   A list of non-updated tracks can be displayed by calling
   display_non_updated (NULL, NULL). This list can be deleted by
   calling display_non_updated ((void *)-1, NULL);

   It is also possible that duplicates get detected in the process --
   a list of those can be displayed by calling "gp_duplicate_remove
   (NULL, NULL)", that list can be deleted by calling
   "gp_duplicate_remove (NULL, (void *)-1)"*/
void update_track_from_file (iTunesDB *itdb, Track *track)
{
    ExtraTrackData *oetr;
    Track *oldtrack;
    gchar *prefs_charset = NULL;
    gchar *trackpath = NULL;
    gint32 oldsize = 0;
    gboolean charset_set;

    g_return_if_fail (itdb);
    g_return_if_fail (track);
    oetr = track->userdata;
    g_return_if_fail (oetr);
    /* remember size of track on iPod */
    if (track->transferred) oldsize = track->size;
    else                    oldsize = 0;

    /* remember if charset was set */
    if (oetr->charset)  charset_set = TRUE;
    else               charset_set = FALSE;

    if (!prefs_get_int("update_charset") && charset_set)
    {   /* we should use the initial charset for the update */
	prefs_charset = prefs_get_string("charset");
	/* use the charset used when first importing the track */
	prefs_set_string("charset", oetr->charset);
    }

    trackpath = get_file_name_from_source (track, SOURCE_PREFER_LOCAL);

    if (!(oetr->pc_path_locale && *oetr->pc_path_locale))
    { /* no path available */
	if (trackpath)
	{
	    display_non_updated (track, _("no local filename available, file on the iPod will be used instead"));
	}
	else
	{
	    if (itdb->usertype & GP_ITDB_TYPE_IPOD)
	    {
		display_non_updated (track, _("no local filename available and copy on iPod cannot be found"));
	    }
	    else
	    {
		display_non_updated (track, _("no local filename available"));
	    }
	}
    }
    else if (!g_file_test (oetr->pc_path_locale, G_FILE_TEST_EXISTS))
    {
	if (trackpath)
	{
	    display_non_updated (track, _("local file could not be found, file on the iPod will be used instead"));
	}
	else
	{
	    if (itdb->usertype & GP_ITDB_TYPE_IPOD)
	    {
		display_non_updated (track, _("local file as well as copy on the iPod cannot be found"));
	    }
	    else
	    {
		display_non_updated (track, _("no local filename available"));
	    }
	}
    }

    if (trackpath && get_track_info_from_file (trackpath, track))
    { /* update successful */
	ExtraTrackData *netr = track->userdata;

	/* remove track from sha1 hash and reinsert it
	   (hash value may have changed!) */
	gchar *oldhash = oetr->sha1_hash;

	sha1_track_remove (track);
	/* need to remove the old value manually! */
	oetr->sha1_hash = NULL;
	oldtrack = sha1_track_exists_insert (itdb, track);
	if (oldtrack) { /* track exists, remove old track
			  and register the new version */
	    sha1_track_remove (oldtrack);
	    gp_duplicate_remove (track, oldtrack);
	    sha1_track_exists_insert (itdb, track);
	}

	if (itdb->usertype & GP_ITDB_TYPE_IPOD)
	{   /* track may have to be copied to iPod on next export */
	    gchar *name_on_ipod;
	    gboolean transfer_again = FALSE;

	    name_on_ipod = get_file_name_from_source (track, SOURCE_IPOD);
	    if (name_on_ipod && (strcmp (name_on_ipod, trackpath) != 0))
	    {   /* trackpath is not on the iPod */
		if (oldhash && oetr->sha1_hash)
		{   /* do we really have to copy the track again? */
		    if (strcmp (oldhash, oetr->sha1_hash) != 0)
		    {
			transfer_again = TRUE;
		    }
		}
		else
		{   /* no hash available -- copy! */
		    transfer_again = TRUE;
		}
	    }
	    else
	    {
		data_changed (itdb);
	    }

	    if (transfer_again)
	    {   /* We need to copy the track back to the iPod. That's done
		   marking a copy of the original track for deletion and
		   then adding the original track to the
		   conversion/transfer list */
		Track *new_track = gp_track_new ();
		ExtraTrackData *new_etr = new_track->userdata;
		g_return_if_fail (new_etr);

		new_track->size = oldsize;
		new_track->ipod_path = track->ipod_path;
		track->ipod_path = g_strdup ("");
		track->transferred = FALSE;

		/* cancel conversion/transfer of track */
		file_convert_cancel_track (track);
		/* mark the track for deletion on the ipod */
		mark_track_for_deletion (itdb, new_track);
		/* reschedule conversion/transfer of track */
		file_convert_add_track (track);

		netr->tchanged = TRUE;
	    }

	    g_free (name_on_ipod);
	}

	/* Set this flag to true to ensure artwork is reread from file */
	netr->tartwork_changed = TRUE;
	
	/* notify display model */
	if (netr->tchanged)
	{
	    pm_track_changed (track);
	    data_changed (itdb);
	    netr->tchanged = FALSE;
	}
	else
	{
		/* Rather than depend on the track data being changed, only the artwork may have changed
		 * hence the reason for the user updating from file
		 */
		coverart_track_changed (track, COVERART_CHANGE_SIGNAL);
	}
	
	display_updated (track, NULL);
        g_free (oldhash);
    }
    else if (trackpath)
    { /* update not successful -- log this track for later display */
	display_non_updated (track, _("update failed (format not supported?)"));
    }

    if (!prefs_get_int("update_charset") && charset_set)
    {   /* reset charset */
	prefs_set_string("charset", prefs_charset);
    }

    g_free (trackpath);
    g_free(prefs_charset);

    while (widgets_blocked && gtk_events_pending ())  gtk_main_iteration ();
}


/*------------------------------------------------------------------*\
 *                                                                  *
 *      Add File                                                    *
 *                                                                  *
\*------------------------------------------------------------------*/

/* Append file @fname to the list of tracks.
   @fname is in the current locale
   @plitem: if != NULL, add track to plitem as well (unless it's the MPL)
   descend: TRUE:  add directories recursively
            FALSE: add contents of directories passed but don't descend
                   into its subdirectories */
/* @addtrackfunc: if != NULL this will be called instead of
   "add_track_to_playlist () -- used for dropping tracks at a specific
   position in the track view */
gboolean add_track_by_filename (iTunesDB *itdb, gchar *fname,
				Playlist *plitem, gboolean descend,
				AddTrackFunc addtrackfunc, gpointer data)
{
  static gint count = 0; /* do a gtkpod_tracks_statusbar_update() every
			    10 tracks */
  Track *oldtrack;
  gchar str[PATH_MAX];
  gchar *basename;
  Playlist *mpl;
  gboolean result = TRUE;

  g_return_val_if_fail (fname, FALSE);
  g_return_val_if_fail (itdb, FALSE);
  mpl = itdb_playlist_mpl (itdb);
  g_return_val_if_fail (mpl, FALSE);

  if (!plitem)  plitem = mpl;

  if (g_file_test (fname, G_FILE_TEST_IS_DIR))
  {
      return add_directory_by_name (itdb, fname, plitem, descend, addtrackfunc, data);
  }

  /* check if file is a playlist */
  switch (determine_file_type(fname))
  {
  case FILE_TYPE_M3U:
  case FILE_TYPE_PLS:
      if (add_playlist_by_filename (itdb, fname, plitem, -1,
				    addtrackfunc, data))
	  return TRUE;
      return FALSE;
  case FILE_TYPE_MP3:
  case FILE_TYPE_M4A:
  case FILE_TYPE_M4P:
  case FILE_TYPE_M4B:
  case FILE_TYPE_WAV:
  case FILE_TYPE_M4V:
  case FILE_TYPE_MP4:
  case FILE_TYPE_MOV:
  case FILE_TYPE_MPG:
  case FILE_TYPE_OGG:
  case FILE_TYPE_FLAC:
  case FILE_TYPE_IMAGE:
  case FILE_TYPE_UNKNOWN:
  case FILE_TYPE_DIRECTORY:
      break;
  }

  /* print a message about which file is being processed */
  basename = g_path_get_basename (fname);
  if (basename)
  {
      gchar *bn_utf8 = charset_to_utf8 (basename);
      gtkpod_statusbar_message (_("Processing '%s'..."), bn_utf8);
      while (widgets_blocked && gtk_events_pending ())  gtk_main_iteration ();
      g_free (bn_utf8);

      if (excludefile(basename))
      {
          gtkpod_warning (_("Skipping '%s' because it matches exclude masks.\n"), basename);
	  while (widgets_blocked && gtk_events_pending ())
	      gtk_main_iteration ();
	  g_free (basename);
	  return FALSE;
      }
  }
  C_FREE (basename);

  /* Check if there exists already a track with the same filename */
  oldtrack = gp_track_by_filename (itdb, fname);
  /* If a track already exists in the database, either update it or
     just add it to the current playlist (if it's not already there) */
  if (oldtrack)
  {
      if (prefs_get_int("update_existing"))
      {   /* update the information */
	  update_track_from_file (itdb, oldtrack);
      }
      /* add to current playlist if it's not already in there */
      if (!itdb_playlist_is_mpl (plitem))
      {
	  if (!itdb_playlist_contains_track (plitem, oldtrack))
	  {
	      if (addtrackfunc)
		  addtrackfunc (plitem, oldtrack, data);
	      else
		  gp_playlist_add_track (plitem, oldtrack, TRUE);
	  }
      }
  }
  else  /* oldtrack == NULL */
  {   /* OK, the same filename does not already exist */
      Track *track = get_track_info_from_file (fname, NULL);
      if (track)
      {
          Track *added_track = NULL;
	  ExtraTrackData *etr = track->userdata;
	  g_return_val_if_fail (etr, FALSE);

	  track->id = 0;
	  track->transferred = FALSE;

	  /* is 'fname' on the iPod? -- if yes mark as transfered, if
	   * it's in the music directory */
	  if (itdb->usertype & GP_ITDB_TYPE_IPOD)
	  {
	      const gchar *mountpoint = itdb_get_mountpoint (itdb);
	      g_return_val_if_fail (mountpoint, FALSE);
	      if (strstr (fname, mountpoint) == fname)
	      {   /* Yes */
		  /* is 'fname' in the iPod's Music directory? */
		  gchar *music_dir = itdb_get_music_dir (mountpoint);
		  if (music_dir)
		  {
		      gchar *cdir = g_strdup_printf ("%s%c", music_dir,
						     G_DIR_SEPARATOR);
		      if (g_strncasecmp (fname, cdir, strlen (cdir)) == 0)
		      {   /* Yes */
			  gchar *fname_i = fname + strlen (mountpoint);
			  if (*fname_i == G_DIR_SEPARATOR) ++fname_i;
			  track->transferred = TRUE;
			  track->ipod_path = g_strdup_printf (
			      "%c%s", G_DIR_SEPARATOR, fname_i);
			  itdb_filename_fs2ipod (track->ipod_path);
		      }
		      g_free (music_dir);
		      g_free (cdir);
		  }
	      }
	  }

	  if (gethostname (str, PATH_MAX-2) == 0)
	  {
	      str[PATH_MAX-1] = 0;
	      etr->hostname = g_strdup (str);
	  }
	  /* add_track may return pointer to a different track if an
	     identical one (SHA1 checksum) was found */
	  added_track = gp_track_add (itdb, track);
	  g_return_val_if_fail (added_track, FALSE);

	  /* set flags to 'podcast' if adding to podcast list */
	  if (itdb_playlist_is_podcasts (plitem))
	      gp_track_set_flags_podcast (added_track);

	  if (itdb_playlist_is_mpl (plitem))
	  {   /* add track to master playlist if it wasn't a
		 duplicate */
	      if (added_track == track)
	      {
		  if (addtrackfunc)
		      addtrackfunc (plitem, added_track, data);
		  else
		      gp_playlist_add_track (plitem, added_track, TRUE);
	      }
	  }
	  else
	  {
#if 0 /* initially iTunes didn't add podcasts to the MPL */
	      /* add track to master playlist if it wasn't a
	       * duplicate and plitem is not the podcasts playlist
	       */
	      if (added_track == track)
	      {
		  if (!itdb_playlist_is_podcasts (plitem))
		      gp_playlist_add_track (mpl, added_track, TRUE);
	      }
#else
	      if (added_track == track)
	      {
		  gp_playlist_add_track (mpl, added_track, TRUE);
	      }
#endif
	      /* add track to specified playlist -- unless adding
	       * to podcasts list and track already exists there */
	      if (itdb_playlist_is_podcasts (plitem) &&
		  g_list_find (plitem->members, added_track))
	      {
		  gchar *buf = get_track_info (added_track, FALSE);
		  gtkpod_warning (_("Podcast already present: '%s'\n\n"), buf);
		  g_free (buf);
	      }
	      else
	      {
		  if (addtrackfunc)
		      addtrackfunc (plitem, added_track, data);
		  else
		      gp_playlist_add_track (plitem, added_track, TRUE);
	      }
	  }

	  /* indicate that non-transferred files exist */
	  data_changed (itdb);
	  ++count;
	  if (count >= 10)  /* update every ten tracks added */
	  {
	      gtkpod_tracks_statusbar_update();
	      count = 0;
	  }
      }
      else
      { /* !track */
	  result = FALSE;
      }
  }
  while (widgets_blocked && gtk_events_pending ())  gtk_main_iteration ();
  return result;
}


/*------------------------------------------------------------------*\
 *                                                                  *
 *      Write Tags                                                  *
 *                                                                  *
\*------------------------------------------------------------------*/


/* Call the correct tag writing function for the filename @name */
static gboolean file_write_info (gchar *name, Track *track)
{
    gchar *buf;

    g_return_val_if_fail (name, FALSE);
    g_return_val_if_fail (track, FALSE);

    switch (determine_file_type(name))
    {
    case FILE_TYPE_MP3:
	return mp3_write_file_info (name, track);
    case FILE_TYPE_M4A:
    case FILE_TYPE_M4P:
    case FILE_TYPE_M4B:
	return mp4_write_file_info (name, track);
    case FILE_TYPE_WAV:
	return wav_write_file_info (name, track);
    case FILE_TYPE_OGG:
        return ogg_write_file_info (name, track);
    case FILE_TYPE_FLAC:
        return flac_write_file_info (name, track);
    case FILE_TYPE_M4V:
    case FILE_TYPE_MP4:
    case FILE_TYPE_MOV:
    case FILE_TYPE_MPG:
	buf = get_track_info (track, FALSE);
	gtkpod_warning (_("Writing to video files not yet supported (%s).\n\n"),
			buf);
	g_free (buf);
	break;
    case FILE_TYPE_M3U:
    case FILE_TYPE_PLS:
    case FILE_TYPE_IMAGE:
    case FILE_TYPE_UNKNOWN:
    case FILE_TYPE_DIRECTORY:
	break;
    }

    return FALSE;
}


/* Write tags to file */
gboolean write_tags_to_file (Track *track)
{
    ExtraTrackData *etr;
    iTunesDB *itdb;
    gchar *ipod_fullpath;
    gchar *prefs_charset = NULL;
    Track *oldtrack;
    gboolean track_charset_set;

    g_return_val_if_fail (track, FALSE);
    etr = track->userdata;
    g_return_val_if_fail (etr, FALSE);
    itdb = track->itdb;
    g_return_val_if_fail (itdb, FALSE);

    /* if we are to use the charset used when first importing
       the track, change the prefs settings temporarily */
    if (etr->charset)  track_charset_set = TRUE;
    else               track_charset_set = FALSE;
    if (!prefs_get_int("write_charset") && track_charset_set)
    {   /* we should use the initial charset for the update */
	prefs_charset = prefs_get_string("charset");
	/* use the charset used when first importing the track */
	prefs_set_string("charset", etr->charset);
    }
    else
    {   /* we should update the track->charset information */
	update_charset_info (track);
    }

    if (etr->pc_path_locale && (strlen (etr->pc_path_locale) > 0))
    {
	if (file_write_info (
		etr->pc_path_locale, track) == FALSE)
	{
	    gtkpod_warning (_("Couldn't change tags of file: %s\n"),
			    etr->pc_path_locale);
	}
    }
    if (!get_offline (itdb) &&
	track->transferred &&
	track->ipod_path &&
	(g_utf8_strlen (track->ipod_path, -1) > 0))
    {
	/* need to get ipod filename */
	ipod_fullpath = get_file_name_from_source (track, SOURCE_IPOD);
	if (file_write_info (
		ipod_fullpath, track) == FALSE)
	{
	    gtkpod_warning (_("Couldn't change tags of file: %s\n"),
			    ipod_fullpath);
	}
	g_free (ipod_fullpath);
    }
    /* remove track from sha1 hash and reinsert it (hash value has changed!) */
    sha1_track_remove (track);
    C_FREE (etr->sha1_hash);  /* need to remove the old value manually! */
    oldtrack = sha1_track_exists_insert (itdb, track);
    if (oldtrack) { /* track exists, remove and register the new version */
	sha1_track_remove (oldtrack);
	gp_duplicate_remove (track, oldtrack);
	sha1_track_exists_insert (itdb, track);
    }

    if (!prefs_get_int("write_charset") && track_charset_set)
    {   /* reset charset */
	prefs_set_string("charset", prefs_charset);
    }
    g_free (prefs_charset);
    return TRUE;
}


/* Get file name from source @source */
/* File is guaranteed to exist, otherwise NULL is returned. */
gchar *get_file_name_from_source (Track *track, FileSource source)
{
    gchar *result = NULL;
    ExtraTrackData *etr;

    g_return_val_if_fail (track, NULL);
    etr = track->userdata;
    g_return_val_if_fail (etr, NULL);

    switch (source)
    {
    case SOURCE_PREFER_LOCAL:
	result = get_file_name_from_source (track, SOURCE_LOCAL);
	if (!result)
	{
	    if (track->itdb && (track->itdb->usertype & GP_ITDB_TYPE_IPOD))
	    {
		result = get_file_name_from_source (track, SOURCE_IPOD);
	    }
	}
	break;
    case SOURCE_PREFER_IPOD:
	result = get_file_name_from_source (track, SOURCE_IPOD);
	if (!result)
	    result = get_file_name_from_source (track, SOURCE_LOCAL);
	break;
    case SOURCE_LOCAL:
	if (etr->pc_path_locale && (*etr->pc_path_locale))
	{
	    if (g_file_test (etr->pc_path_locale, G_FILE_TEST_EXISTS))
	    {
		result = g_strdup (etr->pc_path_locale);
	    }
	}
	break;
    case SOURCE_IPOD:
	if(track &&  !get_offline (track->itdb))
	{
	    result = itdb_filename_on_ipod (track);
	}
	break;
    }
    return result;
}






/* ------------------------------------------------------------

        Reading of offline playcount file

   ------------------------------------------------------------ */

/* Read the ~/.gtkpod/offline_playcount file and adjust the
   playcounts. The tracks will first be matched by their sha1 sum, if
   that fails, by their filename.
   If tracks could not be matched, the user will be queried whether to
   forget about them or write them back into the offline_playcount
   file. */
void parse_offline_playcount (void)
{
    gchar *cfgdir = prefs_get_cfgdir ();
    gchar *offlplyc = g_strdup_printf (
	"%s%c%s", cfgdir, G_DIR_SEPARATOR, "offline_playcount");

    if (g_file_test (offlplyc, G_FILE_TEST_EXISTS))
    {
	FILE *file = fopen (offlplyc, "r+");
	size_t len = 0;  /* how many bytes are written */
	gchar *buf;
	GString *gstr, *gstr_filenames;
	if (!file)
	{
	    gtkpod_warning (_("Could not open '%s' for reading and writing.\n"),
		       offlplyc);
	    g_free (offlplyc);
	    return;
	}
	if (flock (fileno (file), LOCK_EX) != 0)
	{
	    gtkpod_warning (_("Could not obtain lock on '%s'.\n"), offlplyc);
	    fclose (file);
	    g_free (offlplyc);
	    return;
	}
	buf = g_malloc (2*PATH_MAX);
	gstr = g_string_sized_new (PATH_MAX);
	gstr_filenames = g_string_sized_new (PATH_MAX);
	while (fgets (buf, 2*PATH_MAX, file))
	{
	    gchar *buf_utf8 = charset_to_utf8 (buf);
	    gchar *sha1=NULL;
	    gchar *filename=NULL;
	    gchar *ptr1, *ptr2;
	    /* skip strings that do not start with "PLCT:" */
	    if (strncmp (buf, SOCKET_PLYC, strlen (SOCKET_PLYC)) != 0)
	    {
		gtkpod_warning (_("Malformed line in '%s': %s\n"), offlplyc, buf);
		goto cont;
	    }
	    /* start of SHA1 string */
	    ptr1 = buf + strlen (SOCKET_PLYC);
	    /* end of SHA1 string */
	    ptr2 = strchr (ptr1, ' ');
	    if (ptr2 == NULL)
	    {   /* error! */
		gtkpod_warning (_("Malformed line in '%s': %s\n"),
				offlplyc, buf_utf8);
		goto cont;
	    }
	    if (ptr1 != ptr2)    sha1 = g_strndup (ptr1, ptr2-ptr1);
	    /* start of filename */
	    ptr1 = ptr2 + 1;
	    /* end of filename string */
	    ptr2 = strchr (ptr1, '\n');
	    if (ptr2 == NULL)
	    {   /* error! */
		gtkpod_warning (_("Malformed line in '%s': %s\n"),
				offlplyc, buf_utf8);
		goto cont;
	    }
	    if (ptr1 != ptr2)
	    {
		filename = g_strndup (ptr1, ptr2-ptr1);
	    }
	    else
	    {   /* error! */
		gtkpod_warning (_("Malformed line in '%s': %s\n"),
				offlplyc, buf_utf8);
		goto cont;
	    }
	    if (gp_increase_playcount (sha1, filename, 1) == FALSE)
	    {   /* didn't find the track -> store */
		gchar *filename_utf8 = charset_to_utf8 (filename);
/* 		if (gstr->len == 0) */
/* 		{ */
/* 		    gtkpod_warning (_("Couldn't find track for playcount adjustment:\n")); */
/* 		} */
		g_string_append (gstr_filenames, filename_utf8);
		g_string_append (gstr_filenames, "\n");
		g_free (filename_utf8);
		g_string_append (gstr, buf);
	    }
	  cont:
	    g_free (buf_utf8);
	    g_free (sha1);
	    g_free (filename);
	}

	/* rewind file pointer to beginning */
	rewind (file);
	if (gstr->len != 0)
	{
	    gint result = gtkpod_confirmation
	    (-1,                    /* gint id, */
	     TRUE,                  /* gboolean modal, */
	     _("Remove offline playcounts?"), /* title */
	     _("Some tracks played offline could not be found in the iTunesDB. Press 'OK' to remove them from the offline playcount file, 'Cancel' to keep them."),   /* label */
	     gstr_filenames->str,   /* scrolled text */
	     NULL, 0, NULL,         /* option 1 */
	     NULL, 0, NULL,         /* option 2 */
	     TRUE,                  /* confirm_again, */
	     NULL,                  /* confirm_again_key,*/
	     CONF_NULL_HANDLER,     /* ConfHandler ok_handler,*/
	     NULL,                  /* don't show "Apply" button */
	     CONF_NULL_HANDLER,     /* cancel_handler,*/
	     NULL,                  /* gpointer user_data1,*/
	     NULL);                 /* gpointer user_data2,*/

	    if (result != GTK_RESPONSE_OK)
	    {
		len = fwrite (gstr->str, sizeof (gchar), gstr->len, file);
		if (len != gstr->len)
		{
		    gtkpod_warning (_("Error writing to '%s'.\n"), offlplyc);
		}
	    }
	}
	ftruncate (fileno (file), len);
	fclose (file);
	g_string_free (gstr, TRUE);
	g_string_free (gstr_filenames, TRUE);
	g_free (buf);
    }
    g_free (cfgdir);
    g_free (offlplyc);
}


/* ------------------------------------------------------------

        Reading of gain tags

   ------------------------------------------------------------ */
/**
 * Read the soundcheck value for @track.
 *
 * Return value: TRUE, if gain could be read
 */
gboolean read_soundcheck (Track *track) 
{
    gchar *path;
    gchar *buf;
    gboolean result = FALSE;

    g_return_val_if_fail (track, FALSE);

    path = get_file_name_from_source (track, SOURCE_PREFER_LOCAL);

    if (path)
    {
	switch (determine_file_type (path))
	{
	case FILE_TYPE_MP3: 
	    result = mp3_read_soundcheck (path, track);
	    break;
	case FILE_TYPE_M4A:
	case FILE_TYPE_M4P:
	case FILE_TYPE_M4B:
	    result = mp4_read_soundcheck (path, track);
	    break;
        case FILE_TYPE_OGG: /* FIXME */
        case FILE_TYPE_FLAC: /* FIXME */
	case FILE_TYPE_WAV: /* FIXME */
	case FILE_TYPE_M4V:
	case FILE_TYPE_MP4:
	case FILE_TYPE_MOV:
	case FILE_TYPE_MPG:
	case FILE_TYPE_UNKNOWN:
	    buf = get_track_info (track, FALSE);
	    gtkpod_warning (
		_("Normalization failed: file type not supported (%s).\n\n"),
		buf);
	    g_free (buf);
	    break;
	case FILE_TYPE_M3U: 
	case FILE_TYPE_PLS: 
	case FILE_TYPE_IMAGE: 
	case FILE_TYPE_DIRECTORY:
	    break;
	}
	g_free (path);
    }
    else
    {
	buf = get_track_info (track, FALSE);
	gtkpod_warning (
	    _("Normalization failed: file not available (%s).\n\n"),
	    buf);
	g_free (buf);
    }
    return result;
}

/* Get lyrics from file */
gboolean read_lyrics_from_file (Track *track, gchar **lyrics)
{
    gchar *path;
    gchar *buf;
    gboolean result = FALSE;
    ExtraTrackData *etr;

    g_return_val_if_fail (track, FALSE);
    etr = track->userdata;
    g_return_val_if_fail (etr,FALSE);
    path = get_file_name_from_source (track, SOURCE_PREFER_IPOD);
    if (path)
    {
        switch (determine_file_type (path))
        {
        case FILE_TYPE_MP3:
            result = id3_lyrics_read (path, lyrics);
            break;
        case FILE_TYPE_M4A:
        case FILE_TYPE_M4P:
        case FILE_TYPE_M4B:
        case FILE_TYPE_M4V:
        case FILE_TYPE_MP4:
            result = TRUE;
            *lyrics=g_strdup(
                "File format unsupported now.");
            break;
        case FILE_TYPE_MOV:
        case FILE_TYPE_MPG:
        case FILE_TYPE_WAV: /* FIXME */
        case FILE_TYPE_OGG: /* FIXME */
        case FILE_TYPE_FLAC: /* FIXME */
        case FILE_TYPE_UNKNOWN:
            result = TRUE;
            *lyrics=g_strdup(
                "Lyrics not supported for this file format.");
            break;
        case FILE_TYPE_M3U:
        case FILE_TYPE_PLS:
        case FILE_TYPE_IMAGE:
        case FILE_TYPE_DIRECTORY:
            break;
        }
        g_free (path);
    }
    else
    {
        buf = get_track_info (track, FALSE);
        gtkpod_warning (
            _("Lyrics not found, file not available (%s).\n\n"),
            buf);
        g_free (buf);
    }
    if (result)
    {
	if (!*lyrics) *lyrics=g_strdup("");
	if (etr->lyrics) g_free(etr->lyrics);
	etr->lyrics=g_strdup(*lyrics);
    }
    return result;
}

/* Write lyrics to file */
gboolean write_lyrics_to_file (Track *track)
{
    gchar *path=NULL;
    gchar *buf;
    Track *oldtrack;
    gboolean result = FALSE;
    gboolean warned = FALSE;
    ExtraTrackData *etr;
    iTunesDB *itdb;

    g_return_val_if_fail (track, FALSE);
    etr = track->userdata;
    g_return_val_if_fail (etr,FALSE);
    itdb = track->itdb;
    g_return_val_if_fail (itdb, FALSE);
    path = get_file_name_from_source (track, SOURCE_IPOD);
    if (!path)
    {
	if (prefs_get_int("id3_write"))
	{
	    path = get_file_name_from_source (track, SOURCE_LOCAL);
	}
	else
	{
	    buf = get_track_info (track, FALSE);
	    gtkpod_warning (
			_("iPod File not available and ID3 saving disabled in options, cannot save lyrics to: %s.\n\n"),
			buf);
	    g_free (buf);
	    warned=TRUE;
	}
    }
    if (path!=NULL)
    {
        switch (determine_file_type (path))
        {
        case FILE_TYPE_MP3:
            result = id3_lyrics_save (path, etr->lyrics);
            break;
        case FILE_TYPE_M4A:
        case FILE_TYPE_M4P:
        case FILE_TYPE_M4B:
        case FILE_TYPE_M4V:
        case FILE_TYPE_MP4:
            result = TRUE;
            break;
        case FILE_TYPE_MOV:
        case FILE_TYPE_MPG:
        case FILE_TYPE_WAV: /* FIXME */
        case FILE_TYPE_OGG: /* FIXME */
        case FILE_TYPE_FLAC: /* FIXME */
        case FILE_TYPE_UNKNOWN:
            result = TRUE;
            break;
        case FILE_TYPE_M3U:
        case FILE_TYPE_PLS:
        case FILE_TYPE_IMAGE:
        case FILE_TYPE_DIRECTORY:
            break;
        }
        g_free (path);
    }
    else
    {
	if (!warned) {
	    buf = get_track_info (track, FALSE);
	    gtkpod_warning (
		_("Lyrics not written, file name not available (%s).\n\n"),
		buf);
	    g_free (buf);
	}
    }

    if (!result || !etr->lyrics || (strlen(etr->lyrics)==0))
    {
	track->lyrics_flag=0x00;
    }
    else
    {
	track->lyrics_flag=0x01;
    }
    if (!etr->lyrics)
    {
	etr->lyrics = g_strdup ("");
    }

    if (result)
    {
	/* remove track from sha1 hash and reinsert it (hash value has changed!) */
	sha1_track_remove (track);
	C_FREE (etr->sha1_hash);  /* need to remove the old value manually! */
	oldtrack = sha1_track_exists_insert (itdb, track);
	if (oldtrack)
	{ /* track exists, remove the old track and register the new version */
	    sha1_track_remove (oldtrack);
	    gp_duplicate_remove (track, oldtrack);
	    sha1_track_exists_insert (itdb, track);
	}
    }
    return result;
}