summaryrefslogtreecommitdiffstats
path: root/apps/playlist.c
blob: 3c9aa1958f94bb2515a6fd38a1205fb47940da48 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
/***************************************************************************
 *             __________               __   ___.
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
 *                     \/            \/     \/    \/            \/
 * $Id$
 *
 * Copyright (C) 2002 by wavey@wavey.org
 *
 * All files in this archive are subject to the GNU General Public License.
 * See the file COPYING in the source tree root for full license agreement.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ****************************************************************************/

/*
    Dynamic playlist design (based on design originally proposed by ricII)

    There are two files associated with a dynamic playlist:
    1. Playlist file : This file contains the initial songs in the playlist.
                       The file is created by the user and stored on the hard
                       drive.  NOTE: If we are playing the contents of a
                       directory, there will be no playlist file.
    2. Control file :  This file is automatically created when a playlist is
                       started and contains all the commands done to it.
    
    The first non-comment line in a control file must begin with
    "P:VERSION:DIR:FILE" where VERSION is the playlist control file version,
    DIR is the directory where the playlist is located and FILE is the
    playlist filename.  For dirplay, FILE will be empty.  An empty playlist
    will have both entries as null.

    Control file commands:
        a. Add track (A:<position>:<last position>:<path to track>)
            - Insert a track at the specified position in the current
              playlist.  Last position is used to specify where last insertion
              occurred.
        b. Queue track (Q:<position>:<last position>:<path to track>)
            - Queue a track at the specified position in the current
              playlist.  Queued tracks differ from added tracks in that they
              are deleted from the playlist as soon as they are played and
              they are not saved to disk as part of the playlist.
        c. Delete track (D:<position>)
            - Delete track from specified position in the current playlist.
        d. Shuffle playlist (S:<seed>:<index>)
            - Shuffle entire playlist with specified seed.  The index
              identifies the first index in the newly shuffled playlist
              (needed for repeat mode).
        e. Unshuffle playlist (U:<index>)
            - Unshuffle entire playlist.  The index identifies the first index
              in the newly unshuffled playlist.
        f. Reset last insert position (R)
            - Needed so that insertions work properly after resume

  Resume:
      The only resume info that needs to be saved is the current index in the
      playlist and the position in the track.  When resuming, all the commands
      in the control file will be reapplied so that the playlist indices are
      exactly the same as before shutdown.  To avoid unnecessary disk
      accesses, the shuffle mode settings are also saved in settings and only
      flushed to disk when required.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "playlist.h"
#include "file.h"
#include "dir.h"
#include "sprintf.h"
#include "debug.h"
#include "audio.h"
#include "lcd.h"
#include "kernel.h"
#include "settings.h"
#include "status.h"
#include "applimits.h"
#include "screens.h"
#include "buffer.h"
#include "atoi.h"
#include "misc.h"
#include "button.h"
#include "filetree.h"
#include "abrepeat.h"
#include "dircache.h"
#include "thread.h"
#include "usb.h"
#ifdef HAVE_LCD_BITMAP
#include "icons.h"
#include "widgets.h"
#endif

#include "lang.h"
#include "talk.h"
#include "splash.h"

#define PLAYLIST_CONTROL_FILE ROCKBOX_DIR "/.playlist_control"
#define PLAYLIST_CONTROL_FILE_VERSION 2

/*
    Each playlist index has a flag associated with it which identifies what
    type of track it is.  These flags are stored in the 4 high order bits of
    the index.
    
    NOTE: This limits the playlist file size to a max of 256M.

    Bits 31-30:
        00 = Playlist track
        01 = Track was prepended into playlist
        10 = Track was inserted into playlist
        11 = Track was appended into playlist
    Bit 29:
        0 = Added track
        1 = Queued track
    Bit 28:
        0 = Track entry is valid
        1 = Track does not exist on disk and should be skipped
 */
#define PLAYLIST_SEEK_MASK              0x0FFFFFFF
#define PLAYLIST_INSERT_TYPE_MASK       0xC0000000
#define PLAYLIST_QUEUE_MASK             0x20000000

#define PLAYLIST_INSERT_TYPE_PREPEND    0x40000000
#define PLAYLIST_INSERT_TYPE_INSERT     0x80000000
#define PLAYLIST_INSERT_TYPE_APPEND     0xC0000000

#define PLAYLIST_QUEUED                 0x20000000
#define PLAYLIST_SKIPPED                0x10000000

#define PLAYLIST_DISPLAY_COUNT          10

static bool changing_dir = false;

static struct playlist_info current_playlist;
static char now_playing[MAX_PATH+1];

static void empty_playlist(struct playlist_info* playlist, bool resume);
static void new_playlist(struct playlist_info* playlist, const char *dir,
                         const char *file);
static void create_control(struct playlist_info* playlist);
static int  check_control(struct playlist_info* playlist);
static int  recreate_control(struct playlist_info* playlist);
static void update_playlist_filename(struct playlist_info* playlist,
                                     const char *dir, const char *file);
static int add_indices_to_playlist(struct playlist_info* playlist,
                                   char* buffer, int buflen);
static int add_track_to_playlist(struct playlist_info* playlist,
                                 const char *filename, int position,
                                 bool queue, int seek_pos);
static int add_directory_to_playlist(struct playlist_info* playlist,
                                     const char *dirname, int *position,
                                     bool queue, int *count, bool recurse);
static int remove_track_from_playlist(struct playlist_info* playlist,
                                      int position, bool write);
static int randomise_playlist(struct playlist_info* playlist,
                              unsigned int seed, bool start_current,
                              bool write);
static int sort_playlist(struct playlist_info* playlist, bool start_current,
                         bool write);
static int get_next_index(const struct playlist_info* playlist, int steps,
                          int repeat_mode);
static void find_and_set_playlist_index(struct playlist_info* playlist,
                                        unsigned int seek);
static int compare(const void* p1, const void* p2);
static int get_filename(struct playlist_info* playlist, int index, int seek,
                        bool control_file, char *buf, int buf_length);
static int get_next_directory(char *dir);
static int get_next_dir(char *dir, bool is_forward, bool recursion);
static int get_previous_directory(char *dir);
static int check_subdir_for_music(char *dir, char *subdir);
static int format_track_path(char *dest, char *src, int buf_length, int max,
                             char *dir);
static void display_playlist_count(int count, const unsigned char *fmt);
static void display_buffer_full(void);
static int flush_cached_control(struct playlist_info* playlist);
static int update_control(struct playlist_info* playlist,
                          enum playlist_command command, int i1, int i2,
                          const char* s1, const char* s2, void* data);
static void sync_control(struct playlist_info* playlist, bool force);
static int rotate_index(const struct playlist_info* playlist, int index);

#ifdef HAVE_DIRCACHE
#define PLAYLIST_LOAD_POINTERS 1

static struct event_queue playlist_queue;
static long playlist_stack[(DEFAULT_STACK_SIZE + 0x400)/sizeof(long)];
static const char playlist_thread_name[] = "playlist cachectrl";
#endif

/*
 * remove any files and indices associated with the playlist
 */
static void empty_playlist(struct playlist_info* playlist, bool resume)
{
    playlist->filename[0] = '\0';

    if(playlist->fd >= 0)
        /* If there is an already open playlist, close it. */
        close(playlist->fd);
    playlist->fd = -1;

    if(playlist->control_fd >= 0)
        close(playlist->control_fd);
    playlist->control_fd = -1;
    playlist->control_created = false;

    playlist->in_ram = false;

    if (playlist->buffer)
        playlist->buffer[0] = 0;

    playlist->buffer_end_pos = 0;

    playlist->index = 0;
    playlist->first_index = 0;
    playlist->amount = 0;
    playlist->last_insert_pos = -1;
    playlist->seed = 0;
    playlist->shuffle_modified = false;
    playlist->deleted = false;
    playlist->num_inserted_tracks = 0;
    playlist->started = false;

    playlist->num_cached = 0;
    playlist->pending_control_sync = false;

    if (!resume && playlist->current)
    {
        /* start with fresh playlist control file when starting new
           playlist */
        create_control(playlist);

        /* Reset resume settings */
        global_settings.resume_first_index = 0;
        global_settings.resume_seed = -1;
    }
}

/*
 * Initialize a new playlist for viewing/editing/playing.  dir is the
 * directory where the playlist is located and file is the filename.
 */
static void new_playlist(struct playlist_info* playlist, const char *dir,
                         const char *file)
{
    empty_playlist(playlist, false);

    if (!file)
    {
        file = "";

        if (dir && playlist->current) /* !current cannot be in_ram */
            playlist->in_ram = true;
        else
            dir = ""; /* empty playlist */
    }
    
    update_playlist_filename(playlist, dir, file);

    if (playlist->control_fd >= 0)
    {
        update_control(playlist, PLAYLIST_COMMAND_PLAYLIST,
            PLAYLIST_CONTROL_FILE_VERSION, -1, dir, file, NULL);
        sync_control(playlist, false);
    }
}

/*
 * create control file for playlist
 */
static void create_control(struct playlist_info* playlist)
{
    playlist->control_fd = open(playlist->control_filename,
                                O_CREAT|O_RDWR|O_TRUNC);
    if (playlist->control_fd < 0)
    {
        if (check_rockboxdir())
        {
            gui_syncsplash(HZ*2, true, (unsigned char *)"%s (%d)",
                           str(LANG_PLAYLIST_CONTROL_ACCESS_ERROR),
                           playlist->control_fd);
        }
        playlist->control_created = false;
    }
    else
    {
        playlist->control_created = true;
    }
}

/*
 * validate the control file.  This may include creating/initializing it if
 * necessary;
 */
static int check_control(struct playlist_info* playlist)
{
    if (!playlist->control_created)
    {
        create_control(playlist);

        if (playlist->control_fd >= 0)
        {
            char* dir = playlist->filename;
            char* file = playlist->filename+playlist->dirlen;
            char c = playlist->filename[playlist->dirlen-1];

            playlist->filename[playlist->dirlen-1] = '\0';

            update_control(playlist, PLAYLIST_COMMAND_PLAYLIST,
                PLAYLIST_CONTROL_FILE_VERSION, -1, dir, file, NULL);
            sync_control(playlist, false);
            playlist->filename[playlist->dirlen-1] = c;
        }
    }

    if (playlist->control_fd < 0)
        return -1;

    return 0;
}

/*
 * recreate the control file based on current playlist entries
 */
static int recreate_control(struct playlist_info* playlist)
{
    char temp_file[MAX_PATH+1];
    int  temp_fd = -1;
    int  i;
    int  result = 0;

    if(playlist->control_fd >= 0)
    {
        char* dir = playlist->filename;
        char* file = playlist->filename+playlist->dirlen;
        char c = playlist->filename[playlist->dirlen-1];

        close(playlist->control_fd);

        snprintf(temp_file, sizeof(temp_file), "%s_temp",
            playlist->control_filename);

        if (rename(playlist->control_filename, temp_file) < 0)
            return -1;

        temp_fd = open(temp_file, O_RDONLY);
        if (temp_fd < 0)
            return -1;

        playlist->control_fd = open(playlist->control_filename,
            O_CREAT|O_RDWR|O_TRUNC);
        if (playlist->control_fd < 0)
            return -1;

        playlist->filename[playlist->dirlen-1] = '\0';
        
        /* cannot call update_control() because of mutex */
        result = fdprintf(playlist->control_fd, "P:%d:%s:%s\n",
            PLAYLIST_CONTROL_FILE_VERSION, dir, file);

        playlist->filename[playlist->dirlen-1] = c;

        if (result < 0)
        {
            close(temp_fd);
            return result;
        }
    }

    playlist->seed = 0;
    playlist->shuffle_modified = false;
    playlist->deleted = false;
    playlist->num_inserted_tracks = 0;

    if (playlist->current)
    {
        global_settings.resume_seed = -1;
        settings_save();
    }

    for (i=0; i<playlist->amount; i++)
    {
        if (playlist->indices[i] & PLAYLIST_INSERT_TYPE_MASK)
        {
            bool queue = playlist->indices[i] & PLAYLIST_QUEUE_MASK;
            char inserted_file[MAX_PATH+1];

            lseek(temp_fd, playlist->indices[i] & PLAYLIST_SEEK_MASK,
                SEEK_SET);
            read_line(temp_fd, inserted_file, sizeof(inserted_file));

            result = fdprintf(playlist->control_fd, "%c:%d:%d:",
                queue?'Q':'A', i, playlist->last_insert_pos);
            if (result > 0)
            {
                /* save the position in file where name is written */
                int seek_pos = lseek(playlist->control_fd, 0, SEEK_CUR);

                result = fdprintf(playlist->control_fd, "%s\n",
                    inserted_file);

                playlist->indices[i] =
                    (playlist->indices[i] & ~PLAYLIST_SEEK_MASK) | seek_pos;
            }

            if (result < 0)
                break;

            playlist->num_inserted_tracks++;
        }
    }

    close(temp_fd);
    remove(temp_file);
    fsync(playlist->control_fd);

    if (result < 0)
        return result;

    return 0;
}

/*
 * store directory and name of playlist file
 */
static void update_playlist_filename(struct playlist_info* playlist,
                                     const char *dir, const char *file)
{
    char *sep="";
    int dirlen = strlen(dir);
    
    /* If the dir does not end in trailing slash, we use a separator.
       Otherwise we don't. */
    if('/' != dir[dirlen-1])
    {
        sep="/";
        dirlen++;
    }

    playlist->dirlen = dirlen;
    
    snprintf(playlist->filename, sizeof(playlist->filename),
        "%s%s%s", dir, sep, file);
}

/*
 * calculate track offsets within a playlist file
 */
static int add_indices_to_playlist(struct playlist_info* playlist,
                                   char* buffer, int buflen)
{
    unsigned int nread;
    unsigned int i = 0;
    unsigned int count = 0;
    bool store_index;
    unsigned char *p;
    int result = 0;

    if(-1 == playlist->fd)
        playlist->fd = open(playlist->filename, O_RDONLY);
    if(playlist->fd < 0)
        return -1; /* failure */
    
#ifdef HAVE_LCD_BITMAP
    if(global_settings.statusbar)
        lcd_setmargins(0, STATUSBAR_HEIGHT);
    else
        lcd_setmargins(0, 0);
#endif

    gui_syncsplash(0, true, str(LANG_PLAYLIST_LOAD));

    if (!buffer)
    {
        /* use mp3 buffer for maximum load speed */
        audio_stop();
        talk_buffer_steal(); /* we use the mp3 buffer, need to tell */

        buffer = (char *)audiobuf;
        buflen = (audiobufend - audiobuf);
    }
    
    store_index = true;

    while(1)
    {
        nread = read(playlist->fd, buffer, buflen);
        /* Terminate on EOF */
        if(nread <= 0)
            break;
        
        p = (unsigned char *)buffer;

        for(count=0; count < nread; count++,p++) {

            /* Are we on a new line? */
            if((*p == '\n') || (*p == '\r'))
            {
                store_index = true;
            }
            else if(store_index)
            {
                store_index = false;

                if(*p != '#')
                {
                    if ( playlist->amount >= playlist->max_playlist_size ) {
                        display_buffer_full();
                        result = -1;
                        goto exit;
                    }

                    /* Store a new entry */
                    playlist->indices[ playlist->amount ] = i+count;
#ifdef HAVE_DIRCACHE
                    if (playlist->filenames)
                        playlist->filenames[ playlist->amount ] = NULL;
#endif
                    playlist->amount++;
                }
            }
        }

        i+= count;
    }

exit:
#ifdef HAVE_DIRCACHE
    queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
#endif

    return result;
}

/*
 * Add track to playlist at specified position.  There are five special
 * positions that can be specified:
 *     PLAYLIST_PREPEND         - Add track at beginning of playlist
 *     PLAYLIST_INSERT          - Add track after current song.  NOTE: If
 *                                there are already inserted tracks then track
 *                                is added to the end of the insertion list
 *     PLAYLIST_INSERT_FIRST    - Add track immediately after current song, no
 *                                matter what other tracks have been inserted
 *     PLAYLIST_INSERT_LAST     - Add track to end of playlist
 *     PLAYLIST_INSERT_SHUFFLED - Add track at some random point between the
 *                                current playing track and end of playlist
 */
static int add_track_to_playlist(struct playlist_info* playlist,
                                 const char *filename, int position,
                                 bool queue, int seek_pos)
{
    int insert_position = position;
    unsigned long flags = PLAYLIST_INSERT_TYPE_INSERT;
    int i;

    if (playlist->amount >= playlist->max_playlist_size)
    {
        display_buffer_full();
        return -1;
    }

    switch (position)
    {
        case PLAYLIST_PREPEND:
            insert_position = playlist->first_index;
            flags = PLAYLIST_INSERT_TYPE_PREPEND;
            break;
        case PLAYLIST_INSERT:
            /* if there are already inserted tracks then add track to end of
               insertion list else add after current playing track */
            if (playlist->last_insert_pos >= 0 &&
                playlist->last_insert_pos < playlist->amount &&
                (playlist->indices[playlist->last_insert_pos]&
                    PLAYLIST_INSERT_TYPE_MASK) == PLAYLIST_INSERT_TYPE_INSERT)
                position = insert_position = playlist->last_insert_pos+1;
            else if (playlist->amount > 0)
                position = insert_position = playlist->index + 1;
            else
                position = insert_position = 0;

            playlist->last_insert_pos = position;
            break;
        case PLAYLIST_INSERT_FIRST:
            if (playlist->amount > 0)
                position = insert_position = playlist->index + 1;
            else
                position = insert_position = 0;

            if (playlist->last_insert_pos < 0)
                playlist->last_insert_pos = position;
            break;
        case PLAYLIST_INSERT_LAST:
            if (playlist->first_index > 0)
                insert_position = playlist->first_index;
            else
                insert_position = playlist->amount;

            flags = PLAYLIST_INSERT_TYPE_APPEND;
            break;
        case PLAYLIST_INSERT_SHUFFLED:
        {
            if (playlist->started)
            {
                int offset;
                int n = playlist->amount -
                    rotate_index(playlist, playlist->index);
                
                if (n > 0)
                    offset = rand() % n;
                else
                    offset = 0;
                
                position = playlist->index + offset + 1;
                if (position >= playlist->amount)
                    position -= playlist->amount;
                
                insert_position = position;
            }
            else
                position = insert_position = (rand() % (playlist->amount+1));
            break;
        }
    }
    
    if (queue)
        flags |= PLAYLIST_QUEUED;

    /* shift indices so that track can be added */
    for (i=playlist->amount; i>insert_position; i--)
    {
        playlist->indices[i] = playlist->indices[i-1];
#ifdef HAVE_DIRCACHE
        if (playlist->filenames)
            playlist->filenames[i] = playlist->filenames[i-1];
#endif
    }
    
    /* update stored indices if needed */
    if (playlist->amount > 0 && insert_position <= playlist->index &&
        playlist->started)
        playlist->index++;

    if (playlist->amount > 0 && insert_position <= playlist->first_index &&
        position != PLAYLIST_PREPEND && playlist->started)
    {
        playlist->first_index++;

        if (seek_pos < 0 && playlist->current)
        {
            global_settings.resume_first_index = playlist->first_index;
            settings_save();
        }
    }

    if (insert_position < playlist->last_insert_pos ||
        (insert_position == playlist->last_insert_pos && position < 0))
        playlist->last_insert_pos++;

    if (seek_pos < 0 && playlist->control_fd >= 0)
    {
        int result = update_control(playlist,
            (queue?PLAYLIST_COMMAND_QUEUE:PLAYLIST_COMMAND_ADD), position,
            playlist->last_insert_pos, filename, NULL, &seek_pos);

        if (result < 0)
            return result;
    }

    playlist->indices[insert_position] = flags | seek_pos;

#ifdef HAVE_DIRCACHE
    if (playlist->filenames)
        playlist->filenames[insert_position] = NULL;
#endif

    playlist->amount++;
    playlist->num_inserted_tracks++;

    return insert_position;
}

/*
 * Insert directory into playlist.  May be called recursively.
 */
static int add_directory_to_playlist(struct playlist_info* playlist,
                                     const char *dirname, int *position,
                                     bool queue, int *count, bool recurse)
{
    char buf[MAX_PATH+1];
    unsigned char *count_str;
    int result = 0;
    int num_files = 0;
    int i;
    struct entry *files;
    struct tree_context* tc = tree_get_context();
    int dirfilter = *(tc->dirfilter);

    /* use the tree browser dircache to load files */
    *(tc->dirfilter) = SHOW_ALL;

    if (ft_load(tc, dirname) < 0)
    {
        gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_DIRECTORY_ACCESS_ERROR));
        *(tc->dirfilter) = dirfilter;
        return -1;
    }

    files = (struct entry*) tc->dircache;
    num_files = tc->filesindir;

    /* we've overwritten the dircache so tree browser will need to be
       reloaded */
    reload_directory();

    if (queue)
        count_str = str(LANG_PLAYLIST_QUEUE_COUNT);
    else
        count_str = str(LANG_PLAYLIST_INSERT_COUNT);

    for (i=0; i<num_files; i++)
    {
        /* user abort */
        if (button_get(false) == SETTINGS_CANCEL)
        {
            result = -1;
            break;
        }

        if (files[i].attr & ATTR_DIRECTORY)
        {
            if (recurse)
            {
                /* recursively add directories */
                snprintf(buf, sizeof(buf), "%s/%s", dirname, files[i].name);
                result = add_directory_to_playlist(playlist, buf, position,
                    queue, count, recurse);
                if (result < 0)
                    break;

                /* we now need to reload our current directory */
                if(ft_load(tc, dirname) < 0)
                {
                    result = -1;
                    break;
                }
                    
                files = (struct entry*) tc->dircache;
                num_files = tc->filesindir;
                if (!num_files)
                {
                    result = -1;
                    break;
                }
            }
            else
                continue;
        }
        else if ((files[i].attr & TREE_ATTR_MASK) == TREE_ATTR_MPA)
        {
            int insert_pos;

            snprintf(buf, sizeof(buf), "%s/%s", dirname, files[i].name);
            
            insert_pos = add_track_to_playlist(playlist, buf, *position,
                queue, -1);
            if (insert_pos < 0)
            {
                result = -1;
                break;
            }

            (*count)++;

            /* Make sure tracks are inserted in correct order if user requests
               INSERT_FIRST */
            if (*position == PLAYLIST_INSERT_FIRST || *position >= 0)
                *position = insert_pos + 1;

            if ((*count%PLAYLIST_DISPLAY_COUNT) == 0)
            {
                display_playlist_count(*count, count_str);

                if (*count == PLAYLIST_DISPLAY_COUNT &&
                    (audio_status() & AUDIO_STATUS_PLAY) &&
                    playlist->started)
                    audio_flush_and_reload_tracks();
            }
            
            /* let the other threads work */
            yield();
        }
    }

    /* restore dirfilter */
    *(tc->dirfilter) = dirfilter;

    return result;
}

/*
 * remove track at specified position
 */
static int remove_track_from_playlist(struct playlist_info* playlist,
                                      int position, bool write)
{
    int i;
    bool inserted;

    if (playlist->amount <= 0)
        return -1;

    inserted = playlist->indices[position] & PLAYLIST_INSERT_TYPE_MASK;

    /* shift indices now that track has been removed */
    for (i=position; i<playlist->amount; i++)
    {
        playlist->indices[i] = playlist->indices[i+1];
#ifdef HAVE_DIRCACHE
        if (playlist->filenames)
            playlist->filenames[i] = playlist->filenames[i+1];
#endif
    }

    playlist->amount--;

    if (inserted)
        playlist->num_inserted_tracks--;
    else
        playlist->deleted = true;

    /* update stored indices if needed */
    if (position < playlist->index)
        playlist->index--;

    if (position < playlist->first_index)
    {
        playlist->first_index--;

        if (write)
        {
            global_settings.resume_first_index = playlist->first_index;
            settings_save();
        }
    }

    if (position <= playlist->last_insert_pos)
        playlist->last_insert_pos--;

    if (write && playlist->control_fd >= 0)
    {
        int result = update_control(playlist, PLAYLIST_COMMAND_DELETE,
            position, -1, NULL, NULL, NULL);

        if (result < 0)
            return result;

        sync_control(playlist, false);
    }

    return 0;
}

/*
 * randomly rearrange the array of indices for the playlist.  If start_current
 * is true then update the index to the new index of the current playing track
 */
static int randomise_playlist(struct playlist_info* playlist,
                              unsigned int seed, bool start_current,
                              bool write)
{
    int count;
    int candidate;
    long store;
    unsigned int current = playlist->indices[playlist->index];
    
    /* seed 0 is used to identify sorted playlist for resume purposes */
    if (seed == 0)
        seed = 1;

    /* seed with the given seed */
    srand(seed);

    /* randomise entire indices list */
    for(count = playlist->amount - 1; count >= 0; count--)
    {
        /* the rand is from 0 to RAND_MAX, so adjust to our value range */
        candidate = rand() % (count + 1);

        /* now swap the values at the 'count' and 'candidate' positions */
        store = playlist->indices[candidate];
        playlist->indices[candidate] = playlist->indices[count];
        playlist->indices[count] = store;
#ifdef HAVE_DIRCACHE
        if (playlist->filenames)
        {
            store = (long)playlist->filenames[candidate];
            playlist->filenames[candidate] = playlist->filenames[count];
            playlist->filenames[count] = (struct dircache_entry *)store;
        }
#endif
    }

    if (start_current)
        find_and_set_playlist_index(playlist, current);

    /* indices have been moved so last insert position is no longer valid */
    playlist->last_insert_pos = -1;

    playlist->seed = seed;
    if (playlist->num_inserted_tracks > 0 || playlist->deleted)
        playlist->shuffle_modified = true;

    if (write)
    {
        update_control(playlist, PLAYLIST_COMMAND_SHUFFLE, seed,
            playlist->first_index, NULL, NULL, NULL);
        global_settings.resume_seed = seed;
        settings_save();
    }

    return 0;
}

/*
 * Sort the array of indices for the playlist. If start_current is true then
 * set the index to the new index of the current song.
 */
static int sort_playlist(struct playlist_info* playlist, bool start_current,
                         bool write)
{
    unsigned int current = playlist->indices[playlist->index];

    if (playlist->amount > 0)
        qsort(playlist->indices, playlist->amount,
            sizeof(playlist->indices[0]), compare);

#ifdef HAVE_DIRCACHE
    /** We need to re-check the song names from disk because qsort can't
     * sort two arrays at once :/
     * FIXME: Please implement a better way to do this. */
    memset(playlist->filenames, 0, playlist->max_playlist_size * sizeof(int));
    queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
#endif

    if (start_current)
        find_and_set_playlist_index(playlist, current);

    /* indices have been moved so last insert position is no longer valid */
    playlist->last_insert_pos = -1;

    if (!playlist->num_inserted_tracks && !playlist->deleted)
        playlist->shuffle_modified = false;
    if (write && playlist->control_fd >= 0)
    {
        update_control(playlist, PLAYLIST_COMMAND_UNSHUFFLE,
            playlist->first_index, -1, NULL, NULL, NULL);
        global_settings.resume_seed = 0;
        settings_save();
    }

    return 0;
}

/* Calculate how many steps we have to really step when skipping entries
 * marked as bad.
 */
static int calculate_step_count(const struct playlist_info *playlist, int steps)
{
    int i, count, direction;
    int index;
    int stepped_count = 0;
    
    if (steps < 0)
    {
        direction = -1;
        count = -steps;
    }
    else
    {
        direction = 1;
        count = steps;
    }

    index = playlist->index;
    i = 0;
    do {
        /* Boundary check */
        if (index < 0)
            index += playlist->amount;
        if (index >= playlist->amount)
            index -= playlist->amount;

        /* Check if we found a bad entry. */
        if (playlist->indices[index] & PLAYLIST_SKIPPED)
        {
            steps += direction;
            /* Are all entries bad? */
            if (stepped_count++ > playlist->amount)
                break ;
        }
        else
            i++;

        index += direction;
    } while (i <= count);

    return steps;
}

/* Marks the index of the track to be skipped that is "steps" away from
 * current playing track.
 */
void playlist_skip_entry(struct playlist_info *playlist, int steps)
{
    int index;

    if (playlist == NULL)
        playlist = &current_playlist;
    
    /* need to account for already skipped tracks */
    steps = calculate_step_count(playlist, steps);

    index = playlist->index + steps;
    if (index < 0)
        index += playlist->amount;
    else if (index >= playlist->amount)
        index -= playlist->amount;

    playlist->indices[index] |= PLAYLIST_SKIPPED;
}

/*
 * returns the index of the track that is "steps" away from current playing
 * track.
 */
static int get_next_index(const struct playlist_info* playlist, int steps,
                          int repeat_mode)
{
    int current_index = playlist->index;
    int next_index    = -1;

    if (playlist->amount <= 0)
        return -1;

    if (repeat_mode == -1)
        repeat_mode = global_settings.repeat_mode;

    if (repeat_mode == REPEAT_SHUFFLE &&
        (!global_settings.playlist_shuffle || playlist->amount <= 1))
        repeat_mode = REPEAT_ALL;

    steps = calculate_step_count(playlist, steps);
    switch (repeat_mode)
    {
        case REPEAT_SHUFFLE:
            /* Treat repeat shuffle just like repeat off.  At end of playlist,
               play will be resumed in playlist_next() */
        case REPEAT_OFF:
        {
            current_index = rotate_index(playlist, current_index);
            next_index = current_index+steps;
            if ((next_index < 0) || (next_index >= playlist->amount))
                next_index = -1;
            else
                next_index = (next_index+playlist->first_index) %
                    playlist->amount;

            break;
        }

        case REPEAT_ONE:
#if (AB_REPEAT_ENABLE == 1)
        case REPEAT_AB:
#endif
            next_index = current_index;
            break;

        case REPEAT_ALL:
        default:
        {
            next_index = (current_index+steps) % playlist->amount;
            while (next_index < 0)
                next_index += playlist->amount;

            if (steps >= playlist->amount)
            {
                int i, index;

                index = next_index;
                next_index = -1;

                /* second time around so skip the queued files */
                for (i=0; i<playlist->amount; i++)
                {
                    if (playlist->indices[index] & PLAYLIST_QUEUE_MASK)
                        index = (index+1) % playlist->amount;
                    else
                    {
                        next_index = index;
                        break;
                    }
                }
            }
            break;
        }
    }

    /* No luck if the whole playlist was bad. */
    if (playlist->indices[next_index] & PLAYLIST_SKIPPED)
        return -1;
    
    return next_index;
}

/*
 * Search for the seek track and set appropriate indices.  Used after shuffle
 * to make sure the current index is still pointing to correct track.
 */
static void find_and_set_playlist_index(struct playlist_info* playlist,
                                        unsigned int seek)
{
    int i;
    
    /* Set the index to the current song */
    for (i=0; i<playlist->amount; i++)
    {
        if (playlist->indices[i] == seek)
        {
            playlist->index = playlist->first_index = i;

            if (playlist->current)
            {
                global_settings.resume_first_index = i;
                settings_save();
            }

            break;
        }
    }
}

/*
 * used to sort track indices.  Sort order is as follows:
 * 1. Prepended tracks (in prepend order)
 * 2. Playlist/directory tracks (in playlist order)
 * 3. Inserted/Appended tracks (in insert order)
 */
static int compare(const void* p1, const void* p2)
{
    unsigned long* e1 = (unsigned long*) p1;
    unsigned long* e2 = (unsigned long*) p2;
    unsigned long flags1 = *e1 & PLAYLIST_INSERT_TYPE_MASK;
    unsigned long flags2 = *e2 & PLAYLIST_INSERT_TYPE_MASK;

    if (flags1 == flags2)
        return (*e1 & PLAYLIST_SEEK_MASK) - (*e2 & PLAYLIST_SEEK_MASK);
    else if (flags1 == PLAYLIST_INSERT_TYPE_PREPEND ||
        flags2 == PLAYLIST_INSERT_TYPE_APPEND)
        return -1;
    else if (flags1 == PLAYLIST_INSERT_TYPE_APPEND ||
        flags2 == PLAYLIST_INSERT_TYPE_PREPEND)
        return 1;
    else if (flags1 && flags2)
        return (*e1 & PLAYLIST_SEEK_MASK) - (*e2 & PLAYLIST_SEEK_MASK);
    else
        return *e1 - *e2;
}

#ifdef HAVE_DIRCACHE
/**
 * Thread to update filename pointers to dircache on background
 * without affecting playlist load up performance.  This thread also flushes
 * any pending control commands when the disk spins up.
 */
static void playlist_thread(void)
{
    struct event ev;
    bool dirty_pointers = false;
    static char tmp[MAX_PATH+1];

    struct playlist_info *playlist;
    int index;
    int seek;
    bool control_file;

    int sleep_time = 5;

    if (global_settings.disk_spindown > 1 &&
        global_settings.disk_spindown <= 5)
        sleep_time = global_settings.disk_spindown - 1;

    while (1)
    {
        queue_wait_w_tmo(&playlist_queue, &ev, HZ*sleep_time);

        switch (ev.id)
        {
            case PLAYLIST_LOAD_POINTERS:
                dirty_pointers = true;
                break ;

            /* Start the background scanning after either the disk spindown
               timeout or 5s, whichever is less */
            case SYS_TIMEOUT:
                playlist = &current_playlist;

                if (playlist->control_fd >= 0
# ifndef SIMULATOR
                    && ata_disk_is_active()
# endif
                    )
                {
                    if (playlist->num_cached > 0)
                    {
                        mutex_lock(&playlist->control_mutex);
                        flush_cached_control(playlist);
                        mutex_unlock(&playlist->control_mutex);
                    }

                    sync_control(playlist, true);
                }

                if (!dirty_pointers)
                    break ;

                if (!dircache_is_enabled() || !playlist->filenames
                     || playlist->amount <= 0)
                    break ;

#ifdef HAVE_ADJUSTABLE_CPU_FREQ
                cpu_boost(true);
#endif
                for (index = 0; index < playlist->amount
                     && queue_empty(&playlist_queue); index++)
                {
                    /* Process only pointers that are not already loaded. */
                    if (playlist->filenames[index])
                        continue ;
                    
                    control_file = playlist->indices[index] & PLAYLIST_INSERT_TYPE_MASK;
                    seek = playlist->indices[index] & PLAYLIST_SEEK_MASK;

                    /* Load the filename from playlist file. */
                    if (get_filename(playlist, index, seek, control_file, tmp,
                        sizeof(tmp)) < 0)
                        break ;

                    /* Set the dircache entry pointer. */
                    playlist->filenames[index] = dircache_get_entry_ptr(tmp);

                    /* And be on background so user doesn't notice any delays. */
                    yield();
                }

#ifdef HAVE_ADJUSTABLE_CPU_FREQ
                cpu_boost(false);
#endif
                dirty_pointers = false;
                break ;
            
#ifndef SIMULATOR
            case SYS_USB_CONNECTED:
                usb_acknowledge(SYS_USB_CONNECTED_ACK);
                usb_wait_for_disconnect(&playlist_queue);
                break ;
#endif
        }
    }
}
#endif

/*
 * gets pathname for track at seek index
 */
static int get_filename(struct playlist_info* playlist, int index, int seek,
                        bool control_file, char *buf, int buf_length)
{
    int fd;
    int max = -1;
    char tmp_buf[MAX_PATH+1];
    char dir_buf[MAX_PATH+1];

    if (buf_length > MAX_PATH+1)
        buf_length = MAX_PATH+1;

#ifdef HAVE_DIRCACHE
    if (dircache_is_enabled() && playlist->filenames)
    {
        if (playlist->filenames[index] != NULL)
        {
            dircache_copy_path(playlist->filenames[index], tmp_buf, sizeof(tmp_buf)-1);
            max = strlen(tmp_buf) + 1;
        }
    }
#else
    (void)index;
#endif
    
    if (playlist->in_ram && !control_file && max < 0)
    {
        strncpy(tmp_buf, &playlist->buffer[seek], sizeof(tmp_buf));
        tmp_buf[MAX_PATH] = '\0';
        max = strlen(tmp_buf) + 1;
    }
    else if (max < 0)
    {
        mutex_lock(&playlist->control_mutex);

        if (control_file)
            fd = playlist->control_fd;
        else
        {
            if(-1 == playlist->fd)
                playlist->fd = open(playlist->filename, O_RDONLY);
            
            fd = playlist->fd;
        }
        
        if(-1 != fd)
        {
            
            if (lseek(fd, seek, SEEK_SET) != seek)
                max = -1;
            else
                max = read(fd, tmp_buf, buf_length);
        }

        mutex_unlock(&playlist->control_mutex);

        if (max < 0)
        {
            if (control_file)
                gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
            else
                gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_ACCESS_ERROR));

            return max;
        }
    }

    strncpy(dir_buf, playlist->filename, playlist->dirlen-1);
    dir_buf[playlist->dirlen-1] = 0;

    return (format_track_path(buf, tmp_buf, buf_length, max, dir_buf));
}

static int get_next_directory(char *dir){
  return get_next_dir(dir,true,false);
}

static int get_previous_directory(char *dir){
  return get_next_dir(dir,false,false);
}

/*
 * search through all the directories (starting with the current) to find
 * one that has tracks to play
 */
static int get_next_dir(char *dir, bool is_forward, bool recursion)
{
    struct playlist_info* playlist = &current_playlist;
    int result = -1;
    int sort_dir = global_settings.sort_dir;
    char *start_dir = NULL;
    bool exit = false;
    struct tree_context* tc = tree_get_context();
    int dirfilter = *(tc->dirfilter);

    if (recursion){
       /* start with root */
       dir[0] = '\0';
    }
    else{
        /* start with current directory */
        strncpy(dir, playlist->filename, playlist->dirlen-1);
        dir[playlist->dirlen-1] = '\0';
    }

    /* use the tree browser dircache to load files */
    *(tc->dirfilter) = SHOW_ALL;

    /* sort in another direction if previous dir is requested */
    if(!is_forward){
       if ((global_settings.sort_dir == 0) || (global_settings.sort_dir == 3))
           global_settings.sort_dir = 4;
       else if (global_settings.sort_dir == 1)
           global_settings.sort_dir = 2;
       else if (global_settings.sort_dir == 2)
           global_settings.sort_dir = 1;
       else if (global_settings.sort_dir == 4)
           global_settings.sort_dir = 0;
    }

    while (!exit)
    {
        struct entry *files;
        int num_files = 0;
        int i;

        if (ft_load(tc, (dir[0]=='\0')?"/":dir) < 0)
        {
            gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_DIRECTORY_ACCESS_ERROR));
            exit = true;
            result = -1;
            break;
        }
        
        files = (struct entry*) tc->dircache;
        num_files = tc->filesindir;

        for (i=0; i<num_files; i++)
        {
            /* user abort */
            if (button_get(false) == SETTINGS_CANCEL)
            {
                result = -1;
                exit = true;
                break;
            }
            
            if (files[i].attr & ATTR_DIRECTORY)
            {
                if (!start_dir)
                {
                    result = check_subdir_for_music(dir, files[i].name);
                    if (result != -1)
                    {
                        exit = true;
                        break;
                    }
                }
                else if (!strcmp(start_dir, files[i].name))
                    start_dir = NULL;
            }
        }

        if (!exit)
        {
            /* move down to parent directory.  current directory name is
               stored as the starting point for the search in parent */
            start_dir = strrchr(dir, '/');
            if (start_dir)
            {
                *start_dir = '\0';
                start_dir++;
            }
            else
                break;
        }
    }

    /* we've overwritten the dircache so tree browser will need to be
       reloaded */
    reload_directory();

    /* restore dirfilter & sort_dir */
    *(tc->dirfilter) = dirfilter;
    global_settings.sort_dir = sort_dir;

    /* special case if nothing found: try start searching again from root */
    if (result == -1 && !recursion){
        result = get_next_dir(dir,is_forward, true);
    }

    return result;
}

/*
 * Checks if there are any music files in the dir or any of its
 * subdirectories.  May be called recursively.
 */
static int check_subdir_for_music(char *dir, char *subdir)
{
    int result = -1;
    int dirlen = strlen(dir);
    int num_files = 0;
    int i;
    struct entry *files;
    bool has_music = false;
    bool has_subdir = false;
    struct tree_context* tc = tree_get_context();

    snprintf(dir+dirlen, MAX_PATH-dirlen, "/%s", subdir);
    
    if (ft_load(tc, dir) < 0)
    {
        gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_DIRECTORY_ACCESS_ERROR));
        return -2;
    }
    
    files = (struct entry*) tc->dircache;
    num_files = tc->filesindir;
    
    for (i=0; i<num_files; i++)
    {
        if (files[i].attr & ATTR_DIRECTORY)
            has_subdir = true;
        else if ((files[i].attr & TREE_ATTR_MASK) == TREE_ATTR_MPA)
        {
            has_music = true;
            break;
        }
    }

    if (has_music)
        return 0;

    if (has_subdir)
    {
        for (i=0; i<num_files; i++)
        {
            if (button_get(false) == SETTINGS_CANCEL)
            {
                result = -2;
                break;
            }

            if (files[i].attr & ATTR_DIRECTORY)
            {
                result = check_subdir_for_music(dir, files[i].name);
                if (!result)
                    break;
            }
        }
    }

    if (result < 0)
    {
        if (dirlen)
        {
            dir[dirlen] = '\0';
        }
        else
        {
            strcpy(dir, "/");
        }

        /* we now need to reload our current directory */
        if(ft_load(tc, dir) < 0)
            gui_syncsplash(HZ*2, true,
                str(LANG_PLAYLIST_DIRECTORY_ACCESS_ERROR));        
    }

    return result;
}

/*
 * Returns absolute path of track
 */
static int format_track_path(char *dest, char *src, int buf_length, int max,
                             char *dir)
{
    int i = 0;
    int j;
    char *temp_ptr;

    /* Zero-terminate the file name */
    while((src[i] != '\n') &&
          (src[i] != '\r') &&
          (i < max))
        i++;

    /* Now work back killing white space */
    while((src[i-1] == ' ') ||
          (src[i-1] == '\t'))
        i--;

    src[i]=0;
      
    /* replace backslashes with forward slashes */
    for ( j=0; j<i; j++ )
        if ( src[j] == '\\' )
            src[j] = '/';

    if('/' == src[0])
    {
        strncpy(dest, src, buf_length);
    }
    else
    {
        /* handle dos style drive letter */
        if (':' == src[1])
            strncpy(dest, &src[2], buf_length);
        else if (!strncmp(src, "../", 3))
        {
            /* handle relative paths */
            i=3;
            while(!strncmp(&src[i], "../", 3))
                i += 3;
            for (j=0; j<i/3; j++) {
                temp_ptr = strrchr(dir, '/');
                if (temp_ptr)
                    *temp_ptr = '\0';
                else
                    break;
            }
            snprintf(dest, buf_length, "%s/%s", dir, &src[i]);
        }
        else if ( '.' == src[0] && '/' == src[1] ) {
            snprintf(dest, buf_length, "%s/%s", dir, &src[2]);
        }
        else {
            snprintf(dest, buf_length, "%s/%s", dir, src);
        }
    }

    return 0;
}

/*
 * Display splash message showing progress of playlist/directory insertion or
 * save.
 */
static void display_playlist_count(int count, const unsigned char *fmt)
{
    lcd_clear_display();

#ifdef HAVE_LCD_BITMAP
    if(global_settings.statusbar)
        lcd_setmargins(0, STATUSBAR_HEIGHT);
    else
        lcd_setmargins(0, 0);
#endif

    gui_syncsplash(0, true, fmt, count,
#if CONFIG_KEYPAD == PLAYER_PAD
                   str(LANG_STOP_ABORT)
#else
                   str(LANG_OFF_ABORT)
#endif
        );
}

/*
 * Display buffer full message
 */
static void display_buffer_full(void)
{
    gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_BUFFER_FULL));
}

/*
 * Flush any cached control commands to disk.  Called when playlist is being
 * modified.  Returns 0 on success and -1 on failure.
 */
static int flush_cached_control(struct playlist_info* playlist)
{
    int result = 0;
    int i;

    if (!playlist->num_cached)
        return 0;

    lseek(playlist->control_fd, 0, SEEK_END);

    for (i=0; i<playlist->num_cached; i++)
    {
        struct playlist_control_cache* cache =
            &(playlist->control_cache[i]);

        switch (cache->command)
        {
            case PLAYLIST_COMMAND_PLAYLIST:
                result = fdprintf(playlist->control_fd, "P:%d:%s:%s\n",
                    cache->i1, cache->s1, cache->s2);
                break;
            case PLAYLIST_COMMAND_ADD:
            case PLAYLIST_COMMAND_QUEUE:
                result = fdprintf(playlist->control_fd, "%c:%d:%d:",
                    (cache->command == PLAYLIST_COMMAND_ADD)?'A':'Q',
                    cache->i1, cache->i2);
                if (result > 0)
                {
                    /* save the position in file where name is written */
                    int* seek_pos = (int *)cache->data;
                    *seek_pos = lseek(playlist->control_fd, 0, SEEK_CUR);
                    result = fdprintf(playlist->control_fd, "%s\n",
                        cache->s1);
                }
                break;
            case PLAYLIST_COMMAND_DELETE:
                result = fdprintf(playlist->control_fd, "D:%d\n", cache->i1);
                break;
            case PLAYLIST_COMMAND_SHUFFLE:
                result = fdprintf(playlist->control_fd, "S:%d:%d\n",
                    cache->i1, cache->i2);
                break;
            case PLAYLIST_COMMAND_UNSHUFFLE:
                result = fdprintf(playlist->control_fd, "U:%d\n", cache->i1);
                break;
            case PLAYLIST_COMMAND_RESET:
                result = fdprintf(playlist->control_fd, "R\n");
                break;
            default:
                break;
        }

        if (result <= 0)
            break;
    }

    if (result > 0)
    {
        if (global_settings.resume_seed >= 0)
        {
            global_settings.resume_seed = -1;
            settings_save();
        }

        playlist->num_cached = 0;
        playlist->pending_control_sync = true;

        result = 0;
    }
    else
    {
        result = -1;
        gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_CONTROL_UPDATE_ERROR));
    }

    return result;
}

/*
 * Update control data with new command.  Depending on the command, it may be
 * cached or flushed to disk.
 */
static int update_control(struct playlist_info* playlist,
                          enum playlist_command command, int i1, int i2,
                          const char* s1, const char* s2, void* data)
{
    int result = 0;
    struct playlist_control_cache* cache;
    bool flush = false;

    mutex_lock(&playlist->control_mutex);

    cache = &(playlist->control_cache[playlist->num_cached++]);

    cache->command = command;
    cache->i1 = i1;
    cache->i2 = i2;
    cache->s1 = s1;
    cache->s2 = s2;
    cache->data = data;

    switch (command)
    {
        case PLAYLIST_COMMAND_PLAYLIST:
        case PLAYLIST_COMMAND_ADD:
        case PLAYLIST_COMMAND_QUEUE:
#ifndef HAVE_DIRCACHE
        case PLAYLIST_COMMAND_DELETE:
        case PLAYLIST_COMMAND_RESET:
#endif
            flush = true;
            break;
        case PLAYLIST_COMMAND_SHUFFLE:
        case PLAYLIST_COMMAND_UNSHUFFLE:
        default:
            /* only flush when needed */
            break;
    }

    if (flush || playlist->num_cached == PLAYLIST_MAX_CACHE)
        result = flush_cached_control(playlist);

    mutex_unlock(&playlist->control_mutex);
        
    return result;
}

/*
 * sync control file to disk
 */
static void sync_control(struct playlist_info* playlist, bool force)
{
#ifdef HAVE_DIRCACHE
    if (playlist->started && force)
#else
    (void) force;

    if (playlist->started)
#endif
    {
        if (playlist->pending_control_sync)
        {
            mutex_lock(&playlist->control_mutex);
            fsync(playlist->control_fd);
            playlist->pending_control_sync = false;
            mutex_unlock(&playlist->control_mutex);
        }
    }
}

/*
 * Rotate indices such that first_index is index 0
 */
static int rotate_index(const struct playlist_info* playlist, int index)
{
    index -= playlist->first_index;
    if (index < 0)
        index += playlist->amount;

    return index;
}

/*
 * Initialize playlist entries at startup
 */
void playlist_init(void)
{
    struct playlist_info* playlist = &current_playlist;

    playlist->current = true;
    snprintf(playlist->control_filename, sizeof(playlist->control_filename),
        "%s", PLAYLIST_CONTROL_FILE);
    playlist->fd = -1;
    playlist->control_fd = -1;
    playlist->max_playlist_size = global_settings.max_files_in_playlist;
    playlist->indices = buffer_alloc(
        playlist->max_playlist_size * sizeof(int));
    playlist->buffer_size =
        AVERAGE_FILENAME_LENGTH * global_settings.max_files_in_dir;
    playlist->buffer = buffer_alloc(playlist->buffer_size);
    mutex_init(&playlist->control_mutex);
    empty_playlist(playlist, true);

#ifdef HAVE_DIRCACHE
    playlist->filenames = buffer_alloc(
        playlist->max_playlist_size * sizeof(int));
    memset(playlist->filenames, 0,
           playlist->max_playlist_size * sizeof(int));
    create_thread(playlist_thread, playlist_stack, sizeof(playlist_stack),
                  playlist_thread_name);
    queue_init(&playlist_queue);
#endif
}

/*
 * Clean playlist at shutdown
 */
void playlist_shutdown(void)
{
    struct playlist_info* playlist = &current_playlist;

    if (playlist->control_fd >= 0)
    {
        mutex_lock(&playlist->control_mutex);

        if (playlist->num_cached > 0)
            flush_cached_control(playlist);

        close(playlist->control_fd);

        mutex_unlock(&playlist->control_mutex);
    }
}

/*
 * Create new playlist
 */
int playlist_create(const char *dir, const char *file)
{
    struct playlist_info* playlist = &current_playlist;

    new_playlist(playlist, dir, file);

    if (file)
        /* load the playlist file */
        add_indices_to_playlist(playlist, NULL, 0);

    return 0;
}

#define PLAYLIST_COMMAND_SIZE (MAX_PATH+12)

/*
 * Restore the playlist state based on control file commands.  Called to
 * resume playback after shutdown.
 */
int playlist_resume(void)
{
    struct playlist_info* playlist = &current_playlist;
    char *buffer;
    int buflen;
    int nread;
    int total_read = 0;
    int control_file_size = 0;
    bool first = true;
    bool sorted = true;

    /* use mp3 buffer for maximum load speed */
#if CONFIG_CODEC != SWCODEC
    talk_buffer_steal(); /* we use the mp3 buffer, need to tell */
    buflen = (audiobufend - audiobuf);
    buffer = (char *)audiobuf;
#else
    buflen = (audiobufend - audiobuf - talk_get_bufsize());
    buffer = (char *)&audiobuf[talk_get_bufsize()];
#endif

    empty_playlist(playlist, true);

    gui_syncsplash(0, true, str(LANG_WAIT));
    playlist->control_fd = open(playlist->control_filename, O_RDWR);
    if (playlist->control_fd < 0)
    {
        gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
        return -1;
    }
    playlist->control_created = true;

    control_file_size = filesize(playlist->control_fd);
    if (control_file_size <= 0)
    {
        gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
        return -1;
    }

    /* read a small amount first to get the header */
    nread = read(playlist->control_fd, buffer,
        PLAYLIST_COMMAND_SIZE<buflen?PLAYLIST_COMMAND_SIZE:buflen);
    if(nread <= 0)
    {
        gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
        return -1;
    }

    playlist->started = true;

    while (1)
    {
        int result = 0;
        int count;
        enum playlist_command current_command = PLAYLIST_COMMAND_COMMENT;
        int last_newline = 0;
        int str_count = -1;
        bool newline = true;
        bool exit_loop = false;
        char *p = buffer;
        char *str1 = NULL;
        char *str2 = NULL;
        char *str3 = NULL;

        for(count=0; count<nread && !exit_loop; count++,p++)
        {
            /* Are we on a new line? */
            if((*p == '\n') || (*p == '\r'))
            {
                *p = '\0';

                /* save last_newline in case we need to load more data */
                last_newline = count;

                switch (current_command)
                {
                    case PLAYLIST_COMMAND_PLAYLIST:
                    {
                        /* str1=version str2=dir str3=file */
                        int version;

                        if (!str1)
                        {
                            result = -1;
                            exit_loop = true;
                            break;
                        }
                        
                        if (!str2)
                            str2 = "";
                        
                        if (!str3)
                            str3 = "";
                        
                        version = atoi(str1);
                        
                        if (version != PLAYLIST_CONTROL_FILE_VERSION)
                            return -1;
                        
                        update_playlist_filename(playlist, str2, str3);
                        
                        if (str3[0] != '\0')
                        {
                            /* NOTE: add_indices_to_playlist() overwrites the
                               audiobuf so we need to reload control file
                               data */
                            add_indices_to_playlist(playlist, NULL, 0);
                        }
                        else if (str2[0] != '\0')
                        {
                            playlist->in_ram = true;
                            resume_directory(str2);
                        }
                        
                        /* load the rest of the data */
                        first = false;
                        exit_loop = true;

                        break;
                    }
                    case PLAYLIST_COMMAND_ADD:
                    case PLAYLIST_COMMAND_QUEUE:
                    {
                        /* str1=position str2=last_position str3=file */
                        int position, last_position;
                        bool queue;
                        
                        if (!str1 || !str2 || !str3)
                        {
                            result = -1;
                            exit_loop = true;
                            break;
                        }
                        
                        position = atoi(str1);
                        last_position = atoi(str2);
                        
                        queue = (current_command == PLAYLIST_COMMAND_ADD)?
                            false:true;

                        /* seek position is based on str3's position in
                           buffer */
                        if (add_track_to_playlist(playlist, str3, position,
                                queue, total_read+(str3-buffer)) < 0)
                        return -1;
                        
                        playlist->last_insert_pos = last_position;

                        break;
                    }
                    case PLAYLIST_COMMAND_DELETE:
                    {
                        /* str1=position */
                        int position;
                        
                        if (!str1)
                        {
                            result = -1;
                            exit_loop = true;
                            break;
                        }
                        
                        position = atoi(str1);
                        
                        if (remove_track_from_playlist(playlist, position,
                                false) < 0)
                            return -1;

                        break;
                    }
                    case PLAYLIST_COMMAND_SHUFFLE:
                    {
                        /* str1=seed str2=first_index */
                        int seed;
                        
                        if (!str1 || !str2)
                        {
                            result = -1;
                            exit_loop = true;
                            break;
                        }
                        
                        if (!sorted)
                        {
                            /* Always sort list before shuffling */
                            sort_playlist(playlist, false, false);
                        }

                        seed = atoi(str1);
                        playlist->first_index = atoi(str2);
                        
                        if (randomise_playlist(playlist, seed, false,
                                false) < 0)
                            return -1;

                        sorted = false;
                        break;
                    }
                    case PLAYLIST_COMMAND_UNSHUFFLE:
                    {
                        /* str1=first_index */
                        if (!str1)
                        {
                            result = -1;
                            exit_loop = true;
                            break;
                        }
                        
                        playlist->first_index = atoi(str1);
                        
                        if (sort_playlist(playlist, false, false) < 0)
                            return -1;

                        sorted = true;
                        break;
                    }
                    case PLAYLIST_COMMAND_RESET:
                    {
                        playlist->last_insert_pos = -1;
                        break;
                    }
                    case PLAYLIST_COMMAND_COMMENT:
                    default:
                        break;
                }

                newline = true;

                /* to ignore any extra newlines */
                current_command = PLAYLIST_COMMAND_COMMENT;
            }
            else if(newline)
            {
                newline = false;

                /* first non-comment line must always specify playlist */
                if (first && *p != 'P' && *p != '#')
                {
                    result = -1;
                    exit_loop = true;
                    break;
                }

                switch (*p)
                {
                    case 'P':
                        /* playlist can only be specified once */
                        if (!first)
                        {
                            result = -1;
                            exit_loop = true;
                            break;
                        }

                        current_command = PLAYLIST_COMMAND_PLAYLIST;
                        break;
                    case 'A':
                        current_command = PLAYLIST_COMMAND_ADD;
                        break;
                    case 'Q':
                        current_command = PLAYLIST_COMMAND_QUEUE;
                        break;
                    case 'D':
                        current_command = PLAYLIST_COMMAND_DELETE;
                        break;
                    case 'S':
                        current_command = PLAYLIST_COMMAND_SHUFFLE;
                        break;
                    case 'U':
                        current_command = PLAYLIST_COMMAND_UNSHUFFLE;
                        break;
                    case 'R':
                        current_command = PLAYLIST_COMMAND_RESET;
                        break;
                    case '#':
                        current_command = PLAYLIST_COMMAND_COMMENT;
                        break;
                    default:
                        result = -1;
                        exit_loop = true;
                        break;
                }

                str_count = -1;
                str1 = NULL;
                str2 = NULL;
                str3 = NULL;
            }
            else if(current_command != PLAYLIST_COMMAND_COMMENT)
            {
                /* all control file strings are separated with a colon.
                   Replace the colon with 0 to get proper strings that can be
                   used by commands above */
                if (*p == ':')
                {
                    *p = '\0';
                    str_count++;

                    if ((count+1) < nread)
                    {
                        switch (str_count)
                        {
                        case 0:
                            str1 = p+1;
                            break;
                        case 1:
                            str2 = p+1;
                            break;
                        case 2:
                            str3 = p+1;
                            break;
                        default:
                            /* allow last string to contain colons */
                            *p = ':';
                            break;
                        }
                    }
                }
            }
        }

        if (result < 0)
        {
            gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_CONTROL_INVALID));
            return result;
        }

        if (!newline || (exit_loop && count<nread))
        {
            if ((total_read + count) >= control_file_size)
            {
                /* no newline at end of control file */
                gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_CONTROL_INVALID));
                return -1;
            }

            /* We didn't end on a newline or we exited loop prematurely.
               Either way, re-read the remainder. */
            count = last_newline;
            lseek(playlist->control_fd, total_read+count, SEEK_SET);
        }

        total_read += count;

        if (first)
            /* still looking for header */
            nread = read(playlist->control_fd, buffer,
                PLAYLIST_COMMAND_SIZE<buflen?PLAYLIST_COMMAND_SIZE:buflen);
        else
            nread = read(playlist->control_fd, buffer, buflen);

        /* Terminate on EOF */
        if(nread <= 0)
        {
            if (global_settings.resume_seed >= 0)
            {
                /* Apply shuffle command saved in settings */
                if (global_settings.resume_seed == 0)
                    sort_playlist(playlist, false, true);
                else
                {
                    if (!sorted)
                        sort_playlist(playlist, false, false);

                    randomise_playlist(playlist, global_settings.resume_seed,
                        false, true);
                }

                playlist->first_index = global_settings.resume_first_index;
            }

            break;
        }
    }

#ifdef HAVE_DIRCACHE
    queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
#endif

    return 0;
}

/*
 * Add track to in_ram playlist.  Used when playing directories.
 */
int playlist_add(const char *filename)
{
    struct playlist_info* playlist = &current_playlist;
    int len = strlen(filename);
    
    if((len+1 > playlist->buffer_size - playlist->buffer_end_pos) ||
       (playlist->amount >= playlist->max_playlist_size))
    {
        display_buffer_full();
        return -1;
    }

    playlist->indices[playlist->amount] = playlist->buffer_end_pos;
#ifdef HAVE_DIRCACHE
    playlist->filenames[playlist->amount] = NULL;
#endif
    playlist->amount++;
    
    strcpy(&playlist->buffer[playlist->buffer_end_pos], filename);
    playlist->buffer_end_pos += len;
    playlist->buffer[playlist->buffer_end_pos++] = '\0';

    return 0;
}

/* shuffle newly created playlist using random seed. */
int playlist_shuffle(int random_seed, int start_index)
{
    struct playlist_info* playlist = &current_playlist;

    unsigned int seek_pos = 0;
    bool start_current = false;

    if (start_index >= 0 && global_settings.play_selected)
    {
        /* store the seek position before the shuffle */
        seek_pos = playlist->indices[start_index];
        playlist->index = global_settings.resume_first_index =
            playlist->first_index = start_index;
        start_current = true;
    }

    gui_syncsplash(0, true, str(LANG_PLAYLIST_SHUFFLE));
    
    randomise_playlist(playlist, random_seed, start_current, true);

    return playlist->index;
}

/* start playing current playlist at specified index/offset */
int playlist_start(int start_index, int offset)
{
    struct playlist_info* playlist = &current_playlist;

    playlist->index = start_index;

#if CONFIG_CODEC != SWCODEC
    talk_buffer_steal(); /* will use the mp3 buffer */
#endif

    playlist->started = true;
    sync_control(playlist, false);
    audio_play(offset);

    return 0;
}

/* Returns false if 'steps' is out of bounds, else true */
bool playlist_check(int steps)
{
    struct playlist_info* playlist = &current_playlist;

    /* always allow folder navigation */
    if (global_settings.next_folder && playlist->in_ram)
        return true;

    int index = get_next_index(playlist, steps, -1);

    if (index < 0 && steps >= 0 && global_settings.repeat_mode == REPEAT_SHUFFLE)
        index = get_next_index(playlist, steps, REPEAT_ALL);

    return (index >= 0);
}

/* get trackname of track that is "steps" away from current playing track.
   NULL is used to identify end of playlist */
char* playlist_peek(int steps)
{
    struct playlist_info* playlist = &current_playlist;
    int seek;
    int fd;
    char *temp_ptr;
    int index;
    bool control_file;

    index = get_next_index(playlist, steps, -1);
    if (index < 0)
        return NULL;

    control_file = playlist->indices[index] & PLAYLIST_INSERT_TYPE_MASK;
    seek = playlist->indices[index] & PLAYLIST_SEEK_MASK;

    if (get_filename(playlist, index, seek, control_file, now_playing,
            MAX_PATH+1) < 0)
        return NULL;

    temp_ptr = now_playing;

    if (!playlist->in_ram || control_file)
    {
        /* remove bogus dirs from beginning of path
           (workaround for buggy playlist creation tools) */
        while (temp_ptr)
        {
#ifdef HAVE_DIRCACHE
            if (dircache_is_enabled())
            {
                if (dircache_get_entry_ptr(temp_ptr))
                    break;
            }
            else
#endif
            {
                fd = open(temp_ptr, O_RDONLY);
                if (fd >= 0)
                {
                    close(fd);
                    break;
                }
            }
            
            temp_ptr = strchr(temp_ptr+1, '/');
        }
        
        if (!temp_ptr)
        {
            /* Even though this is an invalid file, we still need to pass a
               file name to the caller because NULL is used to indicate end
               of playlist */
            return now_playing;
        }
    }

    return temp_ptr;
}

/*
 * Update indices as track has changed
 */
int playlist_next(int steps)
{
    struct playlist_info* playlist = &current_playlist;
    int index;

    if ( (steps > 0)
#if (AB_REPEAT_ENABLE == 1)
    && (global_settings.repeat_mode != REPEAT_AB)
#endif
    && (global_settings.repeat_mode != REPEAT_ONE) )
    {
        int i, j;

        /* We need to delete all the queued songs */
        for (i=0, j=steps; i<j; i++)
        {
            index = get_next_index(playlist, i, -1);
            
            if (playlist->indices[index] & PLAYLIST_QUEUE_MASK)
            {
                remove_track_from_playlist(playlist, index, true);
                steps--; /* one less track */
            }
        }
    }

    index = get_next_index(playlist, steps, -1);

    if (index < 0)
    {
        /* end of playlist... or is it */
        if (global_settings.repeat_mode == REPEAT_SHUFFLE &&
            global_settings.playlist_shuffle &&
            playlist->amount > 1)
        {
            /* Repeat shuffle mode.  Re-shuffle playlist and resume play */
            playlist->first_index = global_settings.resume_first_index = 0;
            sort_playlist(playlist, false, false);
            randomise_playlist(playlist, current_tick, false, true);
#if CONFIG_CODEC != SWCODEC
            playlist_start(0, 0);
#endif
            playlist->index = 0;
            index = 0;
        }
        else if (playlist->in_ram && global_settings.next_folder)
        {
            char dir[MAX_PATH+1];

            changing_dir = true;
            if (steps > 0)
            {
                if (!get_next_directory(dir))
                {
                    /* start playing next directory */
                    if (playlist_create(dir, NULL) != -1)
                    {
                        ft_build_playlist(tree_get_context(), 0);
                        if (global_settings.playlist_shuffle)
                            playlist_shuffle(current_tick, -1);                    
#if CONFIG_CODEC != SWCODEC
                        playlist_start(0, 0);
#endif
                        playlist->index = index = 0;
                    }
                }
            }
            else
            {
                if (!get_previous_directory(dir))
                {
                    /* start playing previous directory */
                    if (playlist_create(dir, NULL) != -1)
                    {
                        ft_build_playlist(tree_get_context(), 0);
                        if (global_settings.playlist_shuffle)
                            playlist_shuffle(current_tick, -1);
#if CONFIG_CODEC != SWCODEC
                        playlist_start(current_playlist.amount-1, 0);
#endif
                        playlist->index = index = current_playlist.amount - 1;
                    }
                }
            }
            changing_dir = false;
        }

        return index;
    }

    playlist->index = index;

    if (playlist->last_insert_pos >= 0 && steps > 0)
    {
        /* check to see if we've gone beyond the last inserted track */
        int cur = rotate_index(playlist, index);
        int last_pos = rotate_index(playlist, playlist->last_insert_pos);

        if (cur > last_pos)
        {
            /* reset last inserted track */
            playlist->last_insert_pos = -1;

            if (playlist->control_fd >= 0)
            {
                int result = update_control(playlist, PLAYLIST_COMMAND_RESET,
                    -1, -1, NULL, NULL, NULL);

                if (result < 0)
                    return result;

                sync_control(playlist, false);
            }
        }
    }

    return index;
}

/* try playing next or previous folder */
bool playlist_next_dir(int direction)
{
    char dir[MAX_PATH+1];
    bool result;
    int res;

    /* not to mess up real playlists */
    if(!current_playlist.in_ram)
       return false;

    if(changing_dir)
       return false;

    changing_dir = true;
    if(direction > 0)
      res = get_next_directory(dir);
    else
      res = get_previous_directory(dir);
    if (!res)
    {
        if (playlist_create(dir, NULL) != -1)
        {
            ft_build_playlist(tree_get_context(), 0);
            if (global_settings.playlist_shuffle)
                 playlist_shuffle(current_tick, -1);
#if (CONFIG_CODEC != SWCODEC)
            playlist_start(0,0);
#endif
            result = true;
        }
        else
            result = false;
    }
    else
        result = false;

    changing_dir = false;

    return result;    
}

/* Get resume info for current playing song.  If return value is -1 then
   settings shouldn't be saved. */
int playlist_get_resume_info(int *resume_index)
{
    struct playlist_info* playlist = &current_playlist;

    *resume_index = playlist->index;

    return 0;
}

/* Update resume info for current playing song.  Returns -1 on error. */
int playlist_update_resume_info(const struct mp3entry* id3)
{
    struct playlist_info* playlist = &current_playlist;

    if (id3)
    {
        if (global_settings.resume_index != playlist->index ||
            global_settings.resume_offset != id3->offset)
        {
            global_settings.resume_index = playlist->index;
            global_settings.resume_offset = id3->offset;
            settings_save();
        }
    }
    else
    {
        global_settings.resume_index = -1;
        global_settings.resume_offset = -1;
        settings_save();
    }

    return 0;
}

/* Returns index of current playing track for display purposes.  This value
   should not be used for resume purposes as it doesn't represent the actual
   index into the playlist */
int playlist_get_display_index(void)
{
    struct playlist_info* playlist = &current_playlist;

    /* first_index should always be index 0 for display purposes */
    int index = rotate_index(playlist, playlist->index);

    return (index+1);
}

/* returns number of tracks in current playlist */
int playlist_amount(void)
{
    return playlist_amount_ex(NULL);
}

/*
 * Create a new playlist  If playlist is not NULL then we're loading a
 * playlist off disk for viewing/editing.  The index_buffer is used to store
 * playlist indices (required for and only used if !current playlist).  The
 * temp_buffer (if not NULL) is used as a scratchpad when loading indices.
 */
int playlist_create_ex(struct playlist_info* playlist,
                       const char* dir, const char* file,
                       void* index_buffer, int index_buffer_size,
                       void* temp_buffer, int temp_buffer_size)
{
    if (!playlist)
        playlist = &current_playlist;
    else
    {
        /* Initialize playlist structure */
        int r = rand() % 10;
        playlist->current = false;

        /* Use random name for control file */
        snprintf(playlist->control_filename, sizeof(playlist->control_filename),
            "%s.%d", PLAYLIST_CONTROL_FILE, r);
        playlist->fd = -1;
        playlist->control_fd = -1;

        if (index_buffer)
        {
            int num_indices = index_buffer_size / sizeof(int);

#ifdef HAVE_DIRCACHE
            num_indices /= 2;
#endif
            if (num_indices > global_settings.max_files_in_playlist)
                num_indices = global_settings.max_files_in_playlist;

            playlist->max_playlist_size = num_indices;
            playlist->indices = index_buffer;
#ifdef HAVE_DIRCACHE
            playlist->filenames = (const struct dircache_entry **)
                &playlist->indices[num_indices];
#endif
        }
        else
        {
            playlist->max_playlist_size = current_playlist.max_playlist_size;
            playlist->indices = current_playlist.indices;
#ifdef HAVE_DIRCACHE
            playlist->filenames = current_playlist.filenames;
#endif
        }

        playlist->buffer_size = 0;
        playlist->buffer = NULL;
        mutex_init(&playlist->control_mutex);
    }

    new_playlist(playlist, dir, file);

    if (file)
        /* load the playlist file */
        add_indices_to_playlist(playlist, temp_buffer, temp_buffer_size);

    return 0;
}

/*
 * Set the specified playlist as the current.
 * NOTE: You will get undefined behaviour if something is already playing so
 *       remember to stop before calling this.  Also, this call will
 *       effectively close your playlist, making it unusable.
 */
int playlist_set_current(struct playlist_info* playlist)
{
    if (!playlist || (check_control(playlist) < 0))
        return -1;

    empty_playlist(&current_playlist, false);

    strncpy(current_playlist.filename, playlist->filename,
        sizeof(current_playlist.filename));

    current_playlist.fd = playlist->fd;

    close(playlist->control_fd);
    close(current_playlist.control_fd);
    remove(current_playlist.control_filename);
    if (rename(playlist->control_filename,
            current_playlist.control_filename) < 0)
        return -1;
    current_playlist.control_fd = open(current_playlist.control_filename,
        O_RDWR);
    if (current_playlist.control_fd < 0)
        return -1;
    current_playlist.control_created = true;

    current_playlist.dirlen = playlist->dirlen;

    if (playlist->indices && playlist->indices != current_playlist.indices)
    {
        memcpy(current_playlist.indices, playlist->indices,
               playlist->max_playlist_size*sizeof(int));
#ifdef HAVE_DIRCACHE
        memcpy(current_playlist.filenames, playlist->filenames,
               playlist->max_playlist_size*sizeof(int));
#endif
    }
    
    current_playlist.first_index = playlist->first_index;
    current_playlist.amount = playlist->amount;
    current_playlist.last_insert_pos = playlist->last_insert_pos;
    current_playlist.seed = playlist->seed;
    current_playlist.shuffle_modified = playlist->shuffle_modified;
    current_playlist.deleted = playlist->deleted;
    current_playlist.num_inserted_tracks = playlist->num_inserted_tracks;
    
    memcpy(current_playlist.control_cache, playlist->control_cache,
        sizeof(current_playlist.control_cache));
    current_playlist.num_cached = playlist->num_cached;
    current_playlist.pending_control_sync = playlist->pending_control_sync;

    return 0;
}

/*
 * Close files and delete control file for non-current playlist.
 */
void playlist_close(struct playlist_info* playlist)
{
    if (!playlist)
        return;

    if (playlist->fd >= 0)
        close(playlist->fd);

    if (playlist->control_fd >= 0)
        close(playlist->control_fd);

    if (playlist->control_created)
        remove(playlist->control_filename);
}

/*
 * Insert track into playlist at specified position (or one of the special
 * positions).  Returns position where track was inserted or -1 if error.
 */
int playlist_insert_track(struct playlist_info* playlist,
                          const char *filename, int position, bool queue)
{
    int result;
    
    if (!playlist)
        playlist = &current_playlist;

    if (check_control(playlist) < 0)
    {
        gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
        return -1;
    }

    result = add_track_to_playlist(playlist, filename, position, queue, -1);

    if (result != -1)
    {
        sync_control(playlist, false);
        if ((audio_status() & AUDIO_STATUS_PLAY) && playlist->started)
            audio_flush_and_reload_tracks();
    }

#ifdef HAVE_DIRCACHE
    queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
#endif

    return result;
}

/*
 * Insert all tracks from specified directory into playlist.
 */
int playlist_insert_directory(struct playlist_info* playlist,
                              const char *dirname, int position, bool queue,
                              bool recurse)
{
    int count = 0;
    int result;
    unsigned char *count_str;

    if (!playlist)
        playlist = &current_playlist;

    if (check_control(playlist) < 0)
    {
        gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
        return -1;
    }

    if (queue)
        count_str = str(LANG_PLAYLIST_QUEUE_COUNT);
    else
        count_str = str(LANG_PLAYLIST_INSERT_COUNT);

    display_playlist_count(count, count_str);

    cpu_boost(true);

    result = add_directory_to_playlist(playlist, dirname, &position, queue,
        &count, recurse);

    sync_control(playlist, false);

    cpu_boost(false);

    display_playlist_count(count, count_str);

    if ((audio_status() & AUDIO_STATUS_PLAY) && playlist->started)
        audio_flush_and_reload_tracks();

#ifdef HAVE_DIRCACHE
    queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
#endif

    return result;
}

/*
 * Insert all tracks from specified playlist into dynamic playlist.
 */
int playlist_insert_playlist(struct playlist_info* playlist, char *filename,
                             int position, bool queue)
{
    int fd;
    int max;
    char *temp_ptr;
    char *dir;
    unsigned char *count_str;
    char temp_buf[MAX_PATH+1];
    char trackname[MAX_PATH+1];
    int count = 0;
    int result = 0;

    if (!playlist)
        playlist = &current_playlist;

    if (check_control(playlist) < 0)
    {
        gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
        return -1;
    }

    fd = open(filename, O_RDONLY);
    if (fd < 0)
    {
        gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_ACCESS_ERROR));
        return -1;
    }

    /* we need the directory name for formatting purposes */
    dir = filename;

    temp_ptr = strrchr(filename+1,'/');
    if (temp_ptr)
        *temp_ptr = 0;
    else
        dir = "/";

    if (queue)
        count_str = str(LANG_PLAYLIST_QUEUE_COUNT);
    else
        count_str = str(LANG_PLAYLIST_INSERT_COUNT);

    display_playlist_count(count, count_str);

    cpu_boost(true);

    while ((max = read_line(fd, temp_buf, sizeof(temp_buf))) > 0)
    {
        /* user abort */
        if (button_get(false) == SETTINGS_CANCEL)
            break;

        if (temp_buf[0] != '#' && temp_buf[0] != '\0')
        {
            int insert_pos;

            /* we need to format so that relative paths are correctly
               handled */
            if (format_track_path(trackname, temp_buf, sizeof(trackname), max,
                    dir) < 0)
            {
                result = -1;
                break;
            }
            
            insert_pos = add_track_to_playlist(playlist, trackname, position,
                queue, -1);

            if (insert_pos < 0)
            {
                result = -1;
                break;
            }

            /* Make sure tracks are inserted in correct order if user
               requests INSERT_FIRST */
            if (position == PLAYLIST_INSERT_FIRST || position >= 0)
                position = insert_pos + 1;

            count++;
            
            if ((count%PLAYLIST_DISPLAY_COUNT) == 0)
            {
                display_playlist_count(count, count_str);

                if (count == PLAYLIST_DISPLAY_COUNT &&
                    (audio_status() & AUDIO_STATUS_PLAY) &&
                    playlist->started)
                    audio_flush_and_reload_tracks();
            }
        }

        /* let the other threads work */
        yield();
    }

    close(fd);

    if (temp_ptr)
        *temp_ptr = '/';

    sync_control(playlist, false);

    cpu_boost(false);

    display_playlist_count(count, count_str);

    if ((audio_status() & AUDIO_STATUS_PLAY) && playlist->started)
        audio_flush_and_reload_tracks();

#ifdef HAVE_DIRCACHE
    queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
#endif

    return result;
}

/*
 * Delete track at specified index.  If index is PLAYLIST_DELETE_CURRENT then
 * we want to delete the current playing track.
 */
int playlist_delete(struct playlist_info* playlist, int index)
{
    int result = 0;

    if (!playlist)
        playlist = &current_playlist;

    if (check_control(playlist) < 0)
    {
        gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
        return -1;
    }

    if (index == PLAYLIST_DELETE_CURRENT)
        index = playlist->index;

    result = remove_track_from_playlist(playlist, index, true);
    
    if (result != -1 && (audio_status() & AUDIO_STATUS_PLAY) &&
        playlist->started)
        audio_flush_and_reload_tracks();

    return result;
}

/*
 * Move track at index to new_index.  Tracks between the two are shifted
 * appropriately.  Returns 0 on success and -1 on failure.
 */
int playlist_move(struct playlist_info* playlist, int index, int new_index)
{
    int result;
    int seek;
    bool control_file;
    bool queue;
    bool current = false;
    int r;
    char filename[MAX_PATH];

    if (!playlist)
        playlist = &current_playlist;

    if (check_control(playlist) < 0)
    {
        gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_CONTROL_ACCESS_ERROR));
        return -1;
    }

    if (index == new_index)
        return -1;

    if (index == playlist->index)
        /* Moving the current track */
        current = true;

    control_file = playlist->indices[index] & PLAYLIST_INSERT_TYPE_MASK;
    queue = playlist->indices[index] & PLAYLIST_QUEUE_MASK;
    seek = playlist->indices[index] & PLAYLIST_SEEK_MASK;

    if (get_filename(playlist, index, seek, control_file, filename,
            sizeof(filename)) < 0)
        return -1;

    /* Delete track from original position */
    result = remove_track_from_playlist(playlist, index, true);

    if (result != -1)
    {
        /* We want to insert the track at the position that was specified by
           new_index.  This may be different then new_index because of the
           shifting that occurred after the delete */
        r = rotate_index(playlist, new_index);

        if (r == 0)
            /* First index */
            new_index = PLAYLIST_PREPEND;
        else if (r == playlist->amount)
            /* Append */
            new_index = PLAYLIST_INSERT_LAST;
        else
            /* Calculate index of desired position */
            new_index = (r+playlist->first_index)%playlist->amount;

        result = add_track_to_playlist(playlist, filename, new_index, queue,
            -1);
        
        if (result != -1)
        {
            if (current)
            {
                /* Moved the current track */
                switch (new_index)
                {
                    case PLAYLIST_PREPEND:
                        playlist->index = playlist->first_index;
                        break;
                    case PLAYLIST_INSERT_LAST:
                        playlist->index = playlist->first_index - 1;
                        if (playlist->index < 0)
                            playlist->index += playlist->amount;
                        break;
                    default:
                        playlist->index = new_index;
                        break;
                }
            }

            if ((audio_status() & AUDIO_STATUS_PLAY) && playlist->started)
                audio_flush_and_reload_tracks();
        }
    }

#ifdef HAVE_DIRCACHE
    queue_post(&playlist_queue, PLAYLIST_LOAD_POINTERS, 0);
#endif

    return result;
}

/* shuffle currently playing playlist */
int playlist_randomise(struct playlist_info* playlist, unsigned int seed,
                       bool start_current)
{
    int result;

    if (!playlist)
        playlist = &current_playlist;

    check_control(playlist);

    result = randomise_playlist(playlist, seed, start_current, true);

    if (result != -1 && (audio_status() & AUDIO_STATUS_PLAY) &&
        playlist->started)
        audio_flush_and_reload_tracks();

    return result;
}

/* sort currently playing playlist */
int playlist_sort(struct playlist_info* playlist, bool start_current)
{
    int result;

    if (!playlist)
        playlist = &current_playlist;

    check_control(playlist);

    result = sort_playlist(playlist, start_current, true);

    if (result != -1 && (audio_status() & AUDIO_STATUS_PLAY) &&
        playlist->started)
        audio_flush_and_reload_tracks();

    return result;
}

/* returns true if playlist has been modified */
bool playlist_modified(const struct playlist_info* playlist)
{
    if (!playlist)
        playlist = &current_playlist;

    if (playlist->shuffle_modified ||
        playlist->deleted ||
        playlist->num_inserted_tracks > 0)
        return true;

    return false;
}

/* returns index of first track in playlist */
int playlist_get_first_index(const struct playlist_info* playlist)
{
    if (!playlist)
        playlist = &current_playlist;

    return playlist->first_index;
}

/* returns shuffle seed of playlist */
int playlist_get_seed(const struct playlist_info* playlist)
{
    if (!playlist)
        playlist = &current_playlist;

    return playlist->seed;
}

/* returns number of tracks in playlist (includes queued/inserted tracks) */
int playlist_amount_ex(const struct playlist_info* playlist)
{
    if (!playlist)
        playlist = &current_playlist;

    return playlist->amount;
}

/* returns full path of playlist (minus extension) */
char *playlist_name(const struct playlist_info* playlist, char *buf,
                    int buf_size)
{
    char *sep;

    if (!playlist)
        playlist = &current_playlist;

    snprintf(buf, buf_size, "%s", playlist->filename+playlist->dirlen);
  
    if (!buf[0])
        return NULL;

    /* Remove extension */
    sep = strrchr(buf, '.');
    if (sep)
        *sep = 0;

    return buf;
}

/* returns the playlist filename */
char *playlist_get_name(const struct playlist_info* playlist, char *buf,
                        int buf_size)
{
    if (!playlist)
        playlist = &current_playlist;

    snprintf(buf, buf_size, "%s", playlist->filename);

    if (!buf[0])
        return NULL;

    return buf;
}

/* Fills info structure with information about track at specified index.
   Returns 0 on success and -1 on failure */
int playlist_get_track_info(struct playlist_info* playlist, int index,
                            struct playlist_track_info* info)
{
    int seek;
    bool control_file;

    if (!playlist)
        playlist = &current_playlist;

    if (index < 0 || index >= playlist->amount)
        return -1;

    control_file = playlist->indices[index] & PLAYLIST_INSERT_TYPE_MASK;
    seek = playlist->indices[index] & PLAYLIST_SEEK_MASK;

    if (get_filename(playlist, index, seek, control_file, info->filename,
            sizeof(info->filename)) < 0)
        return -1;

    info->attr = 0;

    if (control_file)
    {
        if (playlist->indices[index] & PLAYLIST_QUEUE_MASK)
            info->attr |= PLAYLIST_ATTR_QUEUED;
        else
            info->attr |= PLAYLIST_ATTR_INSERTED;
        
    }

    if (playlist->indices[index] & PLAYLIST_SKIPPED)
        info->attr |= PLAYLIST_ATTR_SKIPPED;
    
    info->index = index;
    info->display_index = rotate_index(playlist, index) + 1;

    return 0;
}

/* save the current dynamic playlist to specified file */
int playlist_save(struct playlist_info* playlist, char *filename)
{
    int fd;
    int i, index;
    int count = 0;
    char path[MAX_PATH+1];
    char tmp_buf[MAX_PATH+1];
    int result = 0;
    bool overwrite_current = false;
    int* index_buf = NULL;

    if (!playlist)
        playlist = &current_playlist;

    if (playlist->amount <= 0)
        return -1;

    /* use current working directory as base for pathname */
    if (format_track_path(path, filename, sizeof(tmp_buf),
                          strlen(filename)+1, getcwd(NULL, -1)) < 0)
        return -1;

    if (!strncmp(playlist->filename, path, strlen(path)))
    {
        /* Attempting to overwrite current playlist file.*/

        if (playlist->buffer_size < (int)(playlist->amount * sizeof(int)))
        {
            /* not enough buffer space to store updated indices */
            gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_ACCESS_ERROR));
            return -1;
        }

        /* in_ram buffer is unused for m3u files so we'll use for storing
           updated indices */
        index_buf = (int*)playlist->buffer;

        /* use temporary pathname */
        snprintf(path, sizeof(path), "%s_temp", playlist->filename);
        overwrite_current = true;
    }

    fd = open(path, O_CREAT|O_WRONLY|O_TRUNC);
    if (fd < 0)
    {
        gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_ACCESS_ERROR));
        return -1;
    }

    display_playlist_count(count, str(LANG_PLAYLIST_SAVE_COUNT));

    cpu_boost(true);

    index = playlist->first_index;
    for (i=0; i<playlist->amount; i++)
    {
        bool control_file;
        bool queue;
        int seek;

        /* user abort */
        if (button_get(false) == SETTINGS_CANCEL)
        {
            result = -1;
            break;
        }

        control_file = playlist->indices[index] & PLAYLIST_INSERT_TYPE_MASK;
        queue = playlist->indices[index] & PLAYLIST_QUEUE_MASK;
        seek = playlist->indices[index] & PLAYLIST_SEEK_MASK;

        /* Don't save queued files */
        if (!queue)
        {
            if (get_filename(playlist, index, seek, control_file, tmp_buf,
                    MAX_PATH+1) < 0)
            {
                result = -1;
                break;
            }

            if (overwrite_current)
                index_buf[count] = lseek(fd, 0, SEEK_CUR);

            if (fdprintf(fd, "%s\n", tmp_buf) < 0)
            {
                gui_syncsplash(HZ*2, true, str(LANG_PLAYLIST_ACCESS_ERROR));
                result = -1;
                break;
            }

            count++;

            if ((count % PLAYLIST_DISPLAY_COUNT) == 0)
                display_playlist_count(count, str(LANG_PLAYLIST_SAVE_COUNT));

            yield();
        }

        index = (index+1)%playlist->amount;
    }

    display_playlist_count(count, str(LANG_PLAYLIST_SAVE_COUNT));

    close(fd);

    if (overwrite_current && result >= 0)
    {
        result = -1;

        mutex_lock(&playlist->control_mutex);

        /* Replace the current playlist with the new one and update indices */
        close(playlist->fd);
        if (remove(playlist->filename) >= 0)
        {
            if (rename(path, playlist->filename) >= 0)
            {
                playlist->fd = open(playlist->filename, O_RDONLY);
                if (playlist->fd >= 0)
                {
                    index = playlist->first_index;
                    for (i=0, count=0; i<playlist->amount; i++)
                    {
                        if (!(playlist->indices[index] & PLAYLIST_QUEUE_MASK))
                        {
                            playlist->indices[index] = index_buf[count];
                            count++;
                        }
                        index = (index+1)%playlist->amount;
                    }

                    /* we need to recreate control because inserted tracks are
                       now part of the playlist and shuffle has been
                       invalidated */
                    result = recreate_control(playlist);
                }
            }
       }

       mutex_unlock(&playlist->control_mutex);

    }

    cpu_boost(false);

    return result;
}