File: dvd-slideshow

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

name='dvd-slideshow'
version='0.8.4-1'

echo "[dvd-slideshow]            dvd-slideshow $version"
echo "[dvd-slideshow]            Licensed under the GNU GPL"
echo "[dvd-slideshow]            Copyright 2003-2011 by Scott Dylewski"
echo "[dvd-slideshow]            "

## todo: (sorted by priority?)
# binary rendering engine for much better speed
# explain difference between Low/Medium/High quality modes
# add hints for smoothest kenburns effects. (no zoom and pan)

## known bugs:
####################
# 8/2011:  using -L with -flv or -s doesn't work
#
# continuous subtitles don't work across non-image/transition lines
# convert image.jpg -bordercolor black -border 0 "$tmpdir/fade_$dj.ppm" works for transparent .png images
# in ImageMagick > 6.0.6, but not in 6.0.6 for some reason. (black output). 

# sometimes we'll get errors:  xargs: cat: terminated by signal 13
# Signal 13 means, "Write on a pipe with no one to read it" so this means
# that cat is trying to write to ppmtoy4m and it's not ready or something

## set up bash variables  http://wiki.sourcemage.org/HOWTO-Locale_problems
LC_ALL=C
LANG="POSIX"

changes ()
{
echo 'Changes:
0.8.4
    New features:
	Improved encoding speed significantly. (thanks Gary Hunt!)
	Use qscale VBR option in avconv for flv and mp4 output instead of fixed bitrate.
	Logo (-logo) works as general overlay (beta).
	Added -threads $cores to ffmepg calls for speed improvement?
	Added .ogg mode ( use -ogv ) (not working yet)
	Added ipod output ( use -ipod ) (not working yet)
	Add quiet output mode -q to reduce output
    Bug fixes:
	Use soxi to determine length of .wav audio instead of sox (better compatibility?)
	Fixed chroma subsampling bug when using -mpeg2enc option (cat terminated by signal 13)
	New dvdauthor/spumux > 0.7.0 require explicit NTSC/PAL declaration
	No audio added to .flv files when none is passed by default.
	Changed default dvd audio bitrate from 192kbps to 256kbps
	Enable subtitle_location_x (was not being passed before)
	Fix audio duration for .avi files (untested) (thanks Guy Albertelli)
	Fix hms2seconds to allow 0:08:05:345 (seconds and minutes like "08") (thanks Guy Albertelli)
	Redirect wait errors to log file to reduce errors in long slideshows
	Improved kenburns jitter.
	Added unset CDPATH to full_path function call (thanks Bob!)
	Fixed bug with old version of findutils < 4.2.5
	Use du -b so it is independend of env variables (thanks kikoun)
	Change sleep 1s to sleep 0.01s for faster machines
	Add better help for missing applications and graphicsmagick
	Allow escaped # in musictitle slides (use \# to print #)
	Added fixes for .avi files (thanks Guy Albertelli)

0.8.2
    New features:
	Error check code BEFORE running full script.
	Added -logo <logofile> option to add a logo to each slide. (does not work with transitions yet)
	Added -mpg output for creating alternate-sized mpeg output that does not conform to dvd standards (very alpha)
	Better control over subtitles with new variables subtitle_location_x and subtitle_location_y. Default x location is 0.
	Better handling of very long subtitles. (up to 3 lines and reduced font size)
	No subtitles are rendered during fades.
	Log file now uses the slideshow name instead of dvd-slideshow.log
    Bug fixes:
	Allow spaces in output files (spaces used to be forced to underscores).
	Removed old "smoothing=0" option in kenburns
	Change imagemagick calls with -type TrueColor to -type TrueColorMatte for latest version
	Sox v. > 13 changes -w to -2 and -e to -n (thanks Ludovic)
	Allow "widescreen=1" in input file. ( not tested much )
	Changed "sleep 0.1s" to "sleep 1s" for better compatibility.
	Fixed hms2seconds with leading zeros (thanks Arnd Baecker)
	Better (larger) resizing for kenburns in high-quality mode.
	Smoother scroll effect in normal mode (fixed rounding error)
	Font search follows links. Thanks Jim Potter!
	Change LANG=C to LANG=POSIX to try to fix radix problems with printf
	Added some code to only process one crossfade in the background at a time.
	Fixed problem with subtitles- last one was not being displayed.
	Added "k" to audio bitrate arguments to avconv (thanks Tony!)
	Fixed bug where subtitles would not show in crop and kenburns effects.
	Fixed bug with audio timing when using scroll & kenburns.
	removed -size option from crop function because large images were improperly cropped.
	added -M option to mplex calls (for some reason it was removed)
	Fix audio when passing an .avi file.
	Fixed chapter keyword timing.
	Increased mplex bitrate to 9500 from 9000 to fix some possible encoding bugs.
	Fix bug with hms handling times longer than 1 hour. Thanks Michael Crider'
}

help ()
{
echo "`basename $0` Version $version "
echo 'http://dvd-slideshow.sourceforge.net'
echo 'Copyright 2003-2011 Scott Dylewski <scott at dylewski.com>'
echo 	 
echo 'Description: 
	Creates a video video from a bunch of images. This can be used
	to make a mpeg2-compatible DVD or to make .flv slideshows for the web.
	You can add music if you want also. Supports several effects
	like fadein/fadeout/crossfade/crop/kenburns. 

Usage:
 dvd-slideshow [-n <slideshow_name>] [-o <output_directory>] 
  [-flv] [-mp4] [-s WxH] [-theme <themefile>] 
  [other options] [-f] input_file.txt

 The preferred method of running a slideshow is to create an input_file.txt
 that includes all the settings, audio, and images, and then run dvd-slideshow with
 that file as an input file. See below for details on how to construct such 
 a file.
	
Options: 
 [-n slideshow_name]
	  The program uses this
	  string as the filename base for the output files
	  so you can distinguish it from other slideshows
	  that you can send to the same output directory.
 [-o <outupt directory>]
	  Directory where the final .vob and dvdauthor .xml files
	  will be written. Default is to write in the directory
	  where dvd-slideshow was run.
 [-b <background jpeg>]
	  Image to use for the background of the slideshow.
	  All of the pictures will be
	  overlaid on top of this background image. If no file 
	  is specified, black will be used for the slideshow
	  and a blue gradient for the title slide.
 [-a <audio file>]
          Audio file to play in background during the slideshow.
          It will be faded out at the end. Supports mp3, ogg, 
	  aac, mp4, or wav formats at this point.
	  Multiple files will be joined.
	  See also the more flexible text file input method.
	  To pass multiple files, use the -a switch again.
 [-p]
	Use PAL output video format instead of NTSC
 [-mpeg2enc]
	Force use mpeg2enc with mp2 audio even though avconv is installed
 [-mp2]
	Use MP2 audio instead of AC3.
	Default audio format is now AC3 because it seems to be more
	compatible with the DVD hardware players.
 [-s WidthxHeight]	
	Use output size other than the standard DVD
	output size (720x480 for NTSC). Usually used with other
	output formats like .flv or .mp4
 [-flv]
	Render a flash video file instead of .vob. 
 [-mp4]
	Render a mp4 video file instead of .vob.
 [-mpg]
	Render a .mpg video file instead of .vob. Allows for alternate
	sizing with -s
 [-L]
	Render a low-quality video suitable for debugging.
	This sets the resolution to 1/2 of full resolution and
	decreases the quality of fades/transitions.
 [-H]
	(Beta) Render a higher-quality video. 
	This uses the default dvd resolution and keeps all other output
	parameters the same, but enables some pixel-sampling methods
	that make the scroll effect look better at very slow velocities.
	This will make dvd-slideshow take up to 4x longer to process the
	scroll effect. Only applied when needed; the output will explain. 
 [-theme <themefile>]
 	Use the given theme when setting variables/colors/etc.
	Themes are installed in /opt/dvd-slideshow/themes or
	in a local directory ~/.dvd-slideshow/themes
 [-border N]
 	Make a border of N pixels around each image. 
 [-sharpen]
 	Sharpen images
 [-r]
 	Autocrop horizontal images to fill the full size of the screen.
 [-nosmp]
	Disable multiple threads in some processes when possible. If you
	have little memory or a slow machine, this may help if you experience
	problems with disk memory caching.
 [-nocleanup]
 	Leave temporary files in the temporary directory. Useful for debugging.
 [-q]	Quiet output mode.  Reduce amount of information on screen, but keep
	a progressbar indicator.
 [-V 1 or 2] Add more verbose debug output.  1 adds more than the default, and 2
	Adds a lot.
 -h or -help 
   Prints this help. 
 -v or -version 
   Prints dvd-slideshow version number. 

 [-f] input_file.txt  (-f is optional if the file is the last argument)
          File to specify all the parameters and order easily
          for bigger slideshows. It uses the : character as a 
	  separator for the fields:
          [image.jpg|keyword]:duration:subtitle:effect:effect_params
          with each line being separate. File options
          will override the ones passed on the command line.

	  NOTE: the effect parameters are separated by a semicolon ;
	  instead of a colon :

	  You can escape a colon with a backslash in subtitle text.

	  Durations can be specified in seconds with
	  up to three decimal points, like 5.583 seconds.

	  Keywords:
            title:duration:Title_text
                makes a title slide. Text is centered on the screen.
            titlebar:duration:Upper_Title:Lower_Title
                makes a title slide. Upper and lower titles are
                optional; if one is missing, only the other will
                be displayed. White bands are underlayed behind
                the text.
	    musictitle:duration:subtitle:Title;Artist;Album
	   	makes a black frame with the song info 
		printed in the bottom left corner.
	    background:duration:subtitle:image 
	    	makes a slide with the current background 
		or it resets the current background image to a new one:
		"background:2:"  will display the current background
		for 2 seconds. 
		"background:2::image.jpg"  will set the background to
		image.jpg and also display it for 2 seconds.
		"background:0::image.jpg"  will set the background to 
		image.jpg, but will not use it until the next picture. 
		"black" or "white" can be used instead of an image 
		name to display a black or white background.
		You can also use a hex RGB code as the background color.

	    Transitions:
	      fadein:duration:subtitle
	      	fades in to the next slide
	      fadeout:duration:subtitle
	      	fades out to the background
	      crossfade:duration:subtitle
	      	fades from one picture to the next.
	      wipe:duration:subtitle:[up|down|left|right]
	    	wipes from one picture to the next. Defaults to left.
	    Transitions do not add time to the overall slideshow, they
	    Just get overlaid on top of of the adjacent images. Because
	    of this, the transition duration can not be greater than half
	    of the adjacent image duration.  

	    chapter
	  	Force manual chapter marker timing. Chapter markers will
	  	only be created where the "chapter" keyword occurs.
		The default is to add chapter markers at every slide.
	    include:includefile.txt
	  	Other input files can be included in the input .txt file.
	  	The file includefile.txt will be concatenated in the
	  	place where the line occurs.
		Useful for setting up a bunch of variables, fonts, etc
		and then just including one standard file at the start of
		your input .txt file.
	    exit
		Stops the slideshow at the current point as if the input
		.txt file ended at this point. Useful for debugging.

	  Effects:
	    Effects are only used with images, not keywords.
	    In the following effects, x0,y0 represents the
	    top left corner of a defined box, and x1,y1 is
	    the bottom right corner. 
	    NOTE: the effect parameters are separated by a
	    semicolon ; instead of a colon :
            crop:
	    	image.jpg:dur:sub:crop:x0,y0;x1,y1
		Crops the image about the coordinates specified.
		Full box description:
	    	  x0,y0;x1,y1
		  Specifies the top-left(0) and bottom-right(1) points.
		Keyword description:
		  frame_size;frame_location
		  where frame_size indicates the fraction of the final 
		  dvd window width/height, and frame_location refers
		  to the CENTER POINT of the picture,
		  and can be any of the following keywords:
		 	topleft		top		topright
			left		middle		right
			bottomleft	bottom		bottomright
		   or
		 	x%,y%
			where % is a percentage of the window width,height
			starting from the top left corner of the dvd window.
		   or
		 	imagewidth | imageheight
			where the image width or height will be scaled to 
			fill the full width or height of the dvd screen.
		Crop examples:
	    	image.jpg:dur:sub:crop:651,390;1134,759
		image.jpg:dur:sub:crop:30%;60%,60%
		image.jpg:dur:sub:crop:50%;topleft
		image.jpg:dur:sub:crop:imageheight;left
	    kenburns:
	    	image.jpg:dur:sub:kenburns:start_box;end_box
		The kenburns effect will crop/zoom from the start
		to the end box.
	    	Where now we have start and end boxes, defined in
		the same way as in the "crop" function, but now
		we have two boxes defined.
		Full box description:
	    	  xs0,ys0;xs1,ys1;xe0,ye0;xe1,ye1
		  Specifies the top-left(0) and bottom-right(1) points.
		Keyword description:
		  start 0%-100%;start_location;end 0%-100%;end_location
		Kenburns examples:
	    	image.jpg:dur:sub:kenburns:651,390;1134,759;372,330;1365,1089
		image.jpg:dur:sub:kenburns:30%;60%,60%;75%;40%,50%
		image.jpg:dur:sub:kenburns:50%;topleft;50%;bottomright
		image.jpg:dur:sub:kenburns:100%;left;0,0;720,480
		image.jpg:dur:sub:kenburns:100%;left;imageheight;left
		kenburns note:  if you find yourself using a lot of lines like:
		crop, kenburns, crop
		where the crop coordinates are the same as the start & end
		of the kenburns, you can use a duration like 1,5,1 for one
		second of crop, followed by a 5 second kenburns, followed by
		another one second of crop (times are adjustable). (alpha)
	    scroll:
	    	image.jpg:dur:sub:scroll:[left|right|up|down]
		This is most useful for displaying panorama-style
		pictures that are much wider than they are tall.
		This will automatically resize the picture so that
		the image height is equal to the video display 
		height (480) before scrolling (or conversely for tall
		images).

	    The subtitle field is optional, but if you are passing
	    effects after the subtitle field, be sure to include 
	    all the colons :: in order for the parser to get the
	    correct info.
	    Two subtitle tracks are possible (alpha). Separate them
	    using a semicolon ;. 

	    When passing a picture, you can optionally use the
	    keyword "audio" instead of the integer duration in 
	    seconds. What this does is force the duration of
	    that image to be the length of the previous audio 
	    track. This is useful for making a music video dvd.

	  Audio:
	    Audio tracks can be inter-mixed with the video. If 
	    an audio track is placed between two different images,
	    that audio track will begin playing at the start of the
	    second image. When placing audio, use the syntax:

            audiofile:track:effect1:effect1_params:effect2:effect2_params

	    The audiofile can be an ogg, mp3, aac/mp4 or wav file.
	    Track is the resulting dvd audio track.
	    Effects are audio effects where
	    you can specify things like fadein/fadeout
	    for the audio. Example:
            audiofile.ogg:1:fadein:3:fadeout:2

	    If you want to concatenate two audio files, just place them
	    one right after another. 

	  Video: [alpha]
	    You can add video (.avi only) files and either use 
	    the audio from the video or ignore it and use your own
	    from the slideshow:
	   
	    To just play the video in the middle of a slieshow, use:
	    videofile.avi
	    To ignore the audio from the video, and use your own, use:
	    videofile.avi:noaudio
	    To use the audio in the video but fade it in or out, use:
	    videofile.avi::fadein:1:fadeout:2

	Configuration file and variables:
	  You can configure some of the variables and settings
	  that control dvd-slideshow through keywords in the input
	  .txt file or through a ~/.dvd-slideshow/dvd-slideshowrc file. The heirarchy
	  is as follows: 
	  program defaults --> ~/.dvd-slideshow/dvd-slideshowrc --> theme settings --> command-line --> input file variables
	  So the input file will over-ride your personal settings, etc.
	  The following variable are supported (with this syntax):
	   
	  debug=1       # 0 (low=default), 1 (some debug info), 2 (per frame info), 3 (function info)
	  pal=0  	# 0=ntsc 1=pal
	  ac3=1         # 0=mp2 audio 1=ac3 audio
	  copy=0        # add copies of original images to the output directory
	  autocrop=1    # autocrop images to fill full screen
  	  high_quality=0	# set high-quality mode
	  border=0	# change to number of pixels around the image that is filled in with background
	  sharpen=0	# change to 1 to enable image sharpening
	  widescreen=0	# set output to widescreen mode (16:9) instead of 4:3 (alpha)

#	  font_dir="/usr/share/fonts"
#	  font_name="n019004l.pfb" # helvetica bold URW font is default
	  font=/usr/share/fonts/default/Type1/n019004l.pfb # Helvetical bold URW font
#	  font=/usr/share/fonts/default/Type1/n0190241.pfb # Helvetical bold oblique
#	  font=/usr/share/fonts/default/Type1/a0100151.pfb # AvantGarde DemiBold
#	  font=/usr/share/fonts/default/Type1/n0220041.pfb # Courier Bold

	  ## Subtitle:
	  subtitle_type="dvd"  # use "render" to force rendering of text.
	  subtitle_font_size=24
	  subtitle_font="/usr/share/fonts/default/Type1/n019004l.pfb" # Helvetical bold URW font
	  subtitle_color="white"
	  subtitle_outline_color="black"
	  subtitle_location="bottom"
	  subtitle_location_x=0
	  subtitle_location_y=105

	  ## Title:
	  title_font_size=48
	  title_font_color="black"  # or use hex "#RRGGBB"
	  title_font="/usr/share/fonts/default/Type1/n019004l.pfb" # Helvetical bold URW font

	  ## top title:
	  toptitle_font_size=48
	  toptitle_font_color="black"  # or use hex "#RRGGBB"
	  toptitle_bar_height=125  # 0 for no 50% white behind text
	  toptitle_text_location_x=80
	  toptitle_text_location_y=50

	  # bottom title: 
	  bottomtitle_font_size=36
	  bottomtitle_font_color="black"  # or use hex "#RRGGBB"
	  bottomtitle_bar_location_y=156 # relative to bottom of image
	  bottomtitle_bar_height=55  # 0 for no 50% white behind text
	  bottomtitle_text_location_x=0
	  bottomtitle_text_location_y=155
	  
	  # kenburns:
	  kenburns_acceleration=1 # in seconds, or:
	  kenburns_acceleration=25%  # as a percentage of the total kenburns effect time
		
	  # logo:
	  logo=path/to/logofile.png  # will be overlaid on top of all frames
	  logo_gravity=gravity # North | South | East | West | NorthEast | NorthWest | SouthEast | SouthWest

 ***** Alpha/Beta commandline options *****
	These have not been tested as well, so you can try them and see how it works for you
 [-C]	Make backup copy of all images passed. Useful if you want to include a directory
	of originals in the final dvd file structure.
 [-logo <logofile.png>] Overlay a logo on top of the video. Only works for most effects. 
	You must resize the logo yourself. Position can be controlled within the .txt file
	by using the logo_gravity variable. Default location is SouthEast.
 [-w]   Alpha! 
 	Render widescreen output (16:9) instead of standard (4:3) 
 [-gm]	Use GraphicsMagick instead of ImageMagick when possible. This usually speeds
	up some of the rendering.
 [-writechaps]	Write out chapter times to slideshow_name.chap for use elsewhere
'
	echo '  '
}

if [ $# -lt 1 ]; then
	echo "[dvd-slideshow] ERROR: Too few arguments"
	help
	exit 1
fi

cpu_start_time=`date +%s`

###################################################################
# Default variables
# order of perference:  
# program defaults --> ~/.dvd-slideshow/dvd-slideshowrc --> command-line args --> .txtfile settings

## setup program default variables (user configurable)
debug=0 # 0-2
quiet=0
pal=0  
copy=0
low_quality=0
#medium_quality=0  #default
high_quality=0
autocrop=0
ac3=1
widescreen=0
border=0  
sharpen=''
#subtitle_type="render"	# force subtitles to be rendered as graphics on the images.
subtitle_type="dvd"	# or, use empty for default.
font_dir="/usr/share/fonts/"
font_dir2="/usr/X11R6/lib/X11/fonts/"
font_dir3="/usr/local/share/fonts/"
default_fontname1='n019004l.pfb' # helvetica bold URW fonts
default_fontname2='helb____.ttf' # helvetica bold truetype

## Subtitle:
subtitle_font_size=24
subtitle_color="white"
subtitle_outline_color="black"
subtitle_location="bottom" # or "top"
subtitle_location_x=0
subtitle_location_y=105

## Title:
title_font_size=48
title_font_color='black'  # or use hex "#RRGGBB"

## top title:
toptitle_font_size=48
toptitle_font_color='black' # or use hex "#RRGGBB"
toptitle_bar_height=125  # 0 for no 50% white behind text
toptitle_text_location_x=80
toptitle_text_location_y=50

# bottom title: 
bottomtitle_font_size=36
bottomtitle_font_color="black"  # or use hex "#RRGGBB"
bottomtitle_bar_location_y=156 # relative to bottom of image
bottomtitle_bar_height=55  # 0 for no 50% white behind text
bottomtitle_text_location_x=0
bottomtitle_text_location_y=155

themedir='/opt/dvd-slideshow/themes'  # LSB/FHS compliant. see: http://www.pathname.com/fhs/pub/fhs-2.3.html#OPTADDONAPPLICATIONSOFTWAREPACKAGES
local_themedir=~/.dvd-slideshow/themes  # local theme directory

logo=""
logo_gravity="SouthEast" # bottom right corner

##################################################################################
## not user configurable:
verbosity=0  # for mpeg2enc and such
slideshow_name=""
titletext=""
i_audio=0
j_audio=0
write_chap=0
subtitle_number=0
n=0
m=0
browse_num=0
submenu=0
write_chaps=0
chapmenu=0
browsable=0
yuvpid=0                    # pid of child mpeg2enc process
yuvfirstfile=1              # tells when to strip yuv headers
write_last_subtitle=0
write_last_subtitle2=0
commandline_audiofiles=0
nocleanup=0 
function_error=0
vcd=0; svcd=0
print_themes=0
first_title=1
first_image=1
filtermethod=Lanczos
commandline_gm=0
kenburns_acceleration=2 # in seconds

#image_postprocess='shadow'
image_postprocess='none'
mpeg_encoder='avconv' # or mpeg2enc. I find avconv 2x faster than mpeg2enc
output_format='mpeg2' # or flv, mpg, mp4, mp4_ipod. mpeg2 is default
#output_format='flv' # or flv, mpg, mp4, mp4_ipod
ignore_seq_end='-M'

# set smp option if more than 1 processor core:
cores="$( grep -i 'cpu cores' /proc/cpuinfo | head -n 1 | cut -d: -f 2 | tr -d \[:blank:\] )"
if [ -n "$cores" ] && [ "$cores" -ge 2 ] ; then
	smp=1
else
	smp=0
	cores=1
fi

theargs="$*"
## command-line settings:
for arg
do
	case "$arg" in
	## config variables:
	-p) shift; commandline_pal=1 ;;  # use pal format
	-r) shift; commandline_autocrop=1 ;;  # autocrop landscape-oriented images
	-C) shift; commandline_copy=1 ;;  # make backup copy of all pictures passed. 
	-mp2) shift; commandline_ac3=0 ;;  # use mp2 audio
	-ac3) shift; commandline_ac3=1 ;;  # use ac3 audio [default]
	-V) shift; commandline_debug="$1"; shift ;;
	## non-config variables:
	-i) shift; image[$n]="$1"; let n=$n+1; shift;;
	-o) shift; outdir="${1%%/}"; shift ;; # ${1%%/} omits trailing slash from outdir
	-b) shift; bgfile="$1"; shift ;;
	-theme) shift; commandline_theme="$1"; shift ;;
	-themes) shift; print_themes=1 ; shift ;;  # print available themes
	-logo) shift; commandline_logo="$1"; shift ;;
	-n) shift; slideshow_name="$1"; shift ;;
	-t) shift; time_per_picture="$1"; shift ;;  ## in tenths or hundredths of seconds?
	-f) shift; input_txtfile="$1"; shift
                if [ ! -f "$input_txtfile" ] ; then
                echo "[dvd-slideshow] ERROR: Input file $input_txtfile does not exist."
                exit 1
                fi ;;
	-border) shift; commandline_border="$1" ; shift ;;  # add border around image [in pixels]
	-sharpen) commandline_sharpen="1" ; shift ;;  # Sharpen image
	-s) shift; commandline_output_size="$1" ; shift ;;  # output size (over-rides defaults). use something like 320x240
	-F) shift; commandline_output_framerate="$1" ; shift ;;  # output framerate (over-rides defaults). use 15 or 10 or 20 (integers only now)  # DO NOT USE
	-writechaps) shift; write_chaps=1 ;;  # Write out chapter times to $slideshow_name.chap
#	-c) shift; chapmenu=1 ; submenu=1 ;;  # create a chapter select sub-menu (implies submenu)
#	-B) shift; browsable=1 ; submenu=1 ;;  # create a browsable slideshow (not working)
	-vcd) shift; vcd=1 ;;  # use vcd resolution and mp1 audio
	-svcd) shift; svcd=1 ;;  # use svcd resolution and mp1 audio
	-mpeg2enc) shift; commandline_mpeg_encoder='mpeg2enc'; commandline_ac3=0 ;; # force using mpeg2enc/mp2 instead of avconv/ac3
	-flv) shift; output_format='flv' ;; # flv output
	-swf) shift; output_format='swf' ;; # swf output
	-mp4) shift; output_format='mp4' ;; # mp4 output
	-ipod) shift; output_format='mp4_ipod' ;; # ipod compatible h.264/mp4 output
	-ogv) shift; output_format='ogv' ;; # OGG theora video and vorbis audio output
	-mpg) shift; output_format='mpg' ;; # mpeg output (do not assume dvd output)
	-w) shift; widescreen=1 ;;  # use 16:9 instead of 4:3 aspect ratio
	-gm) shift; commandline_gm=1 ;;  # use graphicsMagick instead of ImageMagick (alpha)
	-L) shift; low_quality=1 ;;  # use low-quality mode
	-M) shift; commandline_high_quality=0 ; low_quality=0 ;;  # use medium-quality mode (this is the default)
	-H) shift; commandline_high_quality=1 ;;  # ALPHA. use high-quality mode (This might take much longer to process in the future)
	-smp) shift; smp=1 ;;  # use multi-threaded mode 
	-nosmp) shift; smp=0 ;;  # Force no smp on smp machines.
	-nocleanup) shift; nocleanup=1 ;;  # leave all temp files
	-a) shift; 
                # make sure the file exists and is the correct type!
                suffix=`echo "$1" | awk -F. '{print tolower($NF)}'`
                if [ "$suffix" == 'ogv' ] || [ "$suffix" == 'mp3' ] || [ "$suffix" == 'wav' ] || [ "$suffix" == 'm4a' ] || [ "$suffix" == 'aac' ] ; then
                	if [ ! -f "$1" ] ; then
                       	 echo "[dvd-slideshow] ERROR: File $1 does not exist"
                         exit 1
                        fi
                        passed_audio[$m]="$1"
                        let m=$m+1
			commandline_audiofiles=$(( $commandline_audiofiles + 1 ))
                        shift;
                else
                       	 echo "[dvd-slideshow] ERROR: File $1 is not an ogg, mp3, m4a, aac, or wav file."
                         exit 1
                fi ;;
	-h) help ; exit 0 ; shift ;;
	-\?) help ; exit 0 ; shift ;;
	-help) help ; exit 0 ; shift ;;
	-q) quiet=1 ; shift ;;
	--help) help ; exit 0 ; shift ;;
	-v) echo "$version" ; exit 0 ; shift ;;
	-version) echo "$version" ; exit 0 ; shift ;;
	esac
done


##################################################################
### no more user input after this line?

###################################################################
## Functions:

myecho ()
{
	## use this version of echo to write to screen and to the logfile:
	if [ "$quiet" == 0 ] ; then
		echo "$*"
	fi
	echo "$*" >> "$outdir/$logfile"
}

logecho ()
{
	## use this version of echo to write to the logfile:
	echo "$*" >> "$outdir/$logfile"
}

myechon ()
{
	## use this version of echo to write to screen and to the logfile:
	echo -n "$*"
	echo -n "$*" >> "$outdir/$logfile"
}


#check_rm ()
#{
#	if [ -f "$1" ] ; then
#		rm "$1"
#	fi
#}

cleanup ()
{
if [ "$nocleanup" -eq 0 ] ; then
	## clean up temporary files
	myecho "[dvd-slideshow] cleanup..."
	rm -f temp_slideshow_image.ppm ; rm -f temp.ppm
	rm -f temp_slideshow_image_scaled.ppm
	rm -f "$outdir/$tmptxtfile"
	# close pipe to avconv/mpeg2enc  ( close file descriptor 9 )
        exec 9>&-  
        rm -f "$tmpdir/$yuvfifo"
        if [ "$yuvpid" -ne 0 ]; then
        	kill -TERM $yuvpid
        fi
	# Now try deleting tempdir:
	rm -rf "$tmpdir"
fi
}

forcequit () ## function gets run when we have some sort of forcequit...
{
	## clean up temporary files
	cleanup
	exit
}

trap 'forcequit' INT
trap 'forcequit' KILL
trap 'forcequit' TERM

## check for the necessary programs:
checkforprog ()
{
        it=`which $1 2> /dev/null`
        if [ -z "$it" ] ; then
                myecho "[dvd-slideshow] ERROR: $1 not found! "
                myecho "[dvd-slideshow] Check the dependencies and make sure everything is installed."
                exit 1
        fi
}

checkfor_oggdec ()
{
        it=`which oggdec 2> /dev/null`
        if [ -z "$it" ] ; then
		myecho ""
                myecho "[dvd-slideshow] ERROR: oggdec not found! "
                myecho "[dvd-slideshow] You need to download the vorbis-tools package"
		myecho "[dvd-slideshow] in order to use .ogg audio files."
		myecho "[dvd-slideshow] Debian/Ubuntu: sudo apt-get install vorbis-tools"
                exit 1
        fi
}

checkfor_lame ()
{
        it=`which lame 2> /dev/null`
        if [ -z "$it" ] ; then
                myecho "[dvd-slideshow] ERROR: lame not found! "
                myecho "[dvd-slideshow] You need to download the lame package"
		myecho "[dvd-slideshow] in order to use .mp3 audio files."
		myecho "[dvd-slideshow] Debian/Ubuntu: sudo apt-get install lame"
                exit 1
        fi
}

checkfor_faad ()
{
        it=`which faad 2> /dev/null`
        if [ -z "$it" ] ; then
                myecho "[dvd-slideshow] ERROR: faad not found! "
                myecho "[dvd-slideshow] You need to download the faad package"
		myecho "[dvd-slideshow] in order to use .m4a audio files."
		myecho "[dvd-slideshow] Debian/Ubuntu: sudo apt-get install faad"
                exit 1
        fi
}


rpmversion ()
{
	if [ -z `which rpm 2> /dev/null` ] ; then
		ver=''
	else
		ver=`rpm -q $1`
	fi
	if [ "`echo $ver | awk -F- '{print $1}'`" == "$1" ] ; then
		# rpm returned version of program
		vers=`echo $ver | awk -F- '{print $2}'`
#		echo "[dvd-slideshow] Found $1 version $vers"
	else
		# no rpm, try other methods
		vers=0  # no version found (yet)	
#		echo "[dvd-slideshow] Found $1"
	fi
	echo "$vers"  # returns 0 if no version found, but executable exists
}

hms ()  # HMS
{
	## pass a number in thousandths of seconds and get back a 
	## time code of the form HR:MM:SS.XXX
	if [ -z "$1" ] ; then
		logecho "[dvd-slideshow] Error in hms function: no input"	
		function_error=1
	else
		hours=$(( $1 / 3600000 )) ; [ $hours -eq 0 ] && hours="0" 
		it=$(( $1 - $hours * 3600000 ))
		minutes=$(( $it / 60000 )) ; [ $minutes -eq 0 ] && minutes="0" 
		it=$(( $it - $minutes * 60000 ))
		seconds=$(( $it / 1000 )) ; [ $seconds -eq 0 ] && seconds="0" 
		thousandths_out=$( printf %3.3d $(( $it - $seconds * 1000 )) );
		it="$hours:$minutes:$seconds.$thousandths_out"
		echo "${it}"
	fi
}

hms2seconds ()
{
	## pass a number in H:MM:SS.xxx and get back number of seconds
	if [ -z "$1" ] ; then
		echo ''
	else
		# need to get rid of leading zeros to avoid "printf %d '08'"
		hours=$( printf %d `echo $1 | cut -d: -f1 | sed -e 's/^0*//'` )
		minutes=$( printf %d `echo $1 | cut -d: -f2 | sed -e 's/^0*//'` )
		seconds=$( printf %d `echo $1 | cut -d: -f3 | cut -d. -f1 | sed -e 's/^0*//'` )
		fraction=`echo $1 | cut -d: -f3 | cut -d. -f2`
		characters=${#fraction}
		if [ "$characters" -eq 1 ] ; then ## no decimal was specified
			duration_ms="0"
		elif [ "$characters" -eq 2 ] ; then ## 1 decimal was specified
			duration_ms="$fraction"00
		elif [ "$characters" -eq 3 ] ; then ## 2 decimal was specified
			duration_ms="$fraction"0
		elif [ "$characters" -eq 4 ] ; then ## 3 decimal was specified. 
			duration_ms="$fraction"
		else
			echo "[dvd-slideshow] ERROR: Duration string $1 is bad."
			echo "[dvd-slideshow] 	Probably too many decimal places. "
			echo '[dvd-slideshow]   There is no point specifying 0.0001 seconds."'
			# try rounding to only 3 decimal places?	
			function_error=1
		fi
		it=$(( $seconds + $minutes * 60 + $hours * 3600 ))
		## round up thousandths?
		echo "$it"."$duration_ms"
	fi
}


max ()
{
	## get the max of the arguments
	last_number=0
	for number
	do
		if [ "$number" -gt "$last_number" ] ; then
			last_number="$number"
		fi
	done
	echo "$last_number"
}

min ()
{
	## get the min of the arguments
	last_number=10000000000000000
	for number
	do
		if [ "$number" -lt "$last_number" ] ; then
			last_number="$number"
		fi
	done
	echo "$last_number"
}

addzeros ()
{
			[ $1 -lt 1000 ] && dj2="0$1" || dj2=$1
			[ $1 -lt 100 ] && dj2="00$1" || dj2=$dj2
			[ $1 -lt 10 ] && dj2="000$1" || dj2=$dj2
			echo "$dj2"
}

# strip first line of every yuv file except the first
yuvstrip ()
{
       read junk
       cat
       return 0
}


encode_video ()
{
if [ "$yuvfirstfile" -eq 1 ]; then
	yuvfirstfile=0
	avconv -i "$1" -threads "$cores" -y -aspect $aspect_ratio -s "$dvd_width"x"$dvd_height" -r $framerate -an -pix_fmt yuv420p -f yuv4mpegpipe - 2>> "$avconv_err" >&9
else
	avconv -i "$1" -threads "$cores" -y -aspect $aspect_ratio -s "$dvd_width"x"$dvd_height" -r $framerate -an -pix_fmt yuv420p -f yuv4mpegpipe - 2>> "$avconv_err" | yuvstrip >&9
fi
}


encode ()
{
# for encoding one image for N frames
# encode $image $frames
local myimage="$1"
local myframes="$2"
if [ "$mpeg_encoder" == 'avconv' ] ; then
	# use avconv's -loop option to see if it's faster with a single image piped to the yuv4mpegpipe
	if [ "$yuvfirstfile" -eq 1 ]; then
		yuvfirstfile=0
#		avconv -f image2 -loop 1 -i "$1" -vframes "$myframes" -y -aspect $aspect_ratio -s "$dvd_width"x"$dvd_height" -r $framerate -an -pix_fmt yuv420p -f yuv4mpegpipe - 2>> "$avconv_err" >&9
		avconv -f image2 -loop 1 -i "$1" -vframes "$myframes" -y -s "$dvd_width"x"$dvd_height" -r $framerate -an -pix_fmt yuv420p -f yuv4mpegpipe - 2>> "$avconv_err" >&9
	else
#		avconv -f image2 -loop 1 -i "$1" -vframes "$myframes" -y -aspect $aspect_ratio -s "$dvd_width"x"$dvd_height" -r $framerate -an -pix_fmt yuv420p -f yuv4mpegpipe - 2>> "$avconv_err" | yuvstrip >&9
		avconv -f image2 -loop 1 -i "$1" -vframes "$myframes" -y -s "$dvd_width"x"$dvd_height" -r $framerate -an -pix_fmt yuv420p -f yuv4mpegpipe - 2>> "$avconv_err" | yuvstrip >&9
	fi
else # use old method using ppmtoy4m pipe
	if [ "$yuvfirstfile" -eq 1 ]; then
	        yuvfirstfile=0
		ppmtoy4m -v $verbosity -n "$myframes" -r -S "$subsample" -F $ppmtoy4m_frc -A $ppmtoy4m_aspect -I p "$myimage" >&9
	else
		ppmtoy4m -v $verbosity -n "$myframes" -r -S "$subsample" -F $ppmtoy4m_frc -A $ppmtoy4m_aspect -I p "$myimage" | yuvstrip >&9
	fi
fi
}


encode_fade ()
{
if [ "$mpeg_encoder" == 'avconv' ] ; then
	if [ "$yuvfirstfile" -eq 1 ]; then
		yuvfirstfile=0
		avconv -f image2 -i "$tmpdir/fade_%04d.ppm" -y -aspect $aspect_ratio -s "$dvd_width"x"$dvd_height" -r $framerate -an -pix_fmt yuv420p -f yuv4mpegpipe - 2>> "$avconv_err" >&9
	else
		avconv -f image2 -i "$tmpdir/fade_%04d.ppm" -y -aspect $aspect_ratio -s "$dvd_width"x"$dvd_height" -r $framerate -an -pix_fmt yuv420p -f yuv4mpegpipe - 2>> "$avconv_err" | yuvstrip >&9
	fi
else # use old method by sorting through files and piping through ppmtoy4m
	if [ "$yuvfirstfile" -eq 1 ]; then
		yuvfirstfile=0
		find "$tmpdir" -name "fade*.ppm" -type f -print0 | sort -z -d | xargs -0 cat | ppmtoy4m -v $verbosity -n 0 -S "$subsample" -F $ppmtoy4m_frc -A $ppmtoy4m_aspect -I p >&9
	else
		find "$tmpdir" -name "fade*.ppm" -type f -print0 | sort -z -d | xargs -0 cat | ppmtoy4m -v $verbosity -n 0 -S "$subsample" -F $ppmtoy4m_frc -A $ppmtoy4m_aspect -I p | yuvstrip >&9
	fi
fi
}

waitforfile ()
{
	# $1 is the filename
	## wait for the file to exist...
	while [ ! -f "$1" ] 
	do
		sleep 0.05s
	done
	# now, make sure it's not increasing in size, just to be sure:
	initial_size=$( du -b "$1" | awk '{print $1}' )
	sleep 0.05s
	new_size=$( du -b "$1" | awk '{print $1}' )
	while [ $initial_size -ne $new_size ]
	do
		sleep 0.05s
		if [ -f "$1" ]; then   # needed in case we kill the program
#			# tha creates the file during the while loop
			initial_size=$new_size
			new_size=$( du -b "$1" | awk '{print $1}' )
		else	
			break
		fi
	done
}

waitforfiles ()  # WAITFORFILES
# waitforfiles $filename $ext $last_file [$start_file]
{
	# $1 is the filename (with path)
	# $2 is the filename extension
	# $3 is the max digits in the series
	## wait for all files in a fade to exist...
	local dir_tmp=`dirname "$1"`
	local newfile_tmp="0"
	local di_tmp="0"
	local ext=$2
	[ -n "$4" ] && local start="$( printf %4.0f $4 )" || local start="1" 
	local end="$( printf %4.0f $3 )"
	for (( i_tmp=start ; i_tmp<=end ; i_tmp++ )) ; do
		di_tmp=`addzeros $i_tmp`
		newfile_tmp="$1"_$di_tmp.$ext
		[ $debug -ge 2 ] && logecho "waiting for file $newfile_tmp"
		while [ ! -e "$newfile_tmp" ] 
		do
			sleep 0.01s
		done
	done
}

extracopies ()  # EXTRACOPIES
# extracopies $this_frame $total_frames $extension(ppm or png)
{
	local this_frame=$1
	local total_frames=$2
	local suffix=$3
	[ -z "$suffix" ] && suffix='ppm'
	waitforfile "$tmpdir/fade_$dj"."$suffix" 
	if [ $stepsize -gt 1 ] ; then
		if [ $this_frame -eq $total_frames ] ; then
			## last frame in sequence, don't make any copies!
			echo -n ''
		elif [ $this_frame -gt $(( $total_frames - $stepsize )) ] ; then
			## make ( $total_frames - $this_frame ) copies
			end=$(( $total_frames - $this_frame ))
			for (( it=1 ; it<=end ; it++ )) ; do
				dj2=`addzeros $(( $this_frame + $it ))`
				cp "$tmpdir/fade_$dj.$suffix" "$tmpdir/fade_$dj2.$suffix"
				waitforfile "$tmpdir/fade_$dj2"."$suffix"   # need on slow systems?
			done
		else
			## loop over number of copies = stepsize-1
			end=$(( $stepsize - 1 ))
			for (( it=1 ; it<=end ; it++ )) ; do
				dj2=`addzeros $(( $this_frame + $it ))`
				cp "$tmpdir/fade_$dj.$suffix" "$tmpdir/fade_$dj2.$suffix"
				waitforfile "$tmpdir/fade_$dj2"."$suffix"   # need on slow systems?
			done
		fi
	fi
}

seconds2ms ()
{
	## break up the duration into the integer seconds and ms:
	out_duration=`echo $1 | awk '{ print $1 * 1000 }'`
	echo "$out_duration"
}

previousTransitionIncrement ()
{
	## get previous slide:  we can safely ignore the previous fadeouts because they get applied
	## only to the previous image
	local previousimage='0'
	local increment=1
	local image1='0' ; local dur1=0 ; local image_file1='0'
	while [ $(( $i - $increment )) -ge 0 ] ; do
		[ -n "${image[$i-$increment]}" ] && image1="${image[$(($i-$increment))]}" 
		[ -n "${duration[$i-$increment]}" ] && dur1="${duration[$(($i-$increment))]}" 
		[ -n "${image_file[$i-$increment]}" ] && image_file1=${image_file[$i-$increment]}
		[ -n "${avi_file[$i-$increment]}" ] && avi_file1=${avi_file[$i-$increment]}
#echo "i=$i increment=$increment image_file=${image_file[$i-$increment]}" 1>&2
		if [ "$image_file1" == "1" ] || [ "$avi_file1" == "1" ] || [ "$image1" == 'title' ] || [ "$image1" == 'titlebar' ] || [ "$image1" == 'musictitle' ] || ( [ "$image1" == 'background' ] && [ "$dur1" -ne 0 ] ) ; then
			previousimage="0"  #  i.e., not a fade
			break
		elif [ "$image1" == 'fadein' ] || [ "$image1" == 'crossfade' ] || [ "$image1" == 'wipe' ] ; then
			previousimage="$increment"
			break
		else 
			## previous line is not an image. Check for crossfade:
			increment=$(( $increment + 1 ))	
		fi
	done
	echo "$previousimage"
}

nextTransitionIncrement ()
{
	## get next transition, but we can safely ignore the fadein
	local nextimage='0'
	local increment=1
	local image1='0' ; local dur1=0 ; local image_file1='0'
	while [ $(( $i + $increment )) -le ${#image[@]} ] ; do
		[ -n "${image[$i+$increment]}" ] && image1="${image[$(($i+$increment))]}" 
		[ -n "${duration[$i+$increment]}" ] && dur1="${duration[$(($i+$increment))]}" 
		[ -n "${image_file[$i+$increment]}" ] && image_file1=${image_file[$i+$increment]}
		[ -n "${avi_file[$i+$increment]}" ] && avi_file1=${avi_file[$i+$increment]}
#		echo "i=$i increment=$increment image1=$image1 image_file1=$image_file1 nextimage=$nextimage" 1>&2
		if [ "$image_file1" == "1" ] || [ "$avi_file1" == "1" ] || [ "$image1" == 'title' ] || [ "$image1" == 'titlebar' ] || [ "$image1" == 'musictitle' ] || ( [ "$image1" == 'background' ] && [ "$dur1" != 0 ] ) ; then
			nextimage="0"  # i.e., not a transition
			break
		elif [ "$image1" == 'fadeout' ] || [ "$image1" == 'crossfade' ] || [ "$image1" == 'wipe' ] ; then
			nextimage="$increment"
			break
		else 
			## next line is not an image. Check for crossfade:
			increment=$(( $increment + 1 ))	
		fi
	done
	echo "$nextimage"
}

nextslidename ()  # NEXTSLIDENAME
{
	## get next slide:
	nextimage=''
	increment=1
	while [ $(( $i + $increment )) -le ${#image[@]} ] ; do
		image1="${image[$(($i+$increment))]}" ; dur1="${duration[$(($i+$increment))]}" ; image_file1=${image_file[$i+$increment]} ; avi_file1=${avi_file[$i+$increment]}
		if [ "$image_file1" == "1" ] || [ "$avi_file1" == "1" ] || [ "$image1" == 'title' ] || [ "$image1" == 'titlebar' ] || [ "$image1" == 'musictitle' ] || ( [ "$image1" == 'background' ] && [ "$dur1" -ne 0 ] ) ; then
			nextimage="$image1"
			break
		else 
			## next line is not an image!
			increment=$(( $increment + 1 ))	
		fi
	done
	if [ -z "$nextimage" ] ; then
		echo "" 1>&2
		echo '[dvd-slideshow] ERROR: Could not find a valid next slide' 1>&2
		echo '[dvd-slideshow]        This happens when a fade cannot locate a future image in your .txt file' 1>&2
		echo '[dvd-slideshow]	     Fix this in your input file and re-run dvd-slideshow.' 1>&2
		function_error=1
	else
		echo "$nextimage"
	fi
}

previousslideincrement ()
{
	previousimage=''
	increment=1
	while [ $(( $i - $increment )) -ge 0 ] ; do
		image1="${image[$(($i-$increment))]}" ; dur1="${duration[$(($i-$increment))]}" ; image_file1=${image_file[$i-$increment]} ; avi_file1=${avi_file[$i-$increment]}
#		image_file[$i]=0 ; audio_file[$i]=0 ; avi_file[$i]=0
		if [ $image_file1 -eq 1 ] || [ "$avi_file1" == "1" ] || [ "$image1" == 'title' ] || [ "$image1" == 'titlebar' ] || [ "$image1" == 'musictitle' ] || ( [ "$image1" == 'background' ] && [ "$dur1" -ne 0 ] ) ; then
			previousimage="$image1"
			break
		else 
			## previous line is not an image!
			increment=$(( $increment + 1 ))	
		fi
	done
	if [ -z "$previousimage" ] ; then
		increment=0
		echo "$increment"
	else
		echo "$increment"
	fi
}

nextslideincrement ()
{
	nextimage=''
	increment=1
	while [ $(( $i + $increment )) -le ${#image[@]} ] ; do
		image1="${image[$(($i+$increment))]}" ; dur1="${duration[$(($i+$increment))]}" ; image_file1=${image_file[$i+$increment]} ; avi_file1=${avi_file[$i+$increment]}
#		image_file[$i]=0 ; audio_file[$i]=0 ; avi_file[$i]=0
		if [ "$image_file1" == "1" ] || [ "$avi_file1" == "1" ] || [ "$image1" == 'title' ] || [ "$image1" == 'titlebar' ] || [ "$image1" == 'musictitle' ] || ( [ "$image1" == 'background' ] && [ "$dur1" -ne 0 ] ) ; then
			nextimage="$image1"
			break
		else 
			## next line is not an image!
			increment=$(( $increment + 1 ))	
		fi
	done
	if [ -z "$nextimage" ] ; then
		increment=0
		echo "$increment"
	else
		echo "$increment"
	fi
}

previousslideppm ()
{
	## get previous image:
	if [ -f "$tmpdir/slide_$(($i-1)).ppm" ] ; then
		previousimage="$tmpdir/slide_$(($i-1)).ppm"
	elif [ -f "$tmpdir/slide_$(($i-2)).ppm" ] ; then
		previousimage="$tmpdir/slide_$(($i-2)).ppm"
	elif [ -f "$tmpdir/slide_$(($i-3)).ppm" ] ; then
		previousimage="$tmpdir/slide_$(($i-3)).ppm"
	else 
		## previous line is not an image!
		echo "" 1>&2
		echo '[dvd-slideshow] ERROR: Could not find a valid previous image' 1>&2
		echo '[dvd-slideshow]	     This happens when a fade cannot locate a previous image in your .txt file' 1>&2
		echo '[dvd-slideshow]	     Fix this in your input file and re-run dvd-slideshow.' 1>&2
		function_error=1
	fi
	echo "$previousimage"
}

read_next_variables ()  # READ_NEXT_VARIABLES
{
	## get next slide:
	local nextimage=''
	local increment=1
	while [ $(( $i + $increment )) -le ${#image[@]} ] ; do
		local image1="${image[$(($i+$increment))]}" ; local dur1="${duration[$(($i+$increment))]}" ; local image_file1=${image_file[$i+$increment]} ; local avi_file=${avi_file[$i+$increment]}
		if [ "$image_file1" == "1" ] || [ "$avi_file1" == "1" ] || [ "$image1" == 'title' ] || [ "$image1" == 'titlebar' ] || [ "$image1" == 'musictitle' ] || ( [ "$image1" == 'background' ] && [ "$dur1" -ne 0 ] ) ; then
			nextimage="$image1"
			break
		else 
			## next line is not an image!
			# read variable if it exists:
			set_variables "$image1" 1
			increment=$(( $increment + 1 ))	
		fi
	done
	if [ -z "$nextimage" ] ; then
		echo "" 1>&2
		echo '[dvd-slideshow] ERROR: Could not find a valid next slide' 1>&2
		echo '[dvd-slideshow]        This happens when a fade cannot locate a future image in your .txt file' 1>&2
		echo '[dvd-slideshow]	     Fix this in your input file and re-run dvd-slideshow.' 1>&2
		function_error=1
	fi
}

titlebarslide ()
# titlebarslide $title1 $title2 $output_filename $background_file
{
	## $1 contains the head title, and $2 contains the sub-title
	local title1="$1"
	local title2="$2"
	if [ -n "$3" ] ; then
		local output_file="$3"
	else
		local output_file="$tmpdir/title.ppm"  # default
	fi
	if [ -n "$4" ] && [ -f "$4" ] ; then
		local bg="$4"
	else
		local bg="$tmpdir"/slideshow_background.ppm # default
	fi
	rm -f "$output_file"

	# figure out actual coordinates:
	if [ "$low_quality" -eq 1 ] || [ "$vcd" -eq 1 ] || [ "$output_format" == 'flv' ] || [ "$output_format" == 'swf' ] || [ "$output_format" == 'mpg' ] || [ "$output_format" == 'mp4_ipod' ] || [ "$output_format" == 'mp4' ] || [ "$output_format" == 'ogv' ] ; then
		## top title:
		local f_toptitle_font_size=$(( $toptitle_font_size * $dvd_height / 480 ))
		local f_toptitle_bar_height=$(( $toptitle_bar_height * $dvd_height / 480 ))
		local f_toptitle_text_location_x=$(( $toptitle_text_location_x * $dvd_height / 480 ))
		local f_toptitle_text_location_y=$(( $toptitle_text_location_y * $dvd_height / 480 ))
		# bottom title:
		local f_bottomtitle_font_size=$(( $bottomtitle_font_size * $dvd_height / 480 ))
		local f_bottomtitle_bar_location_y=$(( $bottomtitle_bar_location_y * $dvd_height / 480 ))
		local f_bottomtitle_bar_height=$(( $bottomtitle_bar_height * $dvd_height / 480 ))
		local f_bottomtitle_text_location_x=$(( $bottomtitle_text_location_x * $dvd_height / 480 ))
		local f_bottomtitle_text_location_y=$(( $bottomtitle_text_location_y * $dvd_height / 480 ))
		# subtitle:
		local f_subtitle_location_x=$(( $subtitle_location_x * $dvd_height / 480 ))
		local f_subtitle_location_y=$(( $subtitle_location_y * $dvd_height / 480 ))
	elif [ "$svcd" -eq 1 ] ; then  # x-resolution is 480x480 (ntsc) or 480x576 (pal)
		## top title:
		local f_toptitle_font_size=$(( $toptitle_font_size ))
		local f_toptitle_bar_height=$(( $toptitle_bar_height ))
		local f_toptitle_text_location_x=$(( $toptitle_text_location_x / 3 ))
		local f_toptitle_text_location_y=$(( $toptitle_text_location_y ))
		# bottom title:
		local f_bottomtitle_font_size=$(( $bottomtitle_font_size ))
		local f_bottomtitle_bar_location_y=$(( $bottomtitle_bar_location_y ))
		local f_bottomtitle_bar_height=$(( $bottomtitle_bar_height ))
		local f_bottomtitle_text_location_x=$(( $bottomtitle_text_location_x / 3 ))
		local f_bottomtitle_text_location_y=$(( $bottomtitle_text_location_y ))
		# subtitle:
		local f_subtitle_location_x=$(( $subtitle_location_x * $dvd_height / 480 ))
		local f_subtitle_location_y=$(( $subtitle_location_y * $dvd_height / 480 ))
	else
		local f_toptitle_font_size=$(( $toptitle_font_size ))
		local f_toptitle_bar_height=$(( $toptitle_bar_height ))
		local f_toptitle_text_location_x=$(( $toptitle_text_location_x ))
		local f_toptitle_text_location_y=$(( $toptitle_text_location_y ))
		# bottom title:
		local f_bottomtitle_font_size=$(( $bottomtitle_font_size ))
		local f_bottomtitle_bar_location_y=$(( $bottomtitle_bar_location_y ))
		local f_bottomtitle_bar_height=$(( $bottomtitle_bar_height ))
		local f_bottomtitle_text_location_x=$(( $bottomtitle_text_location_x ))
		local f_bottomtitle_text_location_y=$(( $bottomtitle_text_location_y ))
		# subtitle:
		local f_subtitle_location_x=$(( $subtitle_location_x ))
		local f_subtitle_location_y=$(( $subtitle_location_y ))
	fi
	## now the title2 y-locations were specified relative to the bottom of the image
	## but imagemagick needs them relative to the top of the image:
	f_bottomtitle_bar_location_y=$(( $dvd_height - $f_bottomtitle_bar_location_y ))
	f_bottomtitle_text_location_y=$(( $dvd_height - $f_bottomtitle_text_location_y ))
	local title2_bgtop=$f_bottomtitle_bar_location_y
	local title2_bgbot=$(( $f_bottomtitle_bar_location_y + $f_bottomtitle_bar_height ))

	if [ -z "$title1" ] && [ -z "$title2" ] ; then
		myecho "[dvd-slideshow] ERROR: No title text was found. Syntax:"
		myecho "[dvd-slideshow]        titlebar:duration:TopTitle:BottomTitle"
		cleanup; exit 1
	fi
	rm -f "$tmpdir/title1.png"

	if [ -n "$title1" ] ; then  # title1 exists
		if [ "$f_toptitle_bar_height" -ne 0 ] ; then
			convert -size "$dvd_width"x"$dvd_height" xc:transparent -fill white \
		       	-draw "Rectangle 0,0,$dvd_width,$f_toptitle_bar_height" miff:- | \
			composite -compose src-over -type TrueColorMatte -depth 8 -dissolve 50 - \
			"$bg" "$tmpdir/slide_$i.png"	
		else
			convert "$bg" -type TrueColorMatte -depth 8 "$tmpdir/slide_$i.png"
		fi
		convert -size "$dvd_width"x"$dvd_height" xc:transparent -fill "$toptitle_font_color" \
		-pointsize "$f_toptitle_font_size" -gravity NorthWest -font "$title_font" \
		-draw "text $f_toptitle_text_location_x,$f_toptitle_text_location_y \"${title1}\"" miff:- | \
		composite -compose src-over -type TrueColorMatte -depth 8 - \
		"$tmpdir/slide_$i.png" "$tmpdir/title1.png"
		convert "$tmpdir/title1.png" -type TrueColorMatte -depth 8 "$output_file"
	fi
	if [ -n "$title2" ] ; then # title2 exists
		if [ "$f_bottomtitle_bar_height" -ne 0 ] ; then
			convert -size "$dvd_width"x"$dvd_height" xc:transparent -fill white -quality 100\
			-draw "Rectangle 0,$title2_bgtop,$dvd_width,$title2_bgbot" -type TrueColorMatte -depth 8 "$tmpdir/title_background.png"
		else
			convert -size "$dvd_width"x"$dvd_height" xc:transparent -type TrueColorMatte -depth 8 "$tmpdir/title_background.png"
		fi
		if [ -f "$tmpdir/title1.png" ] ; then # use title1 image
			composite -compose src-over -type TrueColorMatte -depth 8 -dissolve 50 -quality 100 "$tmpdir/title_background.png" "$tmpdir/title1.png" "$tmpdir/slide_$i.png"	
		else  # use background image (no first title)
			composite -compose src-over -type TrueColorMatte -depth 8 -dissolve 50 -quality 100 "$tmpdir/title_background.png" "$bg" "$tmpdir/slide_$i.png"	
		fi
		convert -size "$dvd_width"x"$dvd_height" xc:transparent -fill "$bottomtitle_font_color" \
			-pointsize "$f_bottomtitle_font_size" -gravity North -font "$title_font" \
			-draw "text $f_bottomtitle_text_location_x,$f_bottomtitle_text_location_y \"${title2}\"" -type TrueColorMatte -depth 8 miff:- | \
		composite -compose src-over -type TrueColorMatte -depth 8 - \
			"$tmpdir/slide_$i.png" "$output_file"
	fi
	rm -f "$tmpdir/title1.png"
}

titleslide ()
{
# titleslide $title $output_filename $background
	title="$1"
	if [ -z "$title" ] ; then
		myecho "[dvd-slideshow] ERROR: No title text was found. Syntax:"
		myecho "[dvd-slideshow]        title:duration:Title_text"
		cleanup; exit 1
	fi
	if [ -n "$2" ] ; then
		local output_file="$2"
	else
		local output_file="$tmpdir/title.ppm"
	fi
	if [ -n "$3" ] && [ -f "$3" ] ; then
		local bg="$3"
	else
		local bg="$tmpdir"/slideshow_background.ppm
	fi
	rm -f "$output_file"

	if [ "$low_quality" -eq 1 ] || [ "$vcd" -eq 1 ] || [ "$output_format" == 'flv' ] || [ "$output_format" == 'swf' ] || [ "$output_format" == 'mp4_ipod' ] || [ "$output_format" == 'mp4' ] || [ "$output_format" == 'mpg' ]|| [ "$output_format" == 'ogv' ] ; then
		local f_title_font_size=$(( $title_font_size * $dvd_height / 480 ))
	else
		local f_title_font_size=$(( $title_font_size ))
	fi
	## if background is black and font color is black, change font color to white
	if [ "$bgfile" == 'black' ] && [ "$title_font_color" == 'black' ] ; then
		title_font_color='white'
	fi

#		it=`echo "${subtitle[$i]}" | awk -F'\\' '{print $2}' | cut -c 1`
#		if [ "$it" == 'n' ] ; then
	## check to see if we find any user-specified breaks \n
	it=`echo "$title" | awk -F'\\' '{print $2}' | cut -c 1`
	if [ "$it" == 'n' ] ; then
		logecho "[dvd-slideshow] Found \\n in title"
		# user entered a \n to force line wraps
		# break lines at line wraps
		title1=`echo "${title}" | awk -F'\\' '{print $1}'`
		title2=`echo "${title}" | awk -F'\\' '{print $2}' | cut -c 2-`
		title3=`echo "${title}" | awk -F'\\' '{print $3}' | cut -c 2-`
		title4=`echo "${title}" | awk -F'\\' '{print $4}' | cut -c 2-`

		convert -size "$dvd_width"x"$dvd_height" xc:transparent -fill $title_font_color \
		-pointsize $f_title_font_size -gravity Center -font "$title_font" -annotate 0 "$title1\n$title2\n$title3\n$title4" -type TrueColorMatte -depth 8 miff:- | \
		composite -compose src-over -type TrueColorMatte -depth 8 - "$bg" "$output_file"
	else	# no forced line wraps. Eventually Check for long lines
		convert -size "$dvd_width"x"$dvd_height" xc:transparent -fill $title_font_color \
		-pointsize $f_title_font_size -gravity Center -font "$title_font" -draw "text 0,0 \"${title}\"" -type TrueColorMatte -depth 8 miff:- | \
		composite -compose src-over -type TrueColorMatte -depth 8 - "$bg" "$output_file"
	fi
}

musictitleslide ()
{
# musictitleslide $Title $Artist $Album $output_file $background_file
		local Title="$( echo $1 | sed -e 's/\\#/#/g' )"
		local Artist="$( echo $2 | sed -e 's/\\#/#/g' )"
		local Album="$( echo $3 | sed -e 's/\\#/#/g' )"
		# draw text:
		if [ -n "$4" ] ; then
			local output_file="$4"
		else
			local output_file="$tmpdir/title.ppm"
		fi
		if [ -n "$5" ] && [ -f "$5" ] ; then
			local bg="$5"
		else
			local bg="$tmpdir"/slideshow_background.ppm
		fi
		rm -f "$output_file"
		if [ "$low_quality" -eq 1 ] || [ "$vcd" -eq 1 ] || [ "$output_format" == 'flv' ] || [ "$output_format" == 'swf' ] || [ "$output_format" == 'mp4_ipod' ] || [ "$output_format" == 'mp4' ] || [ "$output_format" == 'mpg' ]|| [ "$output_format" == 'ogv' ] ; then
			f_subtitle_font_size=$(( $subtitle_font_size * $dvd_height / 480 ))
			convert -size $dvd_width"x"$dvd_height xc:transparent \
			-pointsize "$f_subtitle_font_size" -gravity SouthWest -font "$title_font" \
			-draw "fill white text 40,100 \"$Title\"" \
			-draw "fill white text 40,75 \"$Artist\"" \
			-draw "fill white text 40,50 \"$Album\"" -quality 100 -type TrueColorMatte -depth 8 "$tmpdir/mytitle.png"
		else  # medium or high quality
			f_subtitle_font_size=$(( $subtitle_font_size ))
			convert -size $dvd_width"x"$dvd_height xc:transparent \
			-pointsize "$f_subtitle_font_size" -gravity SouthWest -font "$title_font" \
			-draw "fill white text 80,200 \"$Title\"" \
			-draw "fill white text 80,150 \"$Artist\"" \
			-draw "fill white text 80,100 \"$Album\"" -quality 100 -type TrueColorMatte -depth 8 "$tmpdir/mytitle.png"
		fi
		composite -compose src-over -type TrueColorMatte -depth 8 "$tmpdir/mytitle.png" "$bg" "$output_file"
		rm -f "$tmpdir"/mytitle.png
}

checkforautocrop ()
{
	if [ "$autocrop" -eq 1 ] ; then
		# figure out whether to autocrop the image or not
	        image_width=`imagewidth "$1"`
	        image_height=`imageheight "$1"`
	        ratio="$(( 100* $image_width / $image_height ))"
	        out_ratio="$(( 100* $dvd_width / $dvd_height ))"
		do_autocrop_w=0 ; do_autocrop_h=0
		out_ratio_plus=$(( $out_ratio + 30 ))
		out_ratio_minus=$(( $out_ratio - 30 ))
		if [ "$ratio" -gt $out_ratio_minus ] && [ $ratio -lt $out_ratio_plus ]; then
			## if ratio is +/- 30 from output ratio 
			if [ "$ratio" -lt "$(( $out_ratio ))" ] ; then
				do_autocrop_h=1 # image too wide, crop height
			elif [ "$ratio" -gt "$(( $out_ratio ))" ] ; then
				do_autocrop_w=1 # image too tall, crop width
			fi
		fi
		[ $debug -ge 3 ] && myecho "[dvd-slideshow:checkforautocrop] image_width=$image_width image_height=$image_height ratio=$ratio out_ratio=$out_ratio"
		[ $debug -ge 3 ] && myecho "[dvd-slideshow:checkforautocrop] do_autocrop_w=$do_autocrop_w  do_autocrop_h=$do_autocrop_h"
	else
		do_autocrop_h=0 ; do_autocrop_w=0
	fi
}

background () # BACKGROUND
{
		## input is:  $1 = effect/image
		# output is written to "$tmpdir"/slideshow_background.ppm 
		bg="$1"
		if [ -f "$bg" ] ; then # if effect is a background file
			myecho "[dvd-slideshow] Creating background $( truncate_filename "$bg")"
			checkforautocrop "$bg"
                       if [ "$do_autocrop_w" -eq 1 ]; then   
                               # autocrop background image width (width too large)
                               convert "${bg}" -filter $filtermethod \
						-resize "$sq_to_dvd_pixels" \
						-resize x"$dvd_height" \
                               			-gravity center \
						-crop "$dvd_width"x"$dvd_height"'+0!+0!' \
						-type TrueColorMatte -depth 8 \
						"$tmpdir"/slideshow_background.ppm
                       elif [ "$do_autocrop_h" -eq 1 ]; then
                               # autocrop background image height (height too large)
                               convert "${bg}" -filter $filtermethod \
						-resize "$sq_to_dvd_pixels" \
						-resize "$dvd_width"x \
                               			-gravity center \
						-crop "$dvd_width"x"$dvd_height"'+0!+0!' \
						-type TrueColorMatte -depth 8 \
						"$tmpdir"/slideshow_background.ppm
                       else
                               #don't autorop
                               convert "${bg}" -filter $filtermethod \
						-resize "$sq_to_dvd_pixels" \
						-resize x"$dvd_height" \
						-bordercolor black \
						-border "$dvd_width"x240 \
                               			-gravity center \
						-crop "$dvd_width"x"$dvd_height"'+0!+0!' \
						-type TrueColorMatte -depth 8 \
						"$tmpdir"/slideshow_background.ppm
                       fi
			bgfile="$bg"
		elif [ "$bg" == 'black' ] ; then  # I guess we could add other types of backgrounds here!
			## use plain black background with no picture
			myecho "[dvd-slideshow] Creating black background"
			convert -size "$dvd_width"'x'"$dvd_height" xc:black -type TrueColorMatte -depth 8 "$tmpdir"/slideshow_background.ppm
			bgfile="black"
		elif [ "$bg" == 'white' ] ; then  # I guess we could add other types of backgrounds here!
			## use plain white background with no picture
			myecho "[dvd-slideshow] Creating white background"
			convert -size "$dvd_width"'x'"$dvd_height" xc:white -type TrueColorMatte -depth 8 "$tmpdir"/slideshow_background.ppm
			bgfile="white"
		elif [ "${bg:0:1}" == '#' ] ; then  # user passed a #RRGGBB hex color
			myecho "[dvd-slideshow] Creating $bg color background"
			convert -size "$dvd_width"'x'"$dvd_height" xc:"$bg" -type TrueColorMatte -depth 8 "$tmpdir"/slideshow_background.ppm
			bgfile="hex"
		else
			myecho "[dvd-slideshow] ERROR: No background file specified!"
			myecho "[dvd-slideshow] 	Correct syntax is:"
			myecho "[dvd-slideshow] background:duration:subtitle:background_image_or_color"
			exit 1
		fi
#		convert "$normal_bg" -type TrueColorMatte -depth 8 "$tmpdir/slideshow_background.mpc"
}

coordinates_in_dvd_aspect_ratio_frame ()
{
	# dvd_width dvd_height image_width image_height x_coordinate y_coordinate
	#dvd_width=$1; dvd_height=$2
	#image_width=$3; image_height=$4
	#x_image_coordinate=$5 y_image_coordinate=$6
	# output: x_dvd_coordinate y_dvd_coordinate

	## calculate frame size after adding black side bars for portrait pictures:
	ratio=$(( 1000* $3 / $4 ))
	out_ratio=$(( 1000* $1 / $2 ))  
	if [ "$ratio" -gt "$(( $out_ratio ))" ] ; then
		# image width greater than output width at same scale
		new_image_width=$3
		new_image_height=`div10 $(( 10* $2 * $3 / $1 ))`
		x_dvd_coordinate=0
		y_dvd_coordinate=`div10 $(( 10*( $new_image_height - $4 ) / 2 ))`
	elif [ "$ratio" -le $(( $out_ratio )) ] ; then
		# image height greater than output height at same scale 
		new_image_width=`div10 $(( 10* $1 * $4 / $2 ))`
		new_image_height=$4
		y_dvd_coordinate=0
		x_dvd_coordinate=`div10 $(( 10*( $new_image_width - $3 ) / 2 ))`
	fi
	# calculate coordinate transformation by xi,yi
#	x_dvd_coordinate=$(( $x_image_coordinate - $xi ))
#	y_dvd_coordinate=$(( $y_image_coordinate - $yi ))
}

parse_window ()  # PARSE_WINDOW
# parse_window $
{
	# pass a string $1 (kenburns start or end arguments)

	# xi,yi is the top left corner of the image relative to the frame
	# xw,yh are the width and height of the crop (must be even numbers)
	# x0,y0 is the top left corner of the crop in the image frame.
	# x1,y1 is the bottom right corner of the crop in the image frame.
	# textfile format is:  
	# file:duration:comment:kenburns:xs0,ys0;xs1,ys1;xe0,ye0;xe1,ye1;[startangle,endangle]
	# or
	# file:duration:comment:kenburns:start 0%-100%;start_location;end 0%-100%;end_location;[startangle,endangle]
	# where 0%-100% indicates the fraction of the window width/height, and
	# where start_location and end_location can be:
	# 	topleft			topmiddle|top		topright
	#	middleleft|left		middle			middleright|right
	#	bottomleft		bottommiddle|bottom	bottomright
	# or
	# 	x%,y%
	#	where % is a percentage of the window width/height starting from the
	# 	top left corner of the screen.
	# or
	# 	imagewidth | imageheight
	#	where the window width or height will be scaled to fill the full
	#	width or height of the dvd screen.
	#	
	# ( angles not implemented yet! )
	# and the optional startangle,endangle parameters will allow for rotation of the image during
	# the kenburns effect. Startangle is optional, and if omitted, will default to zero.
	# Positive numbers denote clockwise rotation, and negative numbers denote counter-clockwise rotation.
	# 

	it=`echo "$1" | awk -F';' '{print $1}' | awk -F% '{print NF}'`
	firstarg=`echo "$1" | awk -F';' '{print $1}'`
	image_width="`imagewidth "$2"`"   # returns non-square image size
	image_height="`imageheight "$2"`"
	## calculate frame size after adding black side bars for portrait pictures:
	ratio=$(( 1000* $image_width / $image_height ))
	out_ratio=$(( 1000* $frame_width / $frame_height ))  # doesn't change during script
	[ $debug -ge 3 ] && myecho "[dvd-slideshow:parse_window] image_width=$image_width image_height=$image_height ratio=$ratio out_ratio=$out_ratio"
	if [ "$ratio" -gt "$out_ratio" ] ; then
		# image width greater than output width at same scale
		new_image_width=$image_width
		new_image_height=`div10 $(( 10* $frame_height * $image_width / $frame_width ))`
		xi=0  # will need to add frame border later...
		yi=`div10 $(( 10*( $new_image_height - $image_height ) / 2 ))`
	elif [ "$ratio" -le $out_ratio ] ; then
		# image height greater than output height at same scale 
		new_image_width=`div10 $(( 10* $frame_width * $image_height / $frame_height ))`
		new_image_height=$image_height
		yi=0 # will need to add frame border later...
		xi=`div10 $(( 10*( $new_image_width - $image_width ) / 2 ))`
	fi
	[ $debug -ge 3 ] && myecho "[dvd-slideshow:parse_window] new_image_width=$new_image_width new_image_height=$new_image_height xi=$xi yi=$yi"
	if [ "$it" -eq 2 ] || [ "$firstarg" == 'imagewidth' ] || [ "$firstarg" == 'imageheight' ] ; then 
		## use "keywords"
		## first parse the zoom amount:
		loc=`echo "$1" | awk -F';' '{print $2}'`
		if [ "$firstarg" == 'imagewidth' ] ; then 
			# scale width to equal output dvd width:
			xw=$image_width
			yh=`div10 $(( 10 * $frame_height * $xw / $frame_width ))`
		elif [ "$firstarg" == 'imageheight' ] ; then 
			# scale height to equal output dvd width:
			yh=$image_height
			xw=`div10 $(( 10 *$frame_width * $yh / $frame_height ))`
		else
			## this needs to be in the non-square pixel frame, hence the
			## resize_factor
			zoom_percent=`echo "$1" | awk -F';' '{print $1}' | awk -F% '{print $1}'`
			[ $debug -ge 3 ] && myecho "[dvd-slideshow:parse_window] zoom=$zoom_percent, loc=$loc "
			## need to make the largest dimension smaller, and then scale the
			## other dimension to the correct aspect ratio!
			if [ "$ratio" -gt "$out_ratio" ] ; then
				# image width greater than output width at same scale
				# take percentage of width and calculate height:
				xw=`div10 $(( 10 * $new_image_width * $zoom_percent / 100 ))`
				yh=`div10 $(( 10 * $frame_height * $xw / $frame_width ))`
#				yh=`div10 $(( 10 * $new_image_height * $zoom_percent / 100 ))`
			elif [ "$ratio" -le $out_ratio ] ; then
				# image height greater than output height at same scale 
				# take percentage of height and calculate width:
#				xw=`div10 $(( 10 * $new_image_width * $zoom_percent / 100 ))`
				yh=`div10 $(( 10 * $new_image_height * $zoom_percent / 100 ))`
				xw=`div10 $(( 10 *$frame_width * $yh / $frame_height ))`
			fi
		fi
		## next line is because we want the zoom % coordinates to be relative to the
		## whole screen size, so if you have a tall, narrow picture, 50% will mean
		## half of the height, etc...	
		# now, calculate the actual coordinates:
		[ $debug -ge 3 ] && myecho "[dvd-slideshow:parse_window] xw=$xw yh=$yh"

		## middle calculations are for using the "middle" keywords:
		ymiddle0=`div10 $(( 10 *$new_image_height / 2 - 10 *$yh / 2 ))`
		ymiddle1=`div10 $(( 10 *$new_image_height / 2 + 10 *$yh / 2 ))`
		xmiddle0=`div10 $(( 10 *$new_image_width / 2 - 10 *$xw / 2 ))`
		xmiddle1=`div10 $(( 10 *$new_image_width / 2 + 10 *$xw / 2 ))`
		[ $debug -ge 3 ] && myecho "[dvd-slideshow:parse_window] ymiddle0=$ymiddle0 ymiddle1=$ymiddle1  xmiddle0=$xmiddle0 xmiddle1=$xmiddle1"

		## now parse the box location:
		it=`echo "$1" | awk -F';' '{print $2}' | awk -F% '{print NF}'`
		if [ "$it" -ge 2 ] ; then # second arg contains a %
			# location is specified a a percent of the window size
			xcenter_pct=`echo "$1" | awk -F';' '{print $2}' | awk -F',' '{print $1}' | awk -F% '{print $1}'`
			ycenter_pct=`echo "$1" | awk -F';' '{print $2}' | awk -F',' '{print $2}' | awk -F% '{print $1}'`
#			[ $debug -ge 3 ] && myecho "[dvd-slideshow] xcenter_pct=$xcenter_pct ycenter_pct=$ycenter_pct"
			[ -z "$xcenter_pct" ] && (myecho '[dvd-slideshow] Error: bad xcenter percentage' ; cleanup; exit 1)
			[ -z "$ycenter_pct" ] && (myecho '[dvd-slideshow] Error: bad ycenter percentage' ; cleanup; exit 1)
			xcenter=$(( 10 * $new_image_width * $xcenter_pct / 100 ))
			ycenter=$(( 10 * $new_image_height * $ycenter_pct / 100 ))
			[ $debug -ge 3 ] && myecho "[dvd-slideshow:parse_window] xcenter=$xcenter ycenter=$ycenter"
#			x0=`div10 $(( $xcenter - 10 * $xw / 2 ))`; x1=$(( $xcenter + $xw / 2 ))
#			y0=`div10 $(( $ycenter - 10 * $yh / 2 ))`; y1=$(( $ycenter + $yh / 2 ))
			x0=`div10 $(( $xcenter - 10 * $xw / 2 ))`; x1=$(( $x0 + $xw ))
			y0=`div10 $(( $ycenter - 10 * $yh / 2 ))`; y1=$(( $y0 + $yh ))
			[ $debug -ge 3 ] && echo "[dvd-slideshow:parse_window] x0=$x0 y0=$y0  x1=$x1 y1=$y1  xi=$xi yi=$yi"
		elif [ "$loc" == 'topleft' ] ; then
			x0=0; x1=$xw
			y0=0; y1=$yh
		elif [ "$loc" == 'middleleft' ] || [ "$loc" == 'left' ] ; then
			x0=0; x1=$xw
			y0=$ymiddle0; y1=$ymiddle1
		elif [ "$loc" == 'bottomleft' ] ; then
			x0=0; x1=$xw
			y0=$(( $new_image_height - $yh )) ; y1=$new_image_height
		elif [ "$loc" == 'topmiddle' ] || [ "$loc" == 'top' ] ; then
			x0=$xmiddle0; x1=$xmiddle1
			y0=0; y1=$yh
		elif [ "$loc" == 'middle' ] || [ "$loc" == 'center' ] ; then
			x0=$xmiddle0; x1=$xmiddle1
			y0=$ymiddle0; y1=$ymiddle1
		elif [ "$loc" == 'bottommiddle' ] || [ "$loc" == 'bottom' ] ; then
			x0=$xmiddle0; x1=$xmiddle1
			y0=$(( $new_image_height - $yh )) ; y1=$new_image_height
		elif [ "$loc" == 'topright' ] ; then
			x0=$(( $new_image_width - $xw )) ; x1=$new_image_width
			y0=0; y1=$yh
		elif [ "$loc" == 'middleright' ] || [ "$loc" == 'right' ] ; then
			x0=$(( $new_image_width - $xw )) ; x1=$new_image_width
			y0=$ymiddle0; y1=$ymiddle1
		elif [ "$loc" == 'bottomright' ] ; then
			x0=$(( $new_image_width - $xw )) ; x1=$new_image_width
			y0=$(( $new_image_height - $yh )) ; y1=$new_image_height
		else	
			myecho "[dvd-slideshow] Error: bad syntax in kenburns/crop location: $loc"
			cleanup; exit 1
		fi
	else  # check for original format with explicit start/end coordinates:
		## coordinate system is relative to the actual picture, unscaled, 
		## in square pixel frame!!!
		## we need to convert this to the buffered (dvd aspect ratio) 
		## and non-square pixel coordinate system!!!	
#	myecho "[dvd-slideshow:parse_window] numbered or explicit coorinates"
		x0=`echo "$1" | awk -F';' '{print $1}' | awk -F',' '{print $1}'`
		y0=`echo "$1" | awk -F';' '{print $1}' | awk -F',' '{print $2}'`
		x1=`echo "$1" | awk -F';' '{print $2}' | awk -F',' '{print $1}'`
		y1=`echo "$1" | awk -F';' '{print $2}' | awk -F',' '{print $2}'`
		[ $debug -ge 3 ] && echo "[dvd-slideshow:parse_window] x0=$x0 y0=$y0  x1=$x1 y1=$y1  xi=$xi yi=$yi"
		if [ -z "$y1" ] ; then
			myecho "[dvd-slideshow] ERROR: Incorrect coordinates. You probably got the syntax wrong:"
			myecho "[dvd-slideshow] image.jpg:duration:subtitle:crop:x0,y0;x1,y1"
			myecho "[dvd-slideshow] image.jpg:duration:subtitle:kenburns:xs0,ys0;xs1,ys1;xe0,ye0;xe1,ye1"
			exit 1
		fi

		## we also need to convert the x coordinates to the dvd aspect (non-square) pixel coordinates:
		x0="$(printf %5.0f $(echo "scale=5; $x0 * $resize_factor / 100" | bc) )"
		x1="$(printf %5.0f $(echo "scale=5; $x1 * $resize_factor / 100" | bc) )"
		[ $debug -ge 3 ] && echo "[dvd-slideshow:parse_window] x0=$x0 y0=$y0  x1=$x1 y1=$y1  xi=$xi yi=$yi"

		# xi,yi already calculated
		# now, the size of the image frame should be new_image_width x new_image_height
		# This mode assumes the image is placed in the center of the dvd window to start.
		
		# width and height of area passed:
		xw=$(( ( $x1 - $x0 ) )) ; yh=$(( $y1 - $y0 ))

		## make sure the image crop coordinates are not outside the image:
		[ $xi -eq 0 ] && x0=$x0 || x0=$(( $x0 + $xi ))
		[ $xi -eq 0 ] && x1=$x1 || x1=$(( $x1 + $xi ))
		[ $yi -eq 0 ] && y0=$y0 || y0=$(( $y0 + $yi ))
		[ $yi -eq 0 ] && y1=$y1 || y1=$(( $y1 + $yi ))
	fi
	[ $debug -ge 2 ] && echo "[dvd-slideshow:parse_window] x0=$x0 y0=$y0  x1=$x1 y1=$y1  xi=$xi yi=$yi"
}

is_even ()
{
	# returns 0 or 1 depending on wether the number is even or not
	number=$1
	fraction=`expr $number % 2`
	if [ $fraction -eq 0 ] ; then
		echo "1"
	else
		echo "0"
	fi
}


todec000 ()
{
	factor_whole=$(( $1 / 1000 ))
	factor_dec=$(( $1 % 1000 ))
	if [ $factor_dec -lt 0 ] ; then
		factor_dec=$(( -1 * $factor_dec ))
	fi
	if [ ${#factor_dec} -eq 2 ] ; then
		factor_dec="0$factor_dec"
	elif [ ${#factor_dec} -eq 1 ] ; then
		factor_dec="00$factor_dec"
	elif [ ${#factor_dec} -eq 0 ] ; then
		factor_dec="000"
	fi
	echo "$factor_whole.$factor_dec"
}

div1000 ()
{
	# takes a number and divides by 1000, rounding appropriately
	number=$1
	whole=`expr $number / 1000`
	fraction=`expr $number % 1000`
	if [ $fraction -ge 500 ] ; then
		whole=$(( $whole + 1 ))  # round up
	fi
	echo $whole
}

div1000_2 ()
{
	# takes a number and divides by 1000, rounding to the nearest factor of 2
	number=$1
	whole=`expr $number / 2000`
	fraction=`expr $number % 2000`
	if [ $fraction -ge 1000 ] ; then
		whole=$(( 2* $whole + 2 ))  # round up
	else
		whole=$(( 2* $whole ))
	fi
	echo $whole
}

div1000_up ()
{
	# takes a number and divides by 1000, rounding up
	number=$1
	whole=`expr $number / 1000`
	fraction=`expr $number % 1000`
	if [ $fraction -ge 1 ] ; then
		whole=$(( $whole + 1 ))  # round up
	else
		whole=$(( $whole ))
	fi
	echo $whole
}

div10 ()
{
	# takes a number and divides by 10, rounding appropriately
	number=$1
	whole=`expr $number / 10`
	fraction=`expr $number % 10`
	if [ $fraction -ge 5 ] ; then
		whole=$(( $whole + 1 ))  # round up
	fi
	echo $whole
}

imagewidth ()  # IMAGEWIDTH
{
	it="`identify -format %w "$1"`"
	it="$(printf %5.0f $(echo "scale=5; $it * $resize_factor / 100" | bc) )"
	echo "$it"
}

imagewidth_sq ()  # IMAGEWIDTH_SQ
{
	#it="`identify -format %w "$1"`"
	identify -format "%w\n" "$1"
#	echo "$it"
}


imageheight ()
{
	#it="`identify -format %h "$1"`"
	identify -format "%h\n" "$1"
	#echo "$it"
}

crop_parameters () # CROP_PARAMETERS image_width image_height frame_width frame_height x0 y0 x1 y1
{
	# converts the crop parameters reference in the full dvd aspect ratio
	# frame back to the actual crop parameters needed in the original 
	# image frame.
	#
	# the input coordinates are relative to the original image size, buffered out to
	# the output dvd aspect ratio
	#	
	# using the parameters x0,y0 ; x1,y1 ; xi,yi in memory (x1000)
	# output is just the crop parameters:
	# c_width, c_height xc0,yc0  (for the actual crop)
	# and for the corresponding composite command:
	# xci,yci for the location of the top left corner of the cropped image
	# relative to the output window.
	#
	# top left corner of dvd window is 0,0
	# top left corner of image is at xi,yi   from parse_window
	# top left corner of the cropped image is at x0,y0
	#
	# i.e., the "i" reference frame is in the unbuffered image (image alone)
	
	##############################################
	## figure out the size of the window scaled to the original image size:
	ratio=$(( 1000* $image_width / $image_height ))
	out_ratio=$(( 1000* $frame_width / $frame_height ))  # doesn't change during script
	#[ $debug -ge 3 ] && myecho "[dvd-slideshow:crop_parameters] input: x0=`todec000 $x0` y0=`todec000 $y0` x1=`todec000 $x1` y1=`todec000 $y1`     xi=$xi yi=$yi (dvd window)"
	[ $debug -ge 3 ] && myecho "[dvd-slideshow:crop_parameters] input: x0=$x0 y0=$y0 x1=$x1 y1=$y1  xi=$xi yi=$yi (dvd window)"

	##############################################
	## shift coordinate system to start at xi,yi: (all integers)
	## xi,yi should already include the border
	xi0=$(( 1000*$x0- 1000*$xi )); yi0=$(( 1000*$y0- 1000*$yi )) # already x1000
	xi1=$(( 1000*$x1- 1000*$xi )); yi1=$(( 1000*$y1- 1000*$yi )) # already x1000
	w=$(( $xi1 - $xi0 )) # already x1000
	h=$(( $yi1 - $yi0 ))	 # already x1000
	[ $debug -ge 3 ] && myecho "[dvd-slideshow:crop_parameters] xi0,yi0=`todec000 $xi0`,`todec000 $yi0` xi1,yi1=`todec000 $xi1`,`todec000 $yi1`   w=`todec000 $w` h=`todec000 $h`  ratio=`todec000 $ratio` out_ratio=`todec000 $out_ratio` (i=image ref frame)"

	##############################################
	## figure out where to crop the image:
	## (make sure the image crop coordinates are not outside the image)
	[ $xi0 -lt 0 ] && xc0=0 || xc0=$xi0 
	[ $xi1 -gt "$(( 1000 * $image_width ))" ] && xc1=$(( 1000 * $image_width )) || xc1=$xi1
	[ $yi0 -lt 0 ] && yc0=0 || yc0=$yi0
	[ $yi1 -gt "$(( 1000 * $image_height ))" ] && yc1=$(( 1000 * $image_height )) || yc1=$yi1
	c_width=$(( $xc1 - $xc0 )) ; c_height=$(( $yc1 - $yc0 )) # already x1000
	crop_ratio=$(( 1000 * $c_width / $c_height ))  
	[ $debug -ge 3 ] && myecho "[dvd-slideshow:crop_parameters] xc0,yc0=`todec000 $xc0`,`todec000 $yc0` xc1,yc1=`todec000 $xc1`,`todec000 $yc1`   c_width=`todec000 $c_width` c_height=`todec000 $c_height`   crop_ratio=$crop_ratio (crop params in image fr)"

	##############################################
	## where to put the top left corner of the cropped image relative to the background?
	deltax=$(( 1000 * 1000 * $frame_width / $c_width )); deltay=$(( 1000 * 1000 * $frame_height / $c_height ))
	## rescale % will be the smaller of the two deltas: 
	[ $deltax -lt $deltay ] && rescale=$deltax || rescale=$deltay # already x1000
# myecho "[dvd-slideshow:crop_parameters] deltax=$deltax deltay=$deltay rescale=$rescale xi0=$xi0 yi0=$yi0 xi0=$xi0 yi0=$yi0"
	if [ $xi0 -lt 0 ] ; then
		## left of cropped image is in the middle of the dvd window
		xci=`div1000 $(( $rescale * -1 * $xi0 ))`
#		xci=$(( $rescale * -1 * $xi0 / 1000 ))
		[ "$xci" -ge 1 ] && xci=$(( $xci - 1 ))
	else
		## left of cropped image should be at x=0 afterward
		xci=0
	fi
	if [ $yi0 -lt 0 ] ; then  ###*  rescale=deltax
		## top of cropped image is in the middle of the dvd window
		yci=`div1000 $(( $rescale * -1 * $yi0 ))`
		[ "$yci" -ge 1 ] && yci=$(( $yci - 1 ))
	else
		## top of cropped image should be at y=0 afterward
		yci=0
	fi
	[ $debug -ge 3 ] && myecho "[dvd-slideshow:crop_parameters] xci,yci=`todec000 $xci`,`todec000 $yci`  c_width,c_height=`todec000 $c_width`,`todec000 $c_height` (location of cropped image in dvd window)"

	c_width=`div1000 $(( $xc1 - $xc0 ))` ; c_height=`div1000 $(( $yc1 - $yc0 ))`

#	echo "[dvd-slideshow:crop_parameters] crop_ratio=$crop_ratio out_ratio=$out_ratio"
	if [ "$crop_ratio" -gt $out_ratio ] ; then
		# image width greater than output width at same scale
		resized_width=$(( 1000 * $frame_width ))
		resized_height=$(( 1000 * $c_height * $frame_width / $c_width ))
	elif [ "$crop_ratio" -lt $out_ratio ] ; then
		# image height greater than output height at same scale 
		resized_height=$(( 1000 * $frame_height ))
		resized_width=$(( 1000 * $c_width * $frame_height / $c_height ))
	else # crop_ratio = out_ratio. good.
		resized_height=$(( 1000 * $frame_height ))
		resized_width=$(( 1000 * $frame_width ))
	fi
#	myecho "[dvd-slideshow] predicted_resized_width=$( todec000 $resized_width ) predicted_resized_height=$( todec000 $resized_height )"
	predicted_resized_width=`div1000 $resized_width`
	predicted_resized_height=`div1000 $resized_height`
#	myecho "[dvd-slideshow:crop_parameters] resized_width=`todec000 $resized_width` resized_height=`todec000 $resized_height` diff=$diff"
#	myecho "[dvd-slideshow:crop_parameters] predicted resized_width=$predicted_resized_width resized_height=$predicted_resized_height"
	[ $debug -ge 3 ] && myecho "[dvd-slideshow:crop_parameters] output: xc0,yc0=$xc0,$yc0 xc1,yc1=$xc1,$yc1 c_width,c_height=$c_width,$c_height ratio=$crop_ratio $out_ratio  xci,yci=$xci,$yci"
	xc0_dec=`todec000 $xc0 | awk -F. '{print $2}'`
	yc0_dec=`todec000 $yc0 | awk -F. '{print $2}'`
	xc0_whole=$(( $xc0 / 1000 )); yc0_whole=$(( $yc0 / 1000 ))
#	xc0=`div1000 $xc0` ; yc0=`div1000 $yc0`  # rounding was causing problems... need to round down.
	xc0=$(( $xc0 / 1000 )) ; yc0=$(( $yc0 / 1000 ))
	xci=`div1000 $xci` ; yci=`div1000 $yci`  # rounding might cause problems. watch this.
	## make sure xci + predicted_resized_width < dvd_width 
	## and yci + predicted_resized_height < dvd_height
	if [ $(( $yci + $predicted_resized_height )) -gt $frame_height ] ; then
		yci=$(( $yci - 1 ))
#		myecho "[dvd-slideshow:crop_parameters] Correcting yci - 1 "
	fi
	if [ $(( $xci + $predicted_resized_width )) -gt $frame_width ] ; then
		xci=$(( $xci - 1 ))
#		myecho "[dvd-slideshow:crop_parameters] Correcting xci - 1 "
	fi
#	w=`div1000 $w` ; h=`div1000 $h`
	[ $debug -ge 3 ] && myecho "[dvd-slideshow:crop_parameters] output: c_width,c_height=$c_width,$c_height ratio=$crop_ratio $out_ratio xc0,yc0=$xc0,$yc0 xci,yci=$xci,$yci"
	# used output is:
	# xc0,yc0 (coordinates of the top left corner of the image crop in the image frame)
	# c_width,c_height (crop width and height in the image frame)
	# xi0,yi0 (coordinates of where to put the top left corner of the image on the background)
}


mycrop ()
{
	# my crop function:  does all the cropping on the current image
	# using the parameters x0,y0 ; x1,y1 ; xi,yi in memory
	# output is just the crop parameters:
	# c_width, c_height xc0,yc0  (for the actual crop)
	# and:
	# xci,yci for the location of the top left corner of the cropped image
	# relative to the output window.
	# note that the c_width x c_height must maintain the correct aspect ratio,
	# so we need to round this appropriately so the image aspect ratio doesn't 
	# keep changing during the pan/zoom.

	## the input coordinates are relative to the original image size, buffered out to
	## the output frame aspect ratio
	
	## we need to convert the existing coordinates back to the actual image coordinates:
	## top left corner of dvd window is 0,0
	## top left corner of image is at xi,yi
	## top left corner of the cropped image is at x0,y0

	x_width=$(( $x1 - $x0 )) ; y_height=$(( $y1 - $y0 ))
	out_ratio=$(( 1000* $x_width / $y_height ))
	[ $debug -ge 3 ] && myecho "[dvd-slideshow:mycrop] mycrop input: x0=$x0 y0=$y0    x1=$x1 y1=$y1   xi=$xi yi=$yi (orig buffered image frame)"

	## figure out the size of the window scaled to the original image size:
	ratio=$(( 1000* $image_width / $image_height ))
	out_ratio=$(( 1000* $frame_width / $frame_height ))
	if [ "$ratio" -gt "$(( $out_ratio ))" ] ; then
		# image width greater than output width at same scale
		newwidth=$image_width
		newheight=$(( $frame_height * $image_width / $frame_width ))
	elif [ "$ratio" -le $(( $out_ratio )) ] ; then
		# image height greater than output height at same scale 
		newwidth=$(( $frame_width * $image_height / $frame_height ))
		newheight=$image_height
	fi
	out_ratio=$(( 1000* $newwidth / $newheight ))  # this number is correct
	[ $debug -ge 3 ] && myecho "[dvd-slideshow] frame_width=$newwidth frame_height=$newheight ratio=$out_ratio"

	## shift coordinate system to start at xi,yi:
	xi0=$(( $x0-$xi )); yi0=$(( $y0-$yi )) 
	xi1=$(( $x1-$xi )); yi1=$(( $y1-$yi )) 
	w=$(( $xi1 - $xi0 ))
	h=$(( $yi1 - $yi0 ))	
	out_ratio=$(( 1000* $w / $h )) ## should be same as before because coordinate system transformation preserves this.
	[ $debug -ge 3 ] && myecho "[dvd-slideshow:mycrop] image crop coordinates=$xi0,$yi0 ; $xi1,$yi1 w=$w h=$h ratio=$out_ratio"

	## make sure the image crop coordinates are not outside the image:
	[ $xi0 -lt 0 ] && xc0=0 || xc0=$xi0 
	[ $xi1 -gt $image_width ] && xc1=$image_width || xc1=$xi1
	[ $yi0 -lt 0 ] && yc0=0 || yc0=$yi0
	[ $yi1 -gt $image_height ] && yc1=$image_height || yc1=$yi1
	c_width=$(( $xc1 - $xc0 )) ; c_height=$(( $yc1 - $yc0 ))
	out_ratio=$(( 1000* $c_width / $c_height )) ## 
	[ $debug -ge 3 ] && myecho "[dvd-slideshow:mycrop] xc0=$xc0 yc0=$yc0 xc1=$xc1 yc1=$yc1 w=$w h=$h"

	## where to put the top left corner of the cropped image relative to the background?
	deltax=$(( 10000* $frame_width / $c_width )); deltay=$(( 10000* $frame_height / $c_height ))
	## rescale % will be the smaller of the two deltas:  10000 is to retain the resolution until dividing.
	[ $deltax -lt $deltay ] && rescale=$deltax || rescale=$deltay
	if [ $xi0 -lt 0 ] ; then
		## left of cropped image is in the middle of the dvd window
		xci=`div10 $(( $rescale * -1 * $xi0 / 1000 ))`
	else
		## left of cropped image should be at x=0 afterward
		xci=0
	fi
	if [ $yi0 -lt 0 ] ; then
		## top of cropped image is in the middle of the dvd window
		yci=`div10 $(( $rescale * -1 * $yi0 / 1000 ))`
	else
		## top of cropped image should be at y=0 afterward
		yci=0
	fi
	[ $debug -ge 3 ] && myecho "[dvd-slideshow:mycrop] xci=$xci yci=$yci"
}

kenburns ()  # KENBURNS
# Kenburns $window_start $window_end $file $total_frames $startframe $lastframe bg [$char]
{
		local l_window_start="$1"
		local l_window_end="$2"
		local l_file="$3"
		local l_frames="$4"
		lastbar=0 # required for progressbar to set back to zero
		[ -z "$5" ] && local l_startframe="1" || local l_startframe="$5"
		[ -z "$6" ] && local l_endframe="$l_frames" || local l_endframe="$6"
		[ -z "$7" ] && local bg="$normal_bg" || local bg="$7"
		[ -z "$8" ] && local c='#' || local c="$8"
		if [ "$bg" == "$transparent_bg" ] ; then
			local suffix='png'
		else
			local suffix='ppm'
		fi
		image_width="`imagewidth "$l_file"`"
		image_height="`imageheight "$l_file"`"
		[ $debug -ge 1 ] && myecho "[dvd-slideshow:kenburns] Nonsquare pixel image width=$image_width image height=$image_height"
		parse_window "$l_window_start" "$l_file"
		xs0=$x0 ; ys0=$y0 ; xs1=$x1 ; ys1=$y1
		if [ -z $x0 ] || [ -z $y0 ] || [ -z $x1 ] || [ -z $y1 ] ; then
			myecho "[dvd-slideshow:kenburns] Error: No starting position found for kenburns effect"	
			myecho "[dvd-slideshow:kenburns] Example: "
			myecho "[dvd-slideshow:kenburns] image.jpg:duration:subtitle:kenburns:70%;topleft;75%;bottomright"	
			cleanup; exit 1
		fi
		parse_window "$l_window_end" "$l_file"
		xe0=$x0 ; ye0=$y0 ; xe1=$x1 ; ye1=$y1
		if [ -z $x0 ] || [ -z $y0 ] || [ -z $x1 ] || [ -z $y1 ] ; then
			myecho "[dvd-slideshow:kenburns] Error: No ending position found for kenburns effect"	
			myecho "[dvd-slideshow:kenburns] Example: "
			myecho "[dvd-slideshow:kenburns] image.jpg:duration:subtitle:kenburns:70%;topleft;75%;bottomright"	
			cleanup; exit 1
		fi
		if [ $xs0 -eq $xe0 ] && [ $ys0 -eq $ye0 ] && [ $xs1 -eq $xe1 ] && [ $ys1 -eq $ye1 ] ; then
			# start and end are the same!
			myecho "[dvd-slideshow:kenburns] WARNING: Start and end of kenburns effect are the same!"	
			myecho "[dvd-slideshow:kenburns] Use crop and it will be MUCH faster!"
		fi

		#### now we have the parameters set up. The coordinate system is relative to the 
		#### ORIGINAL image size, buffered out to the full DVD frame:
		# xi,yi   xw,yh  xs0,ys0  xs1,ys1  xe0,ye0  xe1,ye1

		s_width=$(( $xs1 - $xs0 )) ; s_height=$(( $ys1 - $ys0 ))
		e_width=$(( $xe1 - $xe0 )) ; e_height=$(( $ye1 - $ye0 ))
		[ $debug -ge 1 ] && myecho "[dvd-slideshow:kenburns] Coordinate system is original image size buffered out to dvd aspect ratio"
		[ $debug -ge 1 ] && myecho "[dvd-slideshow:kenburns] and then rescaled to non-square pixels"
		[ $debug -ge 1 ] && myecho "[dvd-slideshow:kenburns] Start: width=$s_width height=$s_height  $xs0,$ys0 : $xs1,$ys1"
		[ $debug -ge 1 ] && myecho "[dvd-slideshow:kenburns] End:   width=$e_width height=$e_height  $xe0,$ye0 : $xe1,$ye1"
		[ $debug -ge 1 ] && myecho "[dvd-slideshow:kenburns] Image top left corner:   xi=$xi yi=$yi"

		## adjust step size: ##############################
#		multiple=2  # 720x480 x 2 = 1440x960 or 1.4M pixels
#		multiple=3  # 720x480 x 3 = 2160x1440 or 3M pixels
		if [ "$low_quality" -eq 1 ] ; then
			stepsize=3
			interp=0
			enable_kenburns_resize=0
			multiple=2
		elif [ "$high_quality" -eq 1 ] ; then
			stepsize=1
			interp=0
			enable_kenburns_resize=1  # see if this still gives decent quality
			multiple=6 
		else
			stepsize=1
			interp=0  # fix this for now?
			enable_kenburns_resize=0
			multiple=4 
		fi

		# check original image width and height. if too large,
		# then make it smaller!  if too small, make it bigger!
		factorx=$(( 1000 * $image_width / $dvd_width ))
		factory=$(( 1000 * $image_height / $dvd_height ))
		maxfactor=$( max $factorx $factory )
		minfactor=$( min $factorx $factory )
		factorlimit_x=$(( $multiple * 1000 ))
		factorlimit_y=$(( $multiple * 1000 ))
#		echo "factorx=$factorx factory=$factory maxfactor=$maxfactor minfactor=$minfactor factorlimit_y=$factorlimit_y"
		if [ "$factorx" -gt "$factorlimit_x" ] && [ "$factory" -gt "$factorlimit_y" ] && [ "$enable_kenburns_resize" == 1 ] ; then
			# only rescale if both the image width and height are more than n times the 
			# output dvd width and height, respectively.
			if [ "$minfactor" == "$factorx" ] ; then	
				newsize=$(( $multiple * $dvd_width ))
				resize='-resize '$newsize'x'
				resized_x=$newsize
				resized_y=$(( 10 * $resized_x * $image_height / $image_width ))
				resized_y=$( div10 $(( 10 * $resized_x * $image_height / $image_width )) )
#				echo "multiple=$multiple dvd_width=$dvd_width newsize=$newsize image_width=$image_width"
				scale_factor=$(( 1000 * $newsize / $image_width ))
#				echo "scale_factor=$scale_factor"
			else
				newsize=$(( $multiple * $dvd_height ))
				resize='-resize x'$newsize
				# resized_x / resized_y = imagewidth_x / imagewidth_y
				resized_y=$newsize
				resized_x=$(( $resized_y * $image_width / $image_height ))
				resized_x=$( div10 $(( 10 * $resized_y * $image_width / $image_height )) )
				scale_factor=$(( 1000 * $newsize / $image_height ))
#				echo "scale_factor=$scale_factor"
			fi
			myecho "[dvd-slideshow] Rescaling $image_width"x"$image_height image to $resized_x"x"$resized_y to speed up processing"
			## now, update the coordinates with the new values after the scale. 
			## we might want to use the actual resized image size instead?
#			echo "xi=$xi yi=$yi xs0=$xs0 xe0=$xe0 xs1=$xs1 xe1=$xe1"
			xi=$(( $xi * $scale_factor / 1000 ))
			yi=$(( $yi * $scale_factor / 1000 ))
			xs0=$(( $xs0 * $scale_factor / 1000 ))
			xe0=$(( $xe0 * $scale_factor / 1000 ))
			ys0=$(( $ys0 * $scale_factor / 1000 ))
			ye0=$(( $ye0 * $scale_factor / 1000 ))
			xs1=$(( $xs1 * $scale_factor / 1000 ))
			xe1=$(( $xe1 * $scale_factor / 1000 ))
			ys1=$(( $ys1 * $scale_factor / 1000 ))
			ye1=$(( $ye1 * $scale_factor / 1000 ))
#			echo "xi=$xi yi=$yi xs0=$xs0 xe0=$xe0 xs1=$xs1 xe1=$xe1"
			image_width=$resized_x
			image_height=$resized_y
		elif [ "$factorx" -lt "$factorlimit_x" ] && [ "$factory" -lt "$factorlimit_y" ] && [ "$enable_kenburns_resize" == 1 ] ; then
			# resolution is too low to have nice smooth output. Increase resolution before cropping.
			if [ "$minfactor" == "$factorx" ] ; then	
				newsize=$(( $multiple * $dvd_width ))
				resize='-resize '$newsize'x'
				resized_x=$newsize
				resized_y=$(( 10 * $resized_x * $image_height / $image_width ))
				resized_y=$( div10 $(( 10 * $resized_x * $image_height / $image_width )) )
#				echo "multiple=$multiple dvd_width=$dvd_width newsize=$newsize image_width=$image_width"
				scale_factor=$(( 1000 * $newsize / $image_width ))
#				echo "scale_factor=$scale_factor"
			else
				newsize=$(( $multiple * $dvd_height ))
				resize='-resize x'$newsize
				# resized_x / resized_y = imagewidth_x / imagewidth_y
				resized_y=$newsize
				resized_x=$(( $resized_y * $image_width / $image_height ))
				resized_x=$( div10 $(( 10 * $resized_y * $image_width / $image_height )) )
				scale_factor=$(( 1000 * $newsize / $image_height ))
#				echo "scale_factor=$scale_factor"
			fi
			myecho "[dvd-slideshow] Rescaling $image_width"x"$image_height image to $resized_x"x"$resized_y for smoother results"
			## now, update the coordinates with the new values after the scale. 
			## we might want to use the actual resized image size instead?
#			echo "xi=$xi yi=$yi xs0=$xs0 xe0=$xe0 xs1=$xs1 xe1=$xe1"
			xi=$(( $xi * $scale_factor / 1000 ))
			yi=$(( $yi * $scale_factor / 1000 ))
			xs0=$(( $xs0 * $scale_factor / 1000 ))
			xe0=$(( $xe0 * $scale_factor / 1000 ))
			ys0=$(( $ys0 * $scale_factor / 1000 ))
			ye0=$(( $ye0 * $scale_factor / 1000 ))
			xs1=$(( $xs1 * $scale_factor / 1000 ))
			xe1=$(( $xe1 * $scale_factor / 1000 ))
			ys1=$(( $ys1 * $scale_factor / 1000 ))
			ye1=$(( $ye1 * $scale_factor / 1000 ))
#			echo "xi=$xi yi=$yi xs0=$xs0 xe0=$xe0 xs1=$xs1 xe1=$xe1"
			image_width=$resized_x
			image_height=$resized_y
		else
			resize=''
		fi
		$gm_cmd convert "$l_file" -filter $filtermethod $resize -resize $sq_to_dvd_pixels $gm_repage -type TrueColorMatte -depth 8 "$tmpdir"/temp_slideshow_image_scaled.ppm

		############################ end crop/resize large images

#		echo 'x0,y0,x1,y1,xcenter,ycenter,xwidth,yheight,xc0,yc0,c_width,c_height' > kenburns_coordinates.csv
#		echo 'xc0,yc0,c_width,c_height,xci,yci,iwn,ihn,predicted_resized_width,predicted_resized_height,xc0_dec,yc0_dec' > kenburns_coordinates.csv
#		echo 'xc0,yc0,c_width,c_height,xci,yci,predicted_resized_width,predicted_resized_height' > kenburns_coordinates.csv
		xvelocity0=$(( 1000 * ($xe0-$xs0)*($xe0-$xs0) / $l_frames ))
		xvelocity1=$(( 1000 * ($xe1-$xs1)*($xe1-$xs1) / $l_frames ))
		xvelocity=$(( ( $xvelocity0 + $xvelocity1 ) / 1000 ))
		#echo "xvelocity0=$xvelocity0  xvelocity1=$xvelocity1"
		yvelocity0=$(( 1000 * ($ye0-$ys0)*($ye0-$ys0) / $l_frames ))
		yvelocity1=$(( 1000 * ($ye1-$ys1)*($ye1-$ys1) / $l_frames ))
		yvelocity=$(( ( $yvelocity0 + $yvelocity1 ) / 1000 ))
		#echo "yvelocity0=$yvelocity0  yvelocity1=$yvelocity1"
		if [ "$interp" -eq 1 ] && [ "$xvelocity" -eq 0 ] && [ "$yvelocity" -lt 4000 ] ; then
			[ $debug -ge 1 ] && echo "[dvd-slideshow:kenburns] Using interpolation. Velocity=$xvelocity $yvelocity"
		elif [ "$interp" -eq 1 ] && [ "$yvelocity" -eq 0 ] && [ "$xvelocity" -lt 4000 ] ; then
			[ $debug -ge 1 ] && echo "[dvd-slideshow:kenburns] Using interpolation. Velocity=$xvelocity $yvelocity"
		elif [ "$interp" -eq 1 ] && [ "$xvelocity" -lt 5000 -a "$yvelocity" -lt 4000 ] ; then
			[ $debug -ge 1 ] && echo "[dvd-slideshow:kenburns] Using interpolation. Velocity=$xvelocity $yvelocity"
		elif [ "$interp" -eq 1 ] ; then
			[ $debug -ge 0 ] && echo "[dvd-slideshow:kenburns] Disabling high-quality mode for fast effect. Velocity=$xvelocity $yvelocity"
			interp=0
		fi
		
		## smooth start and end parameters:
		smoothing=1  # (0=old method before 0.8.0)
		if [ "$kenburns_acceleration" == '0' ] ; then
			# do not use smoothing, or set it to a very small number
#			echo "kb_accel = 0 F1=1"
			F1=1
#			D1x0=0; D1y0=0; D1x1=0; D1y1=0 # distance gone so far  # not needed since we force one frame of region 1
#			smoothing=0
		elif [ $( echo "$kenburns_acceleration" | awk -F% '{print NF}' ) -gt 1 ] ; then
			kb_acceleration_percent=$( echo "$kenburns_acceleration" | awk -F% '{print $1}' )
			F1=$(( $l_frames * $kb_acceleration_percent / 100 ))
			if [ $kb_acceleration_percent -eq 0 ] ; then
				F1=1
				# D1x0=0; D1y0=0; D1x1=0; D1y1=0 # distance gone so far # not needed since we force one frame of region 1
			else
				myecho "using kb percent syntax F1=$F1"
		 	fi
		else
			F1=$( echo "scale=0; $kenburns_acceleration * $frames_per_ms / 1000" | bc )
			F1=$( printf %2.0f $F1 )
#			echo "kb_accel = other F1=$F1"
		fi
		# make sure the acceleration time is shorter than half of the full kenburns time:
		if [ "$F1" -gt "$(( $l_frames / 2 ))" ] ; then
			myecho "[dvd-slideshow] Warning: kenburns acceleration time is longer than kenburns time"
			myecho "[dvd-slideshow]		 Setting acceleration time to $F1 frames"
			F1=$(( $l_frames / 2 ))
		fi
		F2=$(( $l_frames - $F1 ))	
		V0x=$( echo "scale=9; 2 * ( $xe0 - $xs0 ) / ( $l_frames + $F2 - $F1 )" | bc ) 
		V0y=$( echo "scale=9; 2 * ( $ye0 - $ys0 ) / ( $l_frames + $F2 - $F1 )" | bc )
		V1x=$( echo "scale=9; 2 * ( $xe1 - $xs1 ) / ( $l_frames + $F2 - $F1 )" | bc ) 
		V1y=$( echo "scale=9; 2 * ( $ye1 - $ys1 ) / ( $l_frames + $F2 - $F1 )" | bc )
#		echo "F1=$F1 F2=$F2 V0x=$V0x V0y=$V0y"
#		if [ -n "$logo" ] ; then  # optionally add logo layer
#			add_logo "$logo" slide_$i.ppm "$logo_gravity"
#		fi
		subtitle1[$i]="$( echo "${subtitle[$i]}" | awk -F';' '{print $1}' )"
		if [ -n "${subtitle1[$i]}" -a "$subtitle_type" == 'render' ] ; then
			# pre-render the subtitle:
			subtitle "${subtitle1[$i]}" $i transparent # creates subtitle_$i.png
		fi
		pi='3.14159265'
		## start loop for kenburns effect: #################################
		echo -n  "[dvd-slideshow]"
		for (( fr=l_startframe ; fr<=l_endframe ; fr=fr+stepsize )) ; do
#			echo "fr=$fr startframe=$l_startframe endframe=$l_endframe"
			dj=`addzeros $fr`
			if [ $fr -le $F1 ] ; then   # inputs are relatively simple:  make function?
#				echo "$fr $F1 $l_frames region 1"
				# region 1   x0,y0,x1,y1 are floating point numbers
				x0=$( echo "scale=3; $xs0 + $V0x/2 *($fr - $F1/$pi *s($pi*$fr/$F1))" | bc -l )
				y0=$( echo "scale=3; $ys0 + $V0y/2 *($fr - $F1/$pi *s($pi*$fr/$F1))" | bc -l )
				x1=$( echo "scale=3; $xs1 + $V1x/2 *($fr - $F1/$pi *s($pi*$fr/$F1))" | bc -l )
				y1=$( echo "scale=3; $ys1 + $V1y/2 *($fr - $F1/$pi *s($pi*$fr/$F1))" | bc -l )
				D1x0=$x0; D1y0=$y0; D1x1=$x1; D1y1=$y1 # distance gone so far
				D2x0=$x0 ; D2y0=$y0 ; D2x1=$x1 ; D2y1=$y1  # (in case we never get to region2)
				## Get integer portion:
				it=`printf %3f "$x0" | awk -F. '{print $1}'` ; [ -z "$it" ] && x0_whole=0 || x0_whole="$it"
				it=`printf %3f "$y0" | awk -F. '{print $1}'` ; [ -z "$it" ] && y0_whole=0 || y0_whole="$it"
				it=`printf %3f "$x1" | awk -F. '{print $1}'` ; [ -z "$it" ] && x1_whole=0 || x1_whole="$it"
				it=`printf %3f "$y1" | awk -F. '{print $1}'` ; [ -z "$it" ] && y1_whole=0 || y1_whole="$it"
				## decimals:
				it=`printf %3.3f "$x0" | awk -F. '{print "0."$2}'` ; [ -z "$it" ] && x0_dec=0 || x0_dec="$it"
				it=`printf %3.3f "$y0" | awk -F. '{print "0."$2}'` ; [ -z "$it" ] && y0_dec=0 || y0_dec="$it"
				it=`printf %3.3f "$x1" | awk -F. '{print "0."$2}'` ; [ -z "$it" ] && x1_dec=0 || x1_dec="$it"
				it=`printf %3.3f "$y1" | awk -F. '{print "0."$2}'` ; [ -z "$it" ] && y1_dec=0 || y1_dec="$it"
#				x0_dec=$( echo $( printf %3.3f $( echo "scale=3; $x0 / 1000" | bc ) ) | awk -F. '{print "0."$2}')
#				y0_dec=$( echo $( printf %3.3f $( echo "scale=3; $y0 / 1000" | bc ) ) | awk -F. '{print "0."$2}')
#				x1_dec=$( echo $( printf %3.3f $( echo "scale=3; $x1 / 1000" | bc ) ) | awk -F. '{print "0."$2}')
#				y1_dec=$( echo $( printf %3.3f $( echo "scale=3; $y1 / 1000" | bc ) ) | awk -F. '{print "0."$2}')
				# now, set new x0 and y0 values to rounded results
				it=$( echo "scale=3; 1000* $x0" | bc ); it=`echo "$it" | awk -F. '{print $1}'` ; [ -z "$it" ] && it=0 
				x0=$( div1000 $it )	
				it=$( echo "scale=3; 1000* $y0" | bc ); it=`echo "$it" | awk -F. '{print $1}'` ; [ -z "$it" ] && it=0 
				y0=$( div1000 $it )	
				it=$( echo "scale=3; 1000* $x1" | bc ); it=`echo "$it" | awk -F. '{print $1}'` ; [ -z "$it" ] && it=0 
				x1=$( div1000 $it )	
				it=$( echo "scale=3; 1000* $y1" | bc ); it=`echo "$it" | awk -F. '{print $1}'` ; [ -z "$it" ] && it=0 
				y1=$( div1000 $it )	
#				x0=$x0_whole ; y0=$y0_whole
#				x1=$x1_whole ; y1=$y1_whole
				## now, round the results for normal mode:
				[ $debug -ge 2 ] && myecho "[dvd-slideshow:kenburns] $fr x0=$x0_whole.$x0_dec y0=$y0_whole.$y0_dec x0=$x0 y0=$y0 region 1"
			elif [ $fr -ge $(( $F2 + 1 )) ] ; then
				# region 3
#				echo "$fr $F1 $l_frames region 3"
#				echo "D2x0=$D2x0 V0x=$V0x fr=$fr F2=$F2 l_frames=$l_frames pi=$pi"
				x0=$( echo "scale=3; $D2x0 + $V0x/2 *( ($fr-$F2) + ($l_frames-$F2)/$pi*s(($fr-$F2)*$pi/($l_frames-$F2)) )" | bc -l )
				y0=$( echo "scale=3; $D2y0 + $V0y/2 *( ($fr-$F2) + ($l_frames-$F2)/$pi*s(($fr-$F2)*$pi/($l_frames-$F2)) )" | bc -l )
				x1=$( echo "scale=3; $D2x1 + $V1x/2 *( ($fr-$F2) + ($l_frames-$F2)/$pi*s(($fr-$F2)*$pi/($l_frames-$F2)) )" | bc -l )
				y1=$( echo "scale=3; $D2y1 + $V1y/2 *( ($fr-$F2) + ($l_frames-$F2)/$pi*s(($fr-$F2)*$pi/($l_frames-$F2)) )" | bc -l )
				## Get integer portion:
				it=`printf %3f "$x0" | awk -F. '{print $1}'` ; [ -z "$it" ] && x0_whole=0 || x0_whole="$it"
				it=`printf %3f "$y0" | awk -F. '{print $1}'` ; [ -z "$it" ] && y0_whole=0 || y0_whole="$it"
				it=`printf %3f "$x1" | awk -F. '{print $1}'` ; [ -z "$it" ] && x1_whole=0 || x1_whole="$it"
				it=`printf %3f "$y1" | awk -F. '{print $1}'` ; [ -z "$it" ] && y1_whole=0 || y1_whole="$it"
				[ $debug -ge 2 ] && myecho "[dvd-slideshow:kenburns] $fr x0=$x0 y0=$y0 region 3"
				[ $debug -ge 2 ] && myecho "[dvd-slideshow:kenburns] $fr x0=$x0_whole.$x0_dec y0=$y0_whole.$y0_dec x0=$x0 y0=$y0 region 3"
				## decimals:
				it=`printf %3.3f "$x0" | awk -F. '{print "0."$2}'` ; [ -z "$it" ] && x0_dec=0 || x0_dec="$it"
				it=`printf %3.3f "$y0" | awk -F. '{print "0."$2}'` ; [ -z "$it" ] && y0_dec=0 || y0_dec="$it"
				it=`printf %3.3f "$x1" | awk -F. '{print "0."$2}'` ; [ -z "$it" ] && x1_dec=0 || x1_dec="$it"
				it=`printf %3.3f "$y1" | awk -F. '{print "0."$2}'` ; [ -z "$it" ] && y1_dec=0 || y1_dec="$it"
#				x0_dec=$( echo $( printf %3.3f $( echo "scale=3; $x0 / 1000" | bc ) ) | awk -F. '{print "0."$2}')
#				y0_dec=$( echo $( printf %3.3f $( echo "scale=3; $y0 / 1000" | bc ) ) | awk -F. '{print "0."$2}')
#				x1_dec=$( echo $( printf %3.3f $( echo "scale=3; $x1 / 1000" | bc ) ) | awk -F. '{print "0."$2}')
#				y1_dec=$( echo $( printf %3.3f $( echo "scale=3; $y1 / 1000" | bc ) ) | awk -F. '{print "0."$2}')
				# now, set new x0 and y0 values to rounded results
				it=$( echo "scale=3; 1000* $x0" | bc ); it=`echo "$it" | awk -F. '{print $1}'` ; [ -z "$it" ] && it=0 
				x0=$( div1000 $it )	
				it=$( echo "scale=3; 1000* $y0" | bc ); it=`echo "$it" | awk -F. '{print $1}'` ; [ -z "$it" ] && it=0 
				y0=$( div1000 $it )	
				it=$( echo "scale=3; 1000* $x1" | bc ); it=`echo "$it" | awk -F. '{print $1}'` ; [ -z "$it" ] && it=0 
				x1=$( div1000 $it )	
				it=$( echo "scale=3; 1000* $y1" | bc ); it=`echo "$it" | awk -F. '{print $1}'` ; [ -z "$it" ] && it=0 
				y1=$( div1000 $it )	
#				x0=$x0_whole ; y0=$y0_whole
#				x1=$x1_whole ; y1=$y1_whole
			else 
				# middle region 2
#				echo "$fr $F1 $l_frames region 2"
				x0=$( echo "scale=3; $D1x0 + $V0x*($fr-$F1)" | bc )
				y0=$( echo "scale=3; $D1y0 + $V0y*($fr-$F1)" | bc )
				x1=$( echo "scale=3; $D1x1 + $V1x*($fr-$F1)" | bc )
				y1=$( echo "scale=3; $D1y1 + $V1y*($fr-$F1)" | bc )
				## Integer portion
				it=`printf %3f "$x0" | awk -F. '{print $1}'` ; [ -z "$it" ] && x0_whole=0 || x0_whole="$it"
				it=`printf %3f "$y0" | awk -F. '{print $1}'` ; [ -z "$it" ] && y0_whole=0 || y0_whole="$it"
				it=`printf %3f "$x1" | awk -F. '{print $1}'` ; [ -z "$it" ] && x1_whole=0 || x1_whole="$it"
				it=`printf %3f "$y1" | awk -F. '{print $1}'` ; [ -z "$it" ] && y1_whole=0 || y1_whole="$it"
				D2x0=$x0 ; D2y0=$y0 ; D2x1=$x1 ; D2y1=$y1  # distance gone so far
				[ $debug -ge 2 ] && myecho "[dvd-slideshow:kenburns] $fr x0=$x0 y0=$y0 region 2"
				[ $debug -ge 2 ] && myecho "[dvd-slideshow:kenburns] $fr x0=$x0_whole.$x0_dec y0=$y0_whole.$y0_dec x0=$x0 y0=$y0 region 2"
				## decimals:
				it=`printf %3.3f "$x0" | awk -F. '{print "0."$2}'` ; [ -z "$it" ] && x0_dec=0 || x0_dec="$it"
				it=`printf %3.3f "$y0" | awk -F. '{print "0."$2}'` ; [ -z "$it" ] && y0_dec=0 || y0_dec="$it"
				it=`printf %3.3f "$x1" | awk -F. '{print "0."$2}'` ; [ -z "$it" ] && x1_dec=0 || x1_dec="$it"
				it=`printf %3.3f "$y1" | awk -F. '{print "0."$2}'` ; [ -z "$it" ] && y1_dec=0 || y1_dec="$it"
#				x0_dec=$( echo $( printf %3.3f $( echo "scale=3; $x0 / 1000" | bc ) ) | awk -F. '{print "0."$2}')
#				y0_dec=$( echo $( printf %3.3f $( echo "scale=3; $y0 / 1000" | bc ) ) | awk -F. '{print "0."$2}')
#				x1_dec=$( echo $( printf %3.3f $( echo "scale=3; $x1 / 1000" | bc ) ) | awk -F. '{print "0."$2}')
#				y1_dec=$( echo $( printf %3.3f $( echo "scale=3; $y1 / 1000" | bc ) ) | awk -F. '{print "0."$2}')
				# now, set new x0 and y0 values to rounded results
				it=$( echo "scale=3; 1000* $x0" | bc ); it=`echo "$it" | awk -F. '{print $1}'` ; [ -z "$it" ] && it=0 
				x0=$( div1000 $it )	
				it=$( echo "scale=3; 1000* $y0" | bc ); it=`echo "$it" | awk -F. '{print $1}'` ; [ -z "$it" ] && it=0 
				y0=$( div1000 $it )	
				it=$( echo "scale=3; 1000* $x1" | bc ); it=`echo "$it" | awk -F. '{print $1}'` ; [ -z "$it" ] && it=0 
				x1=$( div1000 $it )	
				it=$( echo "scale=3; 1000* $y1" | bc ); it=`echo "$it" | awk -F. '{print $1}'` ; [ -z "$it" ] && it=0 
				y1=$( div1000 $it )	
			fi

###########################

#			myecho "x0=$x0 y0=$y0 x1=$x1 y1=$y1 logfactor=$logfactor"
#			myecho "x0=$x0 y0=$y0 x1=$x1 y1=$y1 "
			## now optionally do convolution if high-quality is enabled:
			if [ "$interp" -eq 1 ] ; then
#				myecho "$fr x0=$x0 x0_dec=$x0_dec y0=$y0 y0_dec=$y0_dec logfactor=$logfactor"
				## now, we're going to calculate the following parameters:
				# calculate subpixel-averaging weights:
	                        Afactor=$( echo "scale=3; 100*(1-$x0_dec)*(1-$y0_dec)" | bc )
	                        Bfactor=$( echo "scale=3; 100*($x0_dec)*(1-$y0_dec)" | bc )
	                        Cfactor=$( echo "scale=3; 100*(1-$x0_dec)*($y0_dec)" | bc )
	                        Dfactor=$( echo "scale=3; 100*($x0_dec)*($y0_dec)" | bc )
	                        Afactor=`printf %3.0f $Afactor | tr -d \[:blank:\]`
	                        Bfactor=`printf %3.0f $Bfactor | tr -d \[:blank:\]`
	                        Cfactor=`printf %3.0f $Cfactor | tr -d \[:blank:\]`
	                        Dfactor=`printf %3.0f $Dfactor | tr -d \[:blank:\]`
				convolve="-convolve 0,0,0,0,$Afactor,$Bfactor,0,$Cfactor,$Dfactor"
	                        [ "$debug" -ge 2 ] && myecho "[dvd-slideshow:kenburns] $fr Af=$Afactor Bf=$Bfactor Cf=$Cfactor Df=$Dfactor"
			else
#				convolve="-filter cubic"
				convolve="-filter $filtermethod"
			fi

			# [c_width c_height xc0 yc0 xci yci]=crop_parameters(image_width image_height frame_width frame_height x0 y0 x1 y1 xi yi)
			crop_parameters # figure out final crop parameters  
#			myecho "$fr x0=$x0 x0_dec=$x0_dec y0=$y0 y0_dec=$y0_dec logfactor=$logfactor"
#			myecho "$fr x0=$x0 x0_dec=$x0_dec y0=$y0 y0_dec=$y0_dec "
			# outputs correct predicted_resized_width and predicted_resized_height

#			echo '$xc0,$yc0,$c_width,$c_height,$xci,$yci,$iwn,$ihn,$predicted_resized_width,$predicted_resized_height,$xc0_dec,$yc0_dec' >> kenburns_coordinates.csv
#			echo "$xc0,$yc0,$c_width,$c_height,$xci,$yci,$predicted_resized_width,$predicted_resized_height" >> kenburns_coordinates.csv

			[ $debug -ge 2 ] && myecho "[dvd-slideshow:kenburns] $fr xc0,yc0=$xc0_whole.$xc0_dec,$yc0_whole.$yc0_dec cw,ch=$c_width,$c_height xci,yci=$xci,$yci"
#			[ $debug -ge 2 ] && myecho "[dvd-slideshow:kenburns] $fr xc0,yc0=$xc0,$yc0 cw,ch=$c_width,$c_height xci,yci=$xci,$yci"
#			i_width=$predicted_resized_width; i_height=$predicted_resized_height

			delta_width=$(( $dvd_width - $predicted_resized_width ))
			delta_height=$(( $dvd_height - $predicted_resized_height ))
			[ $debug -ge 2 ] && myecho "[dvd-slideshow:kenburns] frame_width=$frame_width frame_height=$frame_height"
			[ $debug -ge 2 ] && myecho "[dvd-slideshow:kenburns] predicted_resized_width=$predicted_resized_width predicted_resized_height=$predicted_resized_height"
			[ $debug -ge 2 ] && myecho "[dvd-slideshow:kenburns] delta_width=$delta_width delta_height=$delta_height"
			[ $debug -ge 2 ] && myecho "[dvd-slideshow:kenburns] crop_parameters $c_width x $c_height +$xc0 +$yc0 composite +$(( $xci + $frame_border )) +$(( $yci + $frame_border ))"
			if [ $delta_width -le 1 ] && [ $delta_height -le 1 ] && [ "$frame_border" -eq 0 ] ; then
#				echo "[dvd-slideshow:kenburns: delta_width=$delta_width delta_height=$delta_height"
				# force the output size to be exact:  no composite needed!
#				if [ -n "$logo" ] ; then  # optionally add logo layer
#					add_logo "$logo" slide_$i.ppm "$logo_gravity"
#				fi
				if [ -n "${subtitle1[$i]}" -a "$subtitle_type" == 'render' ] ; then
					if [ "$smp" -eq 1 ] ; then
						[ $debug -ge 3 ] && echo "deltawh<1 smp=1"
						($gm_cmd convert "$tmpdir"/temp_slideshow_image_scaled.ppm -filter $filtermethod -crop "$c_width"x"$c_height"+"$xc0"+"$yc0" $gm_repage -type TrueColorMatte -depth 8 $convolve -resize "$dvd_width"x"$dvd_height"! $sharpen miff:- | composite -compose src-over -type TrueColorMatte -depth 8 "$tmpdir"/subtitle_"$i".png - "$tmpdir"/fade_"$dj.$suffix" ; add_logo "$logo" fade_$dj.$suffix "$logo_gravity" ; extracopies $fr $l_frames $suffix ) &
					elif [ "$smp" -eq 0 ] ; then
						[ $debug -ge 3 ] && echo "deltawh<1 smp=0"
						($gm_cmd convert "$tmpdir"/temp_slideshow_image_scaled.ppm -filter $filtermethod -crop "$c_width"x"$c_height"+"$xc0"+"$yc0" $gm_repage -type TrueColorMatte -depth 8 $convolve -resize "$dvd_width"x"$dvd_height"! $sharpen miff:- | composite -compose src-over -type TrueColorMatte -depth 8 "$tmpdir"/subtitle_"$i".png - "$tmpdir"/fade_"$dj.$suffix" ; add_logo "$logo" fade_$dj.$suffix "$logo_gravity" ; extracopies $fr $l_frames $suffix ) 
					fi
				else  # no subtitles
					if [ "$smp" -eq 1 ] ; then
						[ $debug -ge 3 ] && echo "deltawh<1 smp=1"
						($gm_cmd convert "$tmpdir"/temp_slideshow_image_scaled.ppm -filter $filtermethod -crop "$c_width"x"$c_height"+"$xc0"+"$yc0" $gm_repage -type TrueColorMatte -depth 8 $convolve -resize "$dvd_width"x"$dvd_height"! $sharpen -type TrueColorMatte -depth 8 "$tmpdir"/fade_"$dj.$suffix" ; add_logo "$logo" fade_$dj.$suffix "$logo_gravity" ; extracopies $fr $l_frames $suffix ) &
					elif [ "$smp" -eq 0 ] ; then
						[ $debug -ge 3 ] && echo "deltawh<1 smp=0"
						$gm_cmd convert "$tmpdir"/temp_slideshow_image_scaled.ppm -filter $filtermethod -crop "$c_width"x"$c_height"+"$xc0"+"$yc0" $gm_repage -type TrueColorMatte -depth 8 $convolve -resize "$dvd_width"x"$dvd_height"! $sharpen -type TrueColorMatte -depth 8 "$tmpdir/fade_$dj.$suffix" ; add_logo "$logo" fade_$dj.$suffix "$logo_gravity" ; extracopies $fr $l_frames $suffix
					fi
				fi
			elif [ 0 == 1 ] ; then
#			elif [ $bgfile == 'black' ] ; then
				# calculate border size for possible speed improvement:
				# splice in black background if we can for better speed!
				# split the difference between the two sides. If odd, add extra
				# to bottom right?
				left=$(( $xci + $frame_border )); right=$(( $delta_width - $left ))
				[ "$right" -lt 0 ] && left=$(( $left + $right )) 
				[ "$right" -lt 0 ] && right=0
				top=$(( $yci + $frame_border )) ; bottom=$(( $delta_height - $top ))
				[ "$bottom" -lt 0 ] && top=$(( $top + $bottom )) 
				[ "$bottom" -lt 0 ] && bottom=0
	                        [ $debug -ge 2 ] && myecho "[dvd-slideshow:kenburns] left=$left right=$right top=$top bottom=$bottom delta_w=$delta_width delta_h=$delta_height"
#				if [ "$smp" -eq 1 ] ; then
					[ $debug -ge 1 ] && echo "deltawh>1 bg=black"
					$gm_cmd convert "$tmpdir"/temp_slideshow_image_scaled.ppm -filter $filtermethod -crop "$c_width"x"$c_height"+"$xc0"+"$yc0" $gm_repage -type TrueColorMatte -depth 8 $convolve -resize "$frame_width"x"$frame_height" "$tmpdir"/mytemp.$suffix 
					# now, get size of resized image because of roundoff errors:
					# need to get this correct in the future so we can run this in smp mode!
					resized_width=$( imagewidth_sq "$tmpdir"/mytemp.$suffix )
					resized_height=$( imageheight "$tmpdir"/mytemp.$suffix )
#					if [ "$resized_width" != "$predicted_resized_width" ] || [ "$resized_height" != "$predicted_resized_height" ] ; then
#						echo "resized_width=$resized_width : $predicted_resized_width resized_height=$resized_height : $predicted_resized_height"
#					fi
					delta_width=$(( $dvd_width - $resized_width ))
					delta_height=$(( $dvd_height - $resized_height ))
					left=$(( $xci + $frame_border )); right=$(( $delta_width - $left ))
					top=$(( $yci + $frame_border )) ; bottom=$(( $delta_height - $top ))
	                        	[ $debug -ge 3 ] && myecho "[dvd-slideshow:kenburns] left=$left right=$right top=$top bottom=$bottom delta_w=$delta_width delta_h=$delta_height"
					[ "$right" -lt 0 ] && left=$(( $left + $right )) 
					[ "$right" -lt 0 ] && right=0
					[ "$bottom" -lt 0 ] && top=$(( $top + $bottom )) 
					[ "$bottom" -lt 0 ] && bottom=0
	                        	[ $debug -ge 3 ] && myecho "[dvd-slideshow:kenburns] left=$left right=$right top=$top bottom=$bottom delta_w=$delta_width delta_h=$delta_height"
					$gm_cmd convert "$tmpdir"/mytemp.$suffix -background black -splice "$right"x"$bottom"+$resized_width+$resized_height -splice "$left"x"$top" $gm_repage $sharpen -type TrueColorMatte -depth 8 "$tmpdir/fade_$dj.$suffix" ; rm "$tmpdir"/mytemp.$suffix ; add_logo "$logo" fade_$dj.$suffix "$logo_gravity" ; extracopies $fr $l_frames $suffix

					# works with imagemagick > 6.0.6  ($gm_cmd convert "$tmpdir/temp_slideshow_image_scaled.ppm" -crop "$c_width"x"$c_height"+$xc0+$yc0 $gm_repage -resize "$dvd_width"x"$dvd_height" -bordercolor black -compose src-over -border 0 -background black -splice "$right"x"$bottom"+$i_width+$i_height -splice "$left"x"$top" -type TrueColorMatte -depth 8 "$tmpdir/fade_$dj.ppm" ; add_logo "$logo" fade_$dj.$suffix "$logo_gravity" ; extracopies $fr $l_frames )
#				fi
			else   # need to composite over background image:
#				if [ -n "$logo" ] ; then  # optionally add logo layer
#					add_logo "$logo" slide_$i.ppm "$logo_gravity"
#				fi
				if [ -n "${subtitle1[$i]}" -a "$subtitle_type" == 'render' ] ; then
					## also render subtitles:
					if [ "$smp" -eq 1 ] ; then
						[ $debug -ge 3 ] && echo "deltawh>1 bg=image smp=1"
						($gm_cmd convert "$tmpdir"/temp_slideshow_image_scaled.ppm -crop "$c_width"x"$c_height"+"$xc0"+"$yc0" $gm_repage -type TrueColorMatte -depth 8 -filter $filtermethod $convolve -resize "$frame_width"x"$frame_height" $sharpen miff:- | composite -compose src-over -geometry "+$(( $xci + $frame_border ))+$(( $yci + $frame_border ))" -type TrueColorMatte -depth 8 - "$normal_bg" miff:- | composite -compose src-over -type TrueColorMatte -depth 8 "$tmpdir"/subtitle_"$i".png - "$tmpdir/fade_$dj.$suffix" ; $gm_cmd convert "$tmpdir"/fade_$dj.$suffix -type TrueColorMatte -depth 8 "$tmpdir"/fade_$dj.$suffix ; add_logo "$logo" fade_$dj.$suffix "$logo_gravity" ; extracopies $fr $l_frames $suffix ) & 
					else
						[ $debug -ge 2 ] && echo "deltawh>1 bg=image smp=0"
						($gm_cmd convert "$tmpdir"/temp_slideshow_image_scaled.ppm -crop "$c_width"x"$c_height"+"$xc0"+"$yc0" $gm_repage -type TrueColorMatte -depth 8 -filter $filtermethod $convolve -resize "$frame_width"x"$frame_height" $sharpen miff:- | composite -compose src-over -geometry "+$(( $xci + $frame_border ))+$(( $yci + $frame_border ))" -type TrueColorMatte -depth 8 - "$normal_bg"  miff:- | composite -compose src-over -type TrueColorMatte -depth 8 "$tmpdir"/subtitle_"$i".png - "$tmpdir"/fade_$dj.$suffix ; $gm_cmd convert "$tmpdir"/fade_$dj.$suffix -type TrueColorMatte -depth 8 "$tmpdir"/fade_$dj.$suffix ; add_logo "$logo" fade_$dj.$suffix "$logo_gravity" ; extracopies $fr $l_frames $suffix ) 
						# this last pipe through convert seems to correct
						# the "bad raw ppm magic" errors.	
					fi
				else  # no subtitles to render
					if [ "$smp" -eq 1 ] ; then
						[ $debug -ge 3 ] && echo "deltawh>1 bg=image smp=1"
						($gm_cmd convert "$tmpdir"/temp_slideshow_image_scaled.ppm -crop "$c_width"x"$c_height"+"$xc0"+"$yc0" $gm_repage -type TrueColorMatte -depth 8 -filter $filtermethod $convolve -resize "$frame_width"x"$frame_height" $sharpen miff:- | composite -compose src-over -geometry "+$(( $xci + $frame_border ))+$(( $yci + $frame_border ))" -type TrueColorMatte -depth 8 - "$normal_bg" "$tmpdir/fade_$dj.$suffix" ; add_logo "$logo" fade_$dj.$suffix "$logo_gravity" ; extracopies $fr $l_frames $suffix ) & 
					else
						[ $debug -ge 3 ] && echo "deltawh>1 bg=image smp=0"
						($gm_cmd convert "$tmpdir"/temp_slideshow_image_scaled.ppm -crop "$c_width"x"$c_height"+"$xc0"+"$yc0" $gm_repage -type TrueColorMatte -depth 8 -filter $filtermethod $convolve -resize "$frame_width"x"$frame_height" $sharpen miff:- | composite -compose src-over -geometry "+$(( $xci + $frame_border ))+$(( $yci + $frame_border ))" -type TrueColorMatte -depth 8 - "$normal_bg" "$tmpdir/fade_$dj.$suffix" ; add_logo "$logo" fade_$dj.$suffix "$logo_gravity" ; extracopies $fr $l_frames $suffix ) 
					fi
				fi
			fi
			# this next line only works for non-smp! (since file must exist first)
			# errors here (not depth=8) will often cause ppmtoy4m errors
			# like "Bad Raw PPM magic!"
			if [ "$debug" -ge 2 ] && [ "$smp" -eq 0 ] ; then
				# do error checks on output kenburns image
				outwidth=`imagewidth_sq "$tmpdir/fade_$dj.$suffix"`
				outheight=`imageheight "$tmpdir/fade_$dj.$suffix"`
				if [ "$outwidth" -ne "$dvd_width" ] ; then
					myecho "ERROR: fade_$dj.$suffix is not $dvd_width wide"
					exit 1
				fi
				if [ "$outheight" -ne "$dvd_height" ] ; then
					myecho "ERROR: fade_$dj.$suffix is not $dvd_height high"
					exit 1
				fi
			fi
			progressbar $(( $fr - $l_startframe +1 )) $(( $l_endframe - $l_startframe + 1 )) "$c"
		done
		[ $debug -ge 2 ] && myecho "[dvd-slideshow:kenburns] waiting for files suffix=$suffix end=$dj start=$l_startframe"
#		echo "waiting for files $suffix $dj $l_startframe"
		waitforfiles "$tmpdir/fade" $suffix $dj $l_startframe
#		echo "all files present $suffix $dj $l_startframe"
		finish_progressbar $(( $fr - $l_startframe +1 )) $(( $l_endframe - $l_startframe + 1 )) "$c"
}

wavlength ()
{
	# wavlength $file 
	# returns song length in ms
	if [ "$soxi" == '1' ] ; then
		soxi -D "$1" 1> "$tmpdir"/trash.txt
		song_length=`cat "$tmpdir"/trash.txt` 
	else
		sox "$1" $sox_nop stat 2> "$tmpdir"/trash.txt 
		song_length=`cat "$tmpdir"/trash.txt | grep 'Length (seconds):' | awk -F: '{print $2}' | tr -d \[:blank:\]`
	fi
	song_length=$( echo "scale=0; 1000 * $song_length" | bc | awk -F. '{printf ("%3.0f", $0)}' )
	rm "$tmpdir"/trash.txt
	echo "$song_length"
}

rawlength ()
{
		sox -t raw -r $audio_sample_rate $sox_word $sox_int -c 2 "$1" $sox_nop stat 2> "$tmpdir"/trash.txt
		song_length=`cat "$tmpdir"/trash.txt | grep 'Length (seconds):' | awk -F: '{print $2}' | tr -d \[:blank:\]`
		song_length=$( echo "scale=0; 1000 * $song_length" | bc | awk -F. '{printf ("%3.0f", $0)}' )
		rm "$tmpdir"/trash.txt
		echo "$song_length"
}

progressbar ()
# progressbar $fr $frames $character #finish?
{
	## display progress bar as frame $fr progresses to $frames
	local fr=$1 ; local frames=$2
	[ -z "$3" ] && local c='#' || local c="$3"
	[ -z "$4" ] && local finish=0 || local finish="$4"
	local thisbar=$(( $fr * 59 / $frames  ))
#echo "finish=$finish thisbar=$thisbar"
#	echo "fr=$fr frames=$frames delta=$delta"
	if [ "$finish" -eq 0 ] && [ "$thisbar" -gt "$lastbar" ] ; then
		delta=$(( $thisbar - $lastbar ))
#	echo "finish=$finish fr=$fr frames=$frames delta=$delta"
		if [ "$delta" -eq 1 ] ; then 
			echo -n "$c"
		elif [ "$delta" -eq 2 ] ; then
			echo -n "$c$c"
		elif [ "$delta" -eq 3 ] ; then
			echo -n "$c$c$c"
		elif [ "$delta" -eq 4 ] ; then
			echo -n "$c$c$c$c"
		elif [ "$delta" -eq 5 ] ; then
			echo -n "$c$c$c$c$c"
		elif [ "$delta" -eq 6 ] ; then
			echo -n "$c$c$c$c$c$c"
		elif [ "$delta" -eq 7 ] ; then
			echo -n "$c$c$c$c$c$c$c"
		elif [ "$delta" -eq 8 ] ; then
			echo -n "$c$c$c$c$c$c$c$c"
		elif [ "$delta" -eq 9 ] ; then
			echo -n "$c$c$c$c$c$c$c$c$c"
		else 
			echo -n "$c$c$c$c$c$c$c$c$c$c"
		fi
		lastbar="$thisbar"
	elif [ "$finish" -eq 1 ] && [ "$thisbar" -le 60 ] ; then
		delta=$(( 60 - $thisbar ))
#	echo "finish=$finish fr=$fr frames=$frames delta=$delta"
		if [ "$delta" -le 0 ] ; then 
			echo ""
		elif [ "$delta" -eq 1 ] ; then 
			echo "$c"
		elif [ "$delta" -eq 2 ] ; then
			echo "$c$c"
		elif [ "$delta" -eq 3 ] ; then
			echo "$c$c$c"
		elif [ "$delta" -eq 4 ] ; then
			echo "$c$c$c$c"
		elif [ "$delta" -eq 5 ] ; then
			echo "$c$c$c$c$c"
		elif [ "$delta" -eq 6 ] ; then
			echo "$c$c$c$c$c$c"
		elif [ "$delta" -eq 7 ] ; then
			echo "$c$c$c$c$c$c$c"
		elif [ "$delta" -eq 8 ] ; then
			echo "$c$c$c$c$c$c$c$c"
		elif [ "$delta" -eq 9 ] ; then
			echo "$c$c$c$c$c$c$c$c$c"
		else 
			echo "$c$c$c$c$c$c$c$c$c$c"
		fi
		logecho "[dvd-slideshow]############################################################"
	fi
}

finish_progressbar ()
# finish_progressbar  $fr $frames $char
{
	local fr=$1 ; local frames=$2
	if [ -z "$3" ] ; then
		local c='#'
	else
		local c="$3"
	fi
	local thisbar=$(( $fr * 59 / $frames  ))
	if [ "$thisbar" -lt 60 ] ; then
		delta=$(( 60 - $thisbar ))
		if [ "$delta" -eq 1 ] ; then 
			echo "$c"
		elif [ "$delta" -eq 2 ] ; then
			echo "$c$c"
		elif [ "$delta" -eq 3 ] ; then
			echo "$c$c$c"
		elif [ "$delta" -eq 4 ] ; then
			echo "$c$c$c$c"
		elif [ "$delta" -eq 5 ] ; then
			echo "$c$c$c$c$c"
		elif [ "$delta" -eq 6 ] ; then
			echo "$c$c$c$c$c$c"
		elif [ "$delta" -eq 7 ] ; then
			echo "$c$c$c$c$c$c$c"
		elif [ "$delta" -eq 8 ] ; then
			echo "$c$c$c$c$c$c$c$c"
		elif [ "$delta" -eq 9 ] ; then
			echo "$c$c$c$c$c$c$c$c$c"
		else 
			echo "$c$c$c$c$c$c$c$c$c$c"
		fi
	else
		echo ""
	fi
	logecho "[dvd-slideshow]############################################################"
}

set_system_variables ()
{
	## check for config variables: only specified once per slideshow
	config=`echo "$1" | cut -d= -f1 | tr -d \[:blank:\]`
	config2=`echo "$1" | tr '\t' ' ' | tr -d '\047' | tr -d '\042' | cut -d= -f2 | awk -F' #' '{print $1}' | tr -d \[:blank:\]`
#	config2=`echo "$1" | cut -d= -f2 | awk -F' #' '{print $1}' | tr -d \[:blank:\]`
	[ -n "$2" -a "$2" == 1 ] && noecho=1 || noecho=0
	## check for global configuration variables:
	case "$config" in 
        	debug) debug="$config2" ; [ "$noecho" -eq 0 ] && echo "debug=$debug" ;;
		pal) pal="$config2" ; [ "$noecho" -eq 0 ] && echo "pal=$pal" ;;
		ac3) ac3="$config2" ; [ "$noecho" -eq 0 ] && echo "ac3=$ac3" ;;
		copy) copy="$config2" ; [ "$noecho" -eq 0 ] && echo "copy=$copy" ;;
		autocrop) autocrop="$config2" ; [ "$noecho" -eq 0 ] && echo "autocrop=$autocrop" ;;
		high_quality) high_quality="$config2" ; [ "$noecho" -eq 0 ] && echo "high_quality=$high_quality" ;;
		title_font) title_font="$config2" ; [ "$noecho" -eq 0 ] && echo "title_font=$title_font" ;; 
		# subtitle
		subtitle_type) subtitle_type="$config2" ; [ "$noecho" -eq 0 ] && echo "subtitle_type=$subtitle_type" ;;
		theme) theme="$config2" ; [ "$noecho" -eq 0 ] && echo "theme=$theme" ;; 
		theme_designed_for) theme_designed_for="$config2" ; [ "$noecho" -eq 0 ] && echo "theme_designed_for=$theme_designed_for" ;; 
		widescreen) widescreen="$config2" ; [ "$noecho" -eq 0 ] && echo "widescreen=$widescreen" ;;  #
	esac
}

set_theme ()
{
	## check for config variables: only specified once per slideshow
	config=`echo "$1" | cut -d= -f1 | tr -d \[:blank:\]`
	config2=`echo "$1" | tr '\t' ' ' | tr -d '\047' | tr -d '\042' | cut -d= -f2 | awk -F' #' '{print $1}' | tr -d \[:blank:\]`
#	config2=`echo "$1" | cut -d= -f2 | awk -F' #' '{print $1}' | tr -d \[:blank:\]`
	[ -n "$2" -a "$2" == 1 ] && local noecho=1 || local noecho=0
	## check for global configuration variables:
	case "$config" in 
		theme) theme="$config2" ; [ "$noecho" -eq 0 ] && echo "$theme" ;;
	esac
}

duration2frames ()
# duration2frames $time_added_ms
{
	## calculate the time point that we're at:
	local current_time=$1
	# calculate current time and frame before adding this extra rendered time:

	local this_start_time=$total_slideshow_time # before adding current rendered time
	local this_start_frame=$total_slideshow_frames

	local total_slideshow_time=$(( $total_slideshow_time + $current_time ))
	local time_to_render=$(( $total_slideshow_time - $this_start_time ))
	local total_slideshow_frames=`div1000 $(( $frames_per_ms * $total_slideshow_time / 1000 ))`
	local frames=$(( $total_slideshow_frames - $this_start_frame ))
	if [ "$frames" -le 2 ] ; then
		frames=2  # this is needed because avconv seems to crash when encoding only one frame!
	fi
	echo "$frames"
}

set_end_frame_time ()
# set_end_frame_time $time_added_ms
{
	## calculate the time point that we're at:
	local current_time=$1
	# calculate current time and frame before adding this extra rendered time:

	this_start_time=$total_slideshow_time # before adding current rendered time
	this_start_frame=$total_slideshow_frames

	total_slideshow_time=$(( $total_slideshow_time + $current_time ))
	time_to_render=$(( $total_slideshow_time - $this_start_time ))
	total_slideshow_frames=`div1000 $(( $frames_per_ms * $total_slideshow_time / 1000 ))`
	frames_to_render=$(( $total_slideshow_frames - $this_start_frame ))

	slide_end_time=$total_slideshow_time  ## in thousandths of a second
	slide_end_frame="$total_slideshow_frames"
	slide_end_hms=`hms $slide_end_time`
}

truncate_filename ()
{
	# truncate filenames so they're not longer than 40 characters:
	local length="${#1}"
	if [ $length -gt 40 ] ; then
		local pos=$(( $length - 40 ))
		echo "...${1:$pos}"
	else
		echo "$1"
	fi
}

create_slide ()
# create_slide $file $outfile $transparent
# does autocropping and compositing over background if required
{
	local file="$1"
	if [ -n "$2" ] ; then
		local output_file="$2"
	else
		local output_file="$tmpdir/slide_$i.ppm"
	fi
	if [ -n "$3" ] && [ -f "$3" ] ; then
		local bg="$3"
	else
		local bg="$tmpdir"/slideshow_background.ppm
	fi
	rm -f "$output_file"
	# postprocessing options:
	# add sepia, black_and_white, old, etc...
	if [ "$image_postprocess" == 'shadow' ] && [ "$border" -gt 0 ] ; then
		postprocess='( +clone  -background black  -shadow 80x3+5+5 ) +swap -background none -mosaic'
	else
		postprocess=''
	fi
	checkforautocrop "$file"	
	if [ "$do_autocrop_h" -eq 1 ] ; then
		convert -size "$frame_width"x"$frame_height" "$file" \
			-filter $filtermethod \
			-resize "$sq_to_dvd_pixels" \
			-resize "$frame_width"x \
			-type TrueColorMatte -depth 8 \
			-gravity center \
			-crop "$frame_width"x"$frame_height"'+0!+0!' \
			$sharpen $postprocess +repage miff:- \
		| composite -compose src-over \
			-gravity center \
			-type TrueColorMatte -depth 8 - "$bg" "$output_file"
	elif [ "$do_autocrop_w" -eq 1 ] ; then
		convert -size "$frame_width"x"$frame_height" "$file" \
			-filter $filtermethod \
			-resize "$sq_to_dvd_pixels" \
			-resize x"$frame_height" \
			-type TrueColorMatte -depth 8 \
			-gravity center \
			-crop "$frame_width"x"$frame_height"'+0!+0!' \
			$sharpen $postprocess +repage miff:- \
		| composite -compose src-over \
			-gravity center -type TrueColorMatte -depth 8 - "$bg" "$output_file"
	else
		convert -size "$frame_width"x"$frame_height" "$file" \
			-filter $filtermethod \
			-resize "$sq_to_dvd_pixels" \
			-resize "$frame_width"x"$frame_height" \
			-type TrueColorMatte -depth 8 \
			$sharpen $postprocess miff:- \
		| composite -compose src-over \
			-gravity center -type TrueColorMatte -depth 8 - "$bg" "$output_file"
	fi
}


scroll ()  # SCROLL
# scroll $direction $file $bg $total_frames [$startframe] [$lastframe] [$char]
{
	local l_direction="$1"
	local l_file="$2"
	local l_bg="$3"
	local l_frames="$4"
	lastbar=0 # required for progressbar to set back to zero
	[ -z "$5" ] && local l_startframe="1" || local l_startframe="$5"
	[ -z "$6" ] && local l_endframe="$l_frames" || local l_endframe="$6"
	[ -z "$7" ] && local c='#' || local c="$7"
	if [ "$3" == "$transparent_bg" ] ; then
		local suffix='png'
	else
		local suffix='ppm'
	fi
	[ "$debug" -ge 2 ] && myecho "scroll $l_direction $l_file $l_bg $l_frames $l_startframe $l_endframe $c $suffix"
	image_width="`imagewidth "$l_file"`"
	image_height="`imageheight "$l_file"`"
	## calculate frame size after adding black side bars for portrait pictures:
	if [ $image_width -gt $image_height ] ; then
		# landscape:  (for scroll left/right)
		convert -size "$frame_width"x"$frame_height" "$l_file" -filter $filtermethod -resize "$sq_to_dvd_pixels" -resize x"$frame_height" +repage $sharpen -type TrueColorMatte -depth 8 "$tmpdir"/temp_slideshow_image_scaled.mpc		
	else
		# portrait:  (for scroll up/down )
		convert -size "$frame_width"x"$frame_height" "$l_file" -filter $filtermethod -resize "$sq_to_dvd_pixels" -resize "$frame_width" +repage $sharpen -type TrueColorMatte -depth 8 "$tmpdir"/temp_slideshow_image_scaled.mpc		
	fi

	# now the image is scaled so the height is correct
	image_width="`imagewidth_sq "$tmpdir/temp_slideshow_image_scaled.mpc"`" # already non-suqare pixels
	image_height="`imageheight "$tmpdir/temp_slideshow_image_scaled.mpc"`"
	[ "$debug" -ge 2 ] && myecho "[dvd-slideshow:scroll] Temp image_width=$image_width image_height=$image_height"
	## these are the crop parameters that will be used to crop the temp image:
	if [ "$l_direction" == 'right' ] ; then
#		myecho "[dvd-slideshow] Doing scroll right effect"
		xs0=0 ; ys0=0 # scroll right
		xe0=$(( $image_width - $frame_width )) ; ye0=0
	elif [ "$l_direction" == 'left' ] ; then
#		myecho "[dvd-slideshow] Doing scroll left effect"
		xs0=$(( $image_width - $frame_width )) ; ys0=0
		xe0=0 ; ye0=0 # scroll left
	elif [ "$l_direction" == 'up' ] ; then
#		myecho "[dvd-slideshow] Doing scroll up effect"
		xs0=0 ; ys0=$(( $image_height - $frame_height )) 
		xe0=0 ; ye0=0 # scroll up
	elif [ "$l_direction" == 'down' ] ; then
#		myecho "[dvd-slideshow] Doing scroll down effect"
		xs0=0 ; ys0=0 # scroll down
		xe0=0 ; ye0=$(( $image_height - $frame_height )) 
	else
		myecho "[dvd-slideshow:scroll] ERROR: bad effect parameters $l_direction"
		cleanup; exit 1
	fi
	[ "$debug" -ge 2 ] && myecho "[dvd-slideshow:scroll] params=$xs0,$ys0 ; $xe0,$ye0"
	if [ "$low_quality" -eq 1 ] ; then
		stepsize=3; interp=0
	elif [ "$high_quality" -eq 1 ] ; then
		stepsize=1; interp=1
	else
#		[ "$l_frames" -lt 45 ] && stepsize=1 || stepsize=2 
		stepsize=1; interp=0
	fi
	xvelocity=$(( 1000 * ($xe0-$xs0) / $l_frames ))
	yvelocity=$(( 1000 * ($ye0-$ys0) / $l_frames ))
	[ $debug -ge 2 ] && myecho "[dvd-slideshow:scroll] xVelocity=$xvelocity yVelocity=$yvelocity interp=$interp"
#	if [ "$interp" -eq 1 ] && [ "$yvelocity" -eq 0 ] && [ "$xvelocity" -lt 4000 ] ; then
#		[ $debug -ge 1 ] && myecho "[dvd-slideshow:scroll] Using interpolation. xVelocity=$xvelocity"
#	elif [ "$interp" -eq 1 ] && [ "$xvelocity" -eq 0 ] && [ "$yvelocity" -lt 4000 ] ; then
#		[ $debug -ge 1 ] && myecho "[dvd-slideshow:scroll] Using interpolation. yVelocity=$yvelocity"
#	elif [ "$interp" -eq 1 ] ; then
#		[ $debug -ge 1 ] && myecho "[dvd-slideshow:scroll] No need to use high-quality mode for a fast scroll... disabling -H"
#		interp=0
#	fi
	## smooth start and end parameters:
	F1=$(( $l_frames * 10 / 100 ))  # 10 percent smoothing
	F2=$(( $l_frames - $F1 ))	
	V0x=$( echo "scale=9; 2 * ( $xe0 - $xs0 ) / ( $l_frames + $F2 - $F1 -2 )" | bc )  # hack -2 to make it fit better?
	V0y=$( echo "scale=9; 2 * ( $ye0 - $ys0 ) / ( $l_frames + $F2 - $F1 -2 )" | bc )
	pi='3.14159265'
	[ $debug -ge 2 ] &&  myecho "[dvd-slideshow:scroll] end_frame_number=$slide_end_frame end_time=$slide_end_hms"
	echo -n "[dvd-slideshow]"
	lastbar=0 # required for progressbar
	for (( fr=l_startframe ; fr<=l_endframe ; fr=fr+stepsize )) ; do
		dj=`addzeros $fr`
		progressbar $(( $fr - $l_startframe +1 )) $(( $l_endframe - $l_startframe + 1 )) "$c"
#		if [ "$interp" -eq 1 ] ; then
#			x0=$( echo "scale=3; $xs0 + ($xe0-$xs0)* $fr / $l_frames" | bc )
#			y0=$( echo "scale=3; $ys0 + ($ye0-$ys0)* $fr / $l_frames" | bc )
#			x0_dec=`printf %3.3f $x0 | awk -F. '{print "0."$2}'`; 
#			y0_dec=`printf %3.3f $y0 | awk -F. '{print "0."$2}'`;
#			## Fix numbers without leading zeros:
#			it=`echo "$x0" | awk -F. '{print $1}'` ; [ -z "$it" ] && x0_whole=0 || x0_whole="$it"
#			it=`echo "$y0" | awk -F. '{print $1}'` ; [ -z "$it" ] && y0_whole=0 || y0_whole="$it"
#			# calculate subpixel-averaging weights:
#                        Afactor=$( echo "scale=3; 100*(1-$x0_dec)*(1-$y0_dec)" | bc )
#                        Bfactor=$( echo "scale=3; 100*($x0_dec)*(1-$y0_dec)" | bc )
#                        Cfactor=$( echo "scale=3; 100*(1-$x0_dec)*($y0_dec)" | bc )
#                        Dfactor=$( echo "scale=3; 100*($x0_dec)*($y0_dec)" | bc )
#	                Afactor=`printf %3.0f $Afactor | tr -d \[:blank:\]`
#	                Bfactor=`printf %3.0f $Bfactor | tr -d \[:blank:\]`
#	                Cfactor=`printf %3.0f $Cfactor | tr -d \[:blank:\]`
#	                Dfactor=`printf %3.0f $Dfactor | tr -d \[:blank:\]`
#			convolve="-convolve 0,0,0,0,$Afactor,$Bfactor,0,$Cfactor,$Dfactor"
#			[ $debug -ge 3 ] && myecho "[dvd-slideshow:scroll] x0=$x0 y0=$y0 Af=$Afactor Bf=$Bfactor Cf=$Cfactor Df=$Dfactor"
#		else
			# no interpolation
		if [ $fr -le $F1 ] ; then
			# region 1
			x0=$( echo "scale=3; $xs0 + $V0x/2 *($fr - $F1/$pi *s($pi*$fr/$F1))" | bc -l )
			y0=$( echo "scale=3; $ys0 + $V0y/2 *($fr - $F1/$pi *s($pi*$fr/$F1))" | bc -l )
			[ $debug -ge 3 ] && myecho "[dvd-slideshow:scroll] $fr x0=$x0 y0=$y0 region 1"
			D1x=$x0; D1y=$y0
			x0_dec=`printf %3.3f $x0 | awk -F. '{print "0."$2}'`; 
			y0_dec=`printf %3.3f $y0 | awk -F. '{print "0."$2}'`;
			## Fix numbers without leading zeros:
			it=`echo "$x0" | awk -F. '{print $1}'` ; [ -z "$it" ] && x0_whole=0 || x0_whole="$it"
			it=`echo "$y0" | awk -F. '{print $1}'` ; [ -z "$it" ] && y0_whole=0 || y0_whole="$it"
			# round x0 and y0 to nearest integer:
			it=$( echo "scale=3; 1000* $x0" | bc -l )
			it=`echo "$it" | awk -F. '{print $1}'` ; [ -z "$it" ] && it=0 
			x0=$( div1000 $it )	
			it=$( echo "scale=3; 1000* $y0" | bc -l )
			it=`echo "$it" | awk -F. '{print $1}'` ; [ -z "$it" ] && it=0 
			y0=$( div1000 $it)	
		elif [ $fr -ge $F2 ] ; then
			# region 3
			x0=$( echo "scale=3; $D2x + $V0x/2 *( ($fr-$F2) + ($l_frames-$F2)/$pi*s(($fr-$F2)*$pi/($l_frames-$F2)) )" | bc -l )
			y0=$( echo "scale=3; $D2y + $V0y/2 *( ($fr-$F2) + ($l_frames-$F2)/$pi*s(($fr-$F2)*$pi/($l_frames-$F2)) )" | bc -l )
			[ $debug -ge 3 ] && myecho "[dvd-slideshow:scroll] $fr x0=$x0 y0=$y0 region 3"
			x0_dec=`printf %3.3f $x0 | awk -F. '{print "0."$2}'`; 
			y0_dec=`printf %3.3f $y0 | awk -F. '{print "0."$2}'`;
			## Fix numbers without leading zeros:
			it=`echo "$x0" | awk -F. '{print $1}'` ; [ -z "$it" ] && x0_whole=0 || x0_whole="$it"
			it=`echo "$y0" | awk -F. '{print $1}'` ; [ -z "$it" ] && y0_whole=0 || y0_whole="$it"
			# round x0 and y0 to nearest integer:
			it=$( echo "scale=3; 1000* $x0" | bc -l )
			it=`echo "$it" | awk -F. '{print $1}'` ; [ -z "$it" ] && it=0 
			x0=$( div1000 $it )	
			it=$( echo "scale=3; 1000* $y0" | bc -l )
			it=`echo "$it" | awk -F. '{print $1}'` ; [ -z "$it" ] && it=0 
			y0=$( div1000 $it )	
		else
			# middle region 2
			x0=$( echo "scale=3; $D1x + $V0x*($fr-$F1)" | bc )
			y0=$( echo "scale=3; $D1y + $V0y*($fr-$F1)" | bc )
			D2x=$x0 ; D2y=$y0
			[ $debug -ge 3 ] && myecho "[dvd-slideshow:scroll] $fr x0=$x0 y0=$y0 region 2"
			x0_dec=`printf %3.3f $x0 | awk -F. '{print "0."$2}'`; 
			y0_dec=`printf %3.3f $y0 | awk -F. '{print "0."$2}'`;
			## Fix numbers without leading zeros:
			it=`echo "$x0" | awk -F. '{print $1}'` ; [ -z "$it" ] && x0_whole=0 || x0_whole="$it"
			it=`echo "$y0" | awk -F. '{print $1}'` ; [ -z "$it" ] && y0_whole=0 || y0_whole="$it"
			# round x0 and y0 to nearest integer:
			it=$( echo "scale=3; 1000* $x0" | bc )
			it=`echo "$it" | awk -F. '{print $1}'` ; [ -z "$it" ] && it=0 
			x0=$( div1000 $it )	
			it=$( echo "scale=3; 1000* $y0" | bc )
			it=`echo "$it" | awk -F. '{print $1}'` ; [ -z "$it" ] && it=0 
			y0=$( div1000 $it )	
		fi
		it="${effect1_params[$i]}"
		if [ "$interp" -eq 1 ] ; then
			# calculate subpixel-averaging weights:
	                Afactor=$( echo "scale=3; 100*(1-$x0_dec)*(1-$y0_dec)" | bc )
       		       	Bfactor=$( echo "scale=3; 100*($x0_dec)*(1-$y0_dec)" | bc )
               	 	Cfactor=$( echo "scale=3; 100*(1-$x0_dec)*($y0_dec)" | bc )
	                Dfactor=$( echo "scale=3; 100*($x0_dec)*($y0_dec)" | bc )
		        Afactor=`printf %3.0f $Afactor | tr -d \[:blank:\]`
		        Bfactor=`printf %3.0f $Bfactor | tr -d \[:blank:\]`
		        Cfactor=`printf %3.0f $Cfactor | tr -d \[:blank:\]`
		        Dfactor=`printf %3.0f $Dfactor | tr -d \[:blank:\]`
#			echo "$dj,$frame_width,$frame_height,$frame_border,$x0,$y0,$x0_whole,$y0_whole,$x0_dec,$y0_dec,$Afactor,$Bfactor,$Cfactor,$Dfactor" >> "$outdir/scroll.csv"
			[ $debug -ge 3 ] && myecho "[dvd-slideshow:scroll] x0=$x0 y0=$y0 Af=$Afactor Bf=$Bfactor Cf=$Cfactor Df=$Dfactor"
			convolve="-convolve 0,0,0,0,$Afactor,$Bfactor,0,$Cfactor,$Dfactor"
			if [ "$smp" -eq 1 ] ; then
				if [ "$frame_border" -eq 0 ] ; then
			    	convert "$tmpdir"/temp_slideshow_image_scaled.mpc -crop "$frame_width"x"$frame_height"+"$x0_whole"+"$y0_whole" $convolve +repage -type TrueColorMatte -depth 8 "$tmpdir/fade_$dj.$suffix" &
				else
			    	(convert "$tmpdir"/temp_slideshow_image_scaled.mpc -crop "$frame_width"x"$frame_height"+"$x0_whole"+"$y0_whole" $convolve +repage -type TrueColorMatte -depth 8 miff:- | composite -compose src-over -geometry "+$frame_border+$frame_border" -type TrueColorMatte -depth 8 - "$normal_bg" "$tmpdir/fade_$dj.$suffix") &
				fi
			else
				if [ "$frame_border" -eq 0 ] ; then
			    	convert "$tmpdir"/temp_slideshow_image_scaled.mpc -crop "$frame_width"x"$frame_height"+"$x0_whole"+"$y0_whole" $convolve +repage -type TrueColorMatte -depth 8 "$tmpdir/fade_$dj.$suffix"
				else
			    	convert "$tmpdir"/temp_slideshow_image_scaled.mpc -crop "$frame_width"x"$frame_height"+"$x0_whole"+"$y0_whole" $convolve +repage -type TrueColorMatte -depth 8 miff:- | composite -compose src-over -geometry "+$frame_border+$frame_border" -type TrueColorMatte -depth 8 - "$normal_bg" "$tmpdir/fade_$dj.$suffix" 
				fi
			fi
		else # no interp
			convolve=""
			[ $debug -ge 3 ] && echo "[dvd-slideshow:scroll] $dj crop:$frame_width"x"$frame_height"+"$x0"+"$y0 composite: +$frame_border"+"$frame_border"
			if [ "$smp" -eq 1 ] ; then
				if [ "$frame_border" -eq 0 ] ; then
				(convert "$tmpdir/temp_slideshow_image_scaled.mpc" -crop "$frame_width"x"$frame_height"+$x0+$y0 -type TrueColorMatte -depth 8 "$tmpdir/fade_$dj.$suffix" ; add_logo "$logo" fade_$dj.$suffix "$logo_gravity" ; extracopies $fr $l_frames $suffix ) &
				else
				(convert "$tmpdir/temp_slideshow_image_scaled.mpc" -crop "$frame_width"x"$frame_height"+$x0+$y0 +repage -type TrueColorMatte -depth 8  miff:- | composite -compose src-over -geometry "+$frame_border+$frame_border" -type TrueColorMatte -depth 8 - "$normal_bg" "$tmpdir/fade_$dj.$suffix" ; add_logo "$logo" fade_$dj.$suffix "$logo_gravity" ; extracopies $fr $l_frames $suffix ) &
				fi
			else
				if [ "$frame_border" -eq 0 ] ; then
				(convert "$tmpdir/temp_slideshow_image_scaled.mpc" -crop "$frame_width"x"$frame_height"+$x0+$y0 -type TrueColorMatte -depth 8 "$tmpdir/fade_$dj.$suffix" ; add_logo "$logo" fade_$dj.$suffix "$logo_gravity" ; extracopies $fr $l_frames $suffix )
				else
				(convert "$tmpdir/temp_slideshow_image_scaled.mpc" -crop "$frame_width"x"$frame_height"+$x0+$y0 +repage -type TrueColorMatte -depth 8  miff:- | composite -compose src-over -geometry "+$frame_border+$frame_border" -type TrueColorMatte -depth 8 - "$normal_bg" "$tmpdir/fade_$dj.$suffix" ; add_logo "$logo" fade_$dj.$suffix "$logo_gravity" ; extracopies $fr $l_frames $suffix )
				fi
			fi
		fi
	done
	waitforfiles "$tmpdir/fade" $suffix $dj $l_startframe
	finish_progressbar $(( $fr - $l_startframe +1 )) $(( $l_endframe - $l_startframe + 1 )) "$c"
}

full_path ()   # from Shea Martin, modified by scott dylewski
{
unset CDPATH
if [ -f "$1" ]; then
        DIR="$(dirname "$1")"
        DIR=$(cd "$DIR" && pwd)
        FILE="$(basename "$1")"
        RSLT="$?"
        echo "$DIR/$FILE"
        return "$RSLT"
elif [ -d "$1" ]; then
        DIR="$1"
	FILE="$( cd "$DIR" && pwd)"
	RSLT=$?
        echo "$FILE"
	return $RSLT
else
        echo "unknown file: $1"
        return 1
fi
}

set_variables ()   # SET_VARIABLES
{
	## check for config variables:
	config1=`echo "$1" | cut -d= -f1 | tr -d \[:blank:\]`
	config2=`echo "$1" | tr '\t' ' ' | cut -d= -f2 | tr -d '\047' | tr -d '\042' | awk -F' #' '{print $1}' | tr -d \[:blank:\]`
	[ -n "$2" -a "$2" == 1 ] && noecho=1 || noecho=0
	## check for global configuration variables:
	case "$config1" in 
		debug) debug="$config2" ; [ "$noecho" -eq 0 ] && echo "debug=$debug" ;;
		# title
		title_font_size) title_font_size="$config2" ; [ "$noecho" -eq 0 ] && echo "title_font_size=$title_font_size" ;;
		title_font_color) title_font_color="$config2" ; [ "$noecho" -eq 0 ] && echo "title_font_color=$title_font_color" ;;
		# top title
		toptitle_font_size) toptitle_font_size="$config2" ; [ "$noecho" -eq 0 ] && echo "toptitle_font_size=$toptitle_font_size" ;;
		toptitle_font_color) toptitle_font_color="$config2" ; [ "$noecho" -eq 0 ] && echo "toptitle_font_color=$toptitle_font_color" ;;
		toptitle_bar_height) toptitle_bar_height="$config2" ; [ "$noecho" -eq 0 ] && echo "toptitle_bar_height=$toptitle_bar_height" ;;
		toptitle_text_location_x) toptitle_text_location_x="$config2" ; [ "$noecho" -eq 0 ] && echo "toptitle_text_location_x=$toptitle_text_location_x" ;;
		toptitle_text_location_y) toptitle_text_location_y="$config2" ; [ "$noecho" -eq 0 ] && echo "toptitle_text_location_y=$toptitle_text_location_y" ;;
		# bottom title
		bottomtitle_font_size) bottomtitle_font_size="$config2" ; [ "$noecho" -eq 0 ] && echo "bottomtitle_font_size=$bottomtitle_font_size" ;;
		bottomtitle_font_color) bottomtitle_font_color="$config2" ; [ "$noecho" -eq 0 ] && echo "bottomtitle_font_color=$bottomtitle_font_color" ;;
		bottomtitle_bar_location_y) bottomtitle_bar_location_y="$config2" ; [ "$noecho" -eq 0 ] && echo "bottomtitle_bar_location_y=$bottomtitle_bar_location_y" ;;
		bottomtitle_bar_height) bottomtitle_bar_height="$config2" ; [ "$noecho" -eq 0 ] && echo "bottomtitle_bar_height=$bottomtitle_bar_height" ;;
		bottomtitle_text_location_x) bottomtitle_text_location_x="$config2" ; [ "$noecho" -eq 0 ] && echo "bottomtitle_text_location_x=$bottomtitle_text_location_x" ;;
		bottomtitle_text_location_y) bottomtitle_text_location_y="$config2" ; [ "$noecho" -eq 0 ] && echo "bottomtitle_text_location_y=$bottomtitle_text_location_y" ;;
		border) border="$config2" ; frame_border=$border ; frame_width=$(( $dvd_width - 2 * $frame_border )); frame_height=$(( $dvd_height - 2 * $frame_border )) ; [ "$noecho" -eq 0 ] && echo "border=$border" ;;
		slideshow_image_filter) image_postprocess="$config2" ; image_postprocess=$image_postprocess ; [ "$noecho" -eq 0 ] && echo "image_postprocess=$image_postprocess" ;;
		sharpen) sharpen="$config2" ; [ "$noecho" -eq 0 ] && echo "sharpen=$sharpen" ;;
		kenburns_acceleration) kenburns_acceleration="$config2" ; [ "$noecho" -eq 0 ] && echo "kenburns_acceleration=$kenburns_acceleration" ;;
		subtitle_font) subtitle_font="$config2" ; [ "$noecho" -eq 0 ] && echo "subtitle_font=$subtitle_font" ;;
		subtitle_font_size) subtitle_font_size="$config2" ; [ "$noecho" -eq 0 ] && echo "subtitle_font_size=$subtitle_font_size" ;;
		subtitle_color) subtitle_color="$config2" ; [ "$noecho" -eq 0 ] && echo "subtitle_color=$subtitle_color" ;;
		subtitle_outline_color) subtitle_outline_color="$config2" ; [ "$noecho" -eq 0 ] && echo "subtitle_outline_color=$subtitle_outline_color" ;;
		subtitle_location) subtitle_location="$config2" ; [ "$noecho" -eq 0 ] && echo "subtitle_location=$subtitle_location" ;;
		subtitle_location_x) subtitle_location_x="$config2" ; [ "$noecho" -eq 0 ] && echo "subtitle_location_x=$subtitle_location_x" ;;
		subtitle_location_y) subtitle_location_y="$config2" ; [ "$noecho" -eq 0 ] && echo "subtitle_location_y=$subtitle_location_y" ;;
		logo) logo="$config2" ; [ "$noecho" -eq 0 ] && echo "logo=$logo" ;;
		logo_gravity) logo_gravity="$config2" ; [ "$noecho" -eq 0 ] && echo "logo_gravity=$logo_gravity" ;;
	esac
}

print_themes ()  # print the names of the built-in themes and quit
{
# check in default theme directory:
if [ -d "$themedir" ] ; then
	echo "[dvd-slideshow] Using themes directory $themedir"
	echo "[dvd-slideshow] Found built-in themes:"
	find "$themedir"/ -maxdepth 2 -name "*.theme" -type f -print0 | xargs -0 ls
	if [ -d "$local_themedir" ] ; then
		echo "[dvd-slideshow] Found local themes directory $local_themedir"
		echo "[dvd-slideshow] Found local themes:"
		find "$local_themedir"/ -maxdepth 2 -name "*.theme" -type f -print0 | xargs -0 ls
	fi
        exit 0
else
	echo "[dvd-slideshow] Themes directory not found: $themedir"
	exit 0
fi
}

read_theme ()
# read_theme $theme
{
local theme=$1
[ -n "$2" -a "$2" == 1 ] && local noecho=1 || local noecho=0
## read in theme file if it exists:
if [ -n "$theme" ] ; then
        # check if directory
        if [ -d "$theme" ] ; then
                themedir="$theme"
                themefile="`ls -1 "$theme"/*.theme 2> /dev/null | tail -n 1`"
                [ "$noecho" == '0' ] && myecho "[dvd-slideshow] Using theme $(truncate_filename "$theme")"
        elif [ -f "$theme" ] ; then
                themefile="`full_path "$theme"`"
                themedir="`dirname "$theme"`"
                [ "$noecho" == '0' ] && myecho "[dvd-slideshow] Using theme $(truncate_filename "$theme")"
        else
                # check in default theme directory:
                if [ -d "$themedir"/"$theme" ] ; then
                        themedir="$themedir"/"$theme"
                        themefile="`ls -1 "$themedir"/*.theme 2> /dev/null | tail -n 1`"
                	[ "$noecho" == '0' ] && myecho "[dvd-slideshow] Using theme file $theme"
                elif [ -d "$local_themedir"/"$theme" ] ; then
                        themedir="$local_themedir"/"$theme"
                        themefile="`ls -1 "$themedir"/*.theme 2> /dev/null | tail -n 1`"
                	[ "$noecho" == '0' ] && myecho "[dvd-slideshow] Using theme file $theme"
                else
                        [ "$noecho" == '0' ] && myecho "[dvd-slideshow] ERROR!  Bad theme name (not found)"
                        exit 1
                fi
        fi
        [ "$noecho" == '0' ] && myecho "[dvd-slideshow] Reading theme file..."
	local thisline=0
	while read thisline
        do
	  set_system_variables "${thisline}" 1
	  it=`set_system_variables "${thisline}" 0`
	  if [ -n "$it" ] ; then
		[ "$noecho" == '0' ] && myecho "[dvd-slideshow] Set system variable $it"
		continue
	  fi

	  set_variables "${thisline}" 1
	  it=`set_variables "${thisline}" 0`
	  if [ -n "$it" ] ; then
		[ "$noecho" == '0' ] && myecho "[dvd-slideshow] Set variable $it"
		continue
	  fi
        done < "$themefile"
	if [ -n "$title_font" ] ; then
	        if [ ! -f "$title_font" ] ; then
	                title_font="$themedir"/"$title_font"
	                if [ ! -f "$title_font" ] ; then
	                        echo "Error:  bad title_font filename in theme"
	                fi
	        fi
	fi
	if [ -n "$subtitle_font" ] ; then
	        if [ ! -f "$subtitle_font" ] ; then
	                subtitle_font="$themedir"/"$subtitle_font"
	                if [ ! -f "$subtitle_font" ] ; then
	                        echo "Error:  bad subtitle_font filename in theme"
	                fi
	        fi
	fi
	# now, modify theme depending on ntsc/pal:
	if [ -z "$theme_designed_for" ] ; then
		theme_designed_for="ntsc"
	fi
	if [ "$theme_designed_for" == 'pal' ] && [ "$pal" == 0 ] ; then
		# shift coordinates down by 96?
		myecho "[dvd-slideshow] Theme designed for PAL. Shifting coordinates to NTSC"
	elif [ "$theme_designed_for" == 'ntsc' ] && [ "$pal" == 1 ] ; then
		# shift coordinates down by 96?
		myecho "[dvd-slideshow] Theme designed for NTSC. Shifting coordinates to PAL"
                #toptitle_bar_height=
                #toptitle_text_location_y
                # bottom title
                #bottomtitle_font_size
                #bottomtitle_font_color
                #bottomtitle_bar_location_y
                #bottomtitle_bar_height
                #bottomtitle_text_location_y

	fi
		
fi
}

add_logo () # LOGO
{
	local logo="$1"
	local filename="$2"
	local logo_gravity="$3"
	if [ -n "$logo" ] ; then # only do this if the logo has been specified!
		if [ -z "$logo_gravity" ] ; then
			logo_gravity="SouthEast"
		fi	
		if [ -f "$logo" ] ; then
			composite -compose src-over -gravity $logo_gravity -type TrueColorMatte -depth 8 "$logo" "$tmpdir"/"$filename" "$tmpdir"/tmp_"$filename"
			mv "$tmpdir"/tmp_"$filename" "$tmpdir"/"$filename"
		else
			myecho "[dvd-slideshow] ERROR: Logo specified but file not found:"
			myecho "[dvd-slideshow] $logo"
		fi
	fi
}

subtitle ()  # SUBTITLE
{
	# $1 = the subtitle passed
	# $2 = index to append to subtitle_$i.png
	# $3 = color
	# output is $tmpdir/subtitle_$i.png
	## fix any special characters:
	local index="$2"
	local strokewidth=2
	transparent_color="ff0101"
	if [ -z "$3" ] ; then	
		local bg_color="$transparent_color"
	else
		local bg_color="transparent"
	fi
	local mysubtitle="$( echo "$1" | sed -e 's/"/\\\\"/g' | sed -e 's/\!/\\\!/g')"
	f_subtitle_font_size=$(( $subtitle_font_size * $dvd_height / 480 ))
	characters="${#mysubtitle}"
	local limit=200
	if [ "$characters" -gt "$limit" ] ; then 
		# REALLY long subtitle!  need to truncate it!
		myecho "[dvd-slideshow] WARNING: subtitle is longer than $limit characters! Truncating"
		mysubtitle="${mysubtitle:0:$limit}"
	fi
	## check to see if we find any user-specified breaks \n
	it=`echo "$mysubtitle" | awk -F'\\' '{print $2}' | cut -c 1`
	if [ "$it" == 'n' ] ; then
		logecho "[dvd-slideshow] Found \\n in subtitle"
		# user entered a \n to force line wraps
		# break lines at line wraps
		subtitle_line1=`echo "$mysubtitle" | awk -F'\\' '{print $1}'`
		subtitle_line2=`echo "$mysubtitle" | awk -F'\\' '{print $2}' | cut -c 2-`
		subtitle_line3=`echo "$mysubtitle" | awk -F'\\' '{print $3}' | cut -c 2-`
		if [ -n "$subtitle_line3" ] ; then
			# user small font size
			f_subtitle_font_size=$(( $subtitle_font_size * 3 / 4 * $dvd_height / 480 ))
		fi
		[ $debug -ge 1 ] && myecho "[dvd-slideshow]  Line1=$subtitle_line1"
		[ $debug -ge 1 ] && myecho "[dvd-slideshow]  Line2=$subtitle_line2"
		[ $debug -ge 1 ] && myecho "[dvd-slideshow]  Line3=$subtitle_line3"
	else	# no forced line wraps. Check for long lines:	
		## make the subtitle break up into up to 4 different lines?
		font_width=$(( $f_subtitle_font_size * 2 / 3 - 1 ))
		line_width=$(( $font_width * $characters ))
		if [ "$line_width" -gt "$(( 2 * $dvd_width ))" ] ; then # $dvd_width=720
			## need to split the line into 3 lines:
			# make font size smaller
			strokewidth=1
			f_subtitle_font_size=$(( $subtitle_font_size * 3 / 4 * $dvd_height / 480 ))
			font_width=$(( $f_subtitle_font_size * 2 / 3 -1 ))
			characters="${#mysubtitle}"
			line_width=$(( $font_width * $characters ))
			characters2=$(( $characters / 3 + 1))
			characters3=$(( 2 * $characters2 ))
			# try cutting in the middle:
			subtitle_line1="${mysubtitle:0:$characters2}"
			subtitle_line2="${mysubtitle:$characters2:$characters2}" 
			subtitle_line3="${mysubtitle:$characters3:$characters2}" 
			# now re-join a potential broken word:
			if [ "${mysubtitle:$characters2:1}" != ' ' ] ; then	
				# break occurred in the middle of a word. re-join the word:
				wordend=`echo "$subtitle_line2" | awk '{print $1}'`
				wordend_length=${#wordend}
				subtitle_line1="$subtitle_line1$wordend"
				subtitle_line2="${subtitle_line2:$wordend_length}"
			fi
			if [ "${mysubtitle:$characters3:1}" != ' ' ] ; then	
				# break occurred in the middle of a word. re-join the word:
				wordend=`echo "$subtitle_line3" | awk '{print $1}'`
				wordend_length=${#wordend}
				subtitle_line2="$subtitle_line2$wordend"
				subtitle_line3="${subtitle_line3:$wordend_length}"
			fi
			[ $debug -ge 1 ] && myecho "[dvd-slideshow] Splitting long subtitle... New values:"
			[ $debug -ge 1 ] && myecho "[dvd-slideshow]  Line1=$subtitle_line1"
			[ $debug -ge 1 ] && myecho "[dvd-slideshow]  Line2=$subtitle_line2"
			[ $debug -ge 1 ] && myecho "[dvd-slideshow]  Line3=$subtitle_line3"
			subtitle_line1=`echo "$subtitle_line1" | sed -e 's/\\\!/\!/g' `
			subtitle_line2=`echo "$subtitle_line2" | sed -e 's/\\\!/\!/g' `
			subtitle_line3=`echo "$subtitle_line3" | sed -e 's/\\\!/\!/g' `
			subtitle2_location_y=$(( $subtitle_location_y * 2 / 3 ))
			subtitle3_location_y=$(( $subtitle_location_y * 1 / 3 ))
		elif [ "$line_width" -gt "$dvd_width" ] ; then # $dvd_width=720
			## need to split the line:
			characters2=$(( $characters / 2 + 1))
			# try cutting in the middle:
			subtitle_line1="${mysubtitle:0:$characters2}"
			subtitle_line2="${mysubtitle:$characters2:$characters2}" 
			subtitle_line3=""
			# now re-join a potential broken word:
			if [ "${mysubtitle:$characters2:1}" != ' ' ] ; then	
				# break occurred in the middle of a word. re-join the word:
				wordend=`echo "$subtitle_line2" | awk '{print $1}'`
				wordend_length=${#wordend}
				subtitle_line1="$subtitle_line1$wordend"
				subtitle_line2="${subtitle_line2:$wordend_length}"
			fi
			[ $debug -ge 1 ] && myecho "[dvd-slideshow] Splitting long subtitle... New values:"
			[ $debug -ge 1 ] && myecho "[dvd-slideshow]  Line1=$subtitle_line1"
			[ $debug -ge 1 ] && myecho "[dvd-slideshow]  Line2=$subtitle_line2"
			subtitle_line1=`echo "$subtitle_line1" | sed -e 's/\\\!/\!/g' `
			subtitle_line2=`echo "$subtitle_line2" | sed -e 's/\\\!/\!/g' `
			subtitle2_location_y=$(( $subtitle_location_y / 2 ))
			subtitle3_location_y=0
		else  # single line
			subtitle_line1=""
			subtitle_line2="$mysubtitle"
			subtitle_line3=""
			subtitle_line2=`echo "$subtitle_line2" | sed -e 's/\\\!/\!/g' `
			subtitle2_location_y=$(( $subtitle_location_y / 2 ))
			subtitle3_location_y=0
		fi
	fi	
#	myecho "[dvd-slideshow] $index subtitle_line1=$subtitle_line1 subtitle_line2=$subtitle_line2"
	
	## render subtitles, if necessary:
	## let dvd-slideshow render its own subtitles:
	if [ "$subtitle_location" == 'top' ] ; then
		gravity="North"
	elif [ "$subtitle_location" == 'bottom' ] ; then
		gravity="South"
	elif [ "$subtitle_location" == 'topright' ] ; then
		gravity="NorthEast"
	elif [ "$subtitle_location" == 'topleft' ] ; then
		gravity="NorthWest"
	else 
		gravity="South"
	fi
	if [ "$subtitle_type" == 'render' ] ; then
	       	convert -size $dvd_width"x"$dvd_height xc:transparent -font "$subtitle_font" -pointsize "$f_subtitle_font_size" -gravity $gravity -fill "$subtitle_color" -stroke "$subtitle_outline_color" -strokewidth $strokewidth -draw "text $subtitle_location_x,$subtitle_location_y \"$subtitle_line1\"" -draw "text $subtitle_location_x,$subtitle2_location_y \"$subtitle_line2\"" -draw "text $subtitle_location_x,$subtitle3_location_y \"$subtitle_line3\"" -blur 0x2 -stroke none -draw "text $subtitle_location_x,$subtitle_location_y \"$subtitle_line1\"" -draw "text $subtitle_location_x,$subtitle2_location_y \"$subtitle_line2\"" -draw "text $subtitle_location_x,$subtitle3_location_y \"$subtitle_line3\"" -quality 100 -type TrueColorMatte -depth 8 "$tmpdir/subtitle_$index.png"
	else
       		convert -size $dvd_width"x"$dvd_height xc:'#'$bg_color -font "$subtitle_font" -pointsize "$f_subtitle_font_size" -gravity $gravity -fill "$subtitle_color" -stroke "$subtitle_outline_color" -strokewidth $strokewidth -colors 3 +antialias -draw "text $subtitle_location_x,$subtitle_location_y \"$subtitle_line1\"" -draw "text $subtitle_location_x,$subtitle2_location_y \"$subtitle_line2\"" -draw "text $subtitle_location_x,$subtitle3_location_y \"$subtitle_line3\"" -stroke none -draw "text $subtitle_location_x,$subtitle_location_y \"$subtitle_line1\"" -draw "text $subtitle_location_x,$subtitle2_location_y \"$subtitle_line2\"" -draw "text $subtitle_location_x,$subtitle3_location_y \"$subtitle_line3\"" -quality 100 -type TrueColorMatte -depth 8 "$tmpdir/subtitle_$index.png"
	fi
}

############################################# End of functions

if [ "$print_themes" -eq 1 ] ; then
	echo "[dvd-slideshow] Printing theme list..."
	print_themes
	exit 0
fi

## check that input files and directories exist:
if [ -z "$input_txtfile" ] ; then
	input_txtfile="$1"
fi
if [ ! -f "$input_txtfile" ] ; then
	echo "[dvd-slideshow] ERROR: Input file $input_txtfile does not exist."
	exit 1
fi

# make sure a slideshow name was given:
if [ -z "$slideshow_name" ] ; then
	slideshow_name="`basename "$input_txtfile" .txt`"
	echo "[dvd-slideshow] Using default slideshow name: $slideshow_name"
fi
hilight_title="$slideshow_name"  # make default

# verity output directory exists:
if [ -z "$outdir" ] ; then
	if [ -w "`pwd`" ] ; then
		echo "[dvd-slideshow] Output directory not specified."
		echo "[dvd-slideshow] Using `pwd`"
		outdir="`pwd`"
	else
		echo '[dvd-slideshow] ERROR: Output directory not specified.'
		exit 0
	fi
fi

## make sure output directory can be written to:
if [ ! -w "$outdir" ] ; then
	echo "[dvd-slideshow] Creating output directory $outdir"
	mkdir -p "$outdir"
	if [ ! -w "$outdir" ] ; then
		echo "[dvd-slideshow] ERROR: Output directory is not writeable!"
		exit 1
	fi
fi
	
tmpdir="$outdir/dvd-slideshow_temp_$$"
yuvfifo="dvdss-pipe-$$"   # pipe to mpeg2enc process

## create temporary directory:
if [ -d "$tmpdir" ] ; then
	echo "[dvd-slideshow] Removing old temporary directory $tmpdir"
	rmdir "$tmpdir"
fi
mkdir "$tmpdir"

## initialize log file:
logfile="$slideshow_name".log
echo "[dvd-slideshow] `date`" > "$outdir/$logfile"
logecho "[dvd-slideshow] Command line was:"
logecho "[dvd-slideshow] $0 $theargs"
logecho "[dvd-slideshow] dvd-slideshow version $version" 
logecho "[dvd-slideshow] `uname -a`"
logecho "[dvd-slideshow] Output directory=$outdir" 
logecho "[dvd-slideshow] Locale: "
logecho "`locale`"

#############################################################
## Now, read in the ~/.dvd-slideshow/dvd-slideshowrc file if it exists:
if [ -f "${HOME}/.dvd-slideshow/dvd-slideshowrc" ] ; then
	myecho "[dvd-slideshow] Reading default variables in ${HOME}/.dvd-slideshow/dvd-slideshowrc"
	while read thisline
	do
	  set_system_variables "${thisline}" 1
	  it=`set_system_variables "${thisline}" 0`
	  if [ -n "$it" ] ; then
		mymyecho "[dvd-slideshow] Set system variable $it"
		continue
	  fi

	  it=`set_variables "${thisline}" 0`
	  if [ -n "$it" ] ; then
		myecho "[dvd-slideshow] Set variable $it"
		continue
	  fi
	done < "$HOME/.dvd-slideshow/dvd-slideshowrc"
fi

################################################################
## Now, set the variables that were passed on the command-line:
[ -n "$commandline_pal" ] && pal=$commandline_pal
[ -n "$commandline_autocrop" ] && autocrop=$commandline_autocrop
[ -n "$commandline_copy" ] && copy=$commandline_copy
[ -n "$commandline_ac3" ] && ac3=$commandline_ac3
[ -n "$commandline_mpeg_encoder" ] && mpeg_encoder=$commandline_mpeg_encoder
[ -n "$commandline_debug" ] && debug=$commandline_debug
[ -n "$commandline_theme" ] && theme=$commandline_theme
[ -n "$commandline_high_quality" ] && high_quality=$commandline_high_quality
[ -n "$commandline_output_size" ] && output_size=$commandline_output_size
[ -n "$commandline_output_framerate" ] && output_framerate=$commandline_output_framerate
[ -n "$commandline_border" ] && border=$commandline_border
[ -n "$commandline_sharpen" ] && sharpen=$commandline_sharpen
[ -n "$commandline_logo" ] && logo=$commandline_logo

## now, read the theme file if it was passed on the commandline:
if [ "$theme" != 'default' ] && [ -n "$theme" ] ; then
	read_theme "$theme" 0
fi

## we will read the .txt file next...

## report version of bash for debugging:
logecho "[dvd-slideshow] Using `which bash` version `bash --version | head -n 1`"
bashversion=`bash --version | head -n 1 | awk '{print $4}' | awk -F. '{print $1"."$2}'`

if [ $debug -ge 2 ] ; then
	avconv_out="$outdir"/"$logfile"
	avconv_err="$outdir"/"$logfile"
elif [ $debug -ge 1 ] ; then
	avconv_out="$outdir"/"$logfile"
	avconv_err='/dev/null'
else
	avconv_out='/dev/null'
	avconv_err='/dev/null'
fi

# version of "find"
findutils_version=`find --version | head -1 |  awk '{print $4}'`
if [ -n "$findutils_version" ] ; then
	logecho "[dvd-slideshow] Found findutils version $findutils_version"
	v1="$( echo $findutils_version | cut -d. -f1 )"
	v2="$( echo $findutils_version | cut -d. -f2 )"
	v3="$( echo $findutils_version | cut -d. -f3 )"
	if [ "$v1" -eq 4 ] && [ "$v2" -ge 3 ] ; then
		# -L option was added in findutils version 4.2.5
		find_L='-L' # use modern syntax
		find_follow=''
	elif [ "$v1" -gt 4 ] ; then
		# -L option was added in findutils version 4.2.5
		find_L='-L' # use modern syntax
		find_follow=''
	else
		find_L=''  # use old syntax
		find_follow='-follow'
		logecho "[dvd-slideshow] WARNING: Found findutils version $v1.$v2.$v3"
		logecho "[dvd-slideshow]	This version may work, but isn't tested well. Consider upgrading to a newer version of findutils."
	fi
fi

## Check for required programs
program_needed=0
it=`which ppmtoy4m 2> /dev/null`
if [ -z "$it" ] ; then # no ppmtoy4m
               myecho "[dvd-slideshow] ERROR:  no mjpegtools found for audio processing"
               myecho "[dvd-slideshow]         You need to download and install mjpegtools."
               myecho "[dvd-slideshow]         http://mjpegtools.sourceforge.net"
               myecho "[dvd-slideshow]         Debian/Ubuntu: sudo apt-get install mjpegtools"
		program_needed=1
#		cleanup ; exit 0
else
	progver=`mplex 2>&1 | grep version | awk '{ print $4 }'`
	logecho "[dvd-slideshow] Found mjpegtools version $progver"
	if ppmtoy4m -S 420mpeg2 xxxxx 2>&1 | grep -q xxxxx; then
		logecho "[dvd-slideshow] Using mjpegtools subsampling -S 420mpeg2"
		subsample='420mpeg2'
#		logecho "[dvd-slideshow] Using mjpegtools subsampling -S 444 (none)"
#		subsample='444'
	else
#		logecho "[dvd-slideshow] Using mjpegtools subsampling -S 420mpeg2"
#		subsample='420mpeg2'
		logecho "[dvd-slideshow] Using mjpegtools subsampling -S 444 (none)"
		subsample='444'
	fi
fi	
# sox
it=`which sox 2> /dev/null`
if [ -z "$it" ] ; then # no sox
               myecho "[dvd-slideshow] ERROR:  no sox found for audio processing"
               myecho "[dvd-slideshow]         You need to download and install sox."
               myecho "[dvd-slideshow]         http://sox.sourceforge.net"
               myecho "[dvd-slideshow]         Debian/Ubuntu: sudo apt-get install sox"
		program_needed=1
#		cleanup ; exit 0
else
	progver=`sox -h 2>&1 | head -n 1 | awk '{ print $3 }'`
	logecho "[dvd-slideshow] Found sox version $progver"
	progver1="$( echo ${progver#v} | awk -F. '{print $1}' )"
	progver2="$( echo ${progver#v} | awk -F. '{print $2}' )"
	if [ $progver1 -lt 14 ] ; then  # use old sox commands:
		sox_word='-w'
		sox_int='-s'
		sox_nop='-e'
		soxi=0
	elif [ $progver2 -lt 4 ]; then  # use new commands ( < 14.4.0 )
		sox_word='-2'
		sox_int='-s'
		sox_nop='-n'
		soxi=1
	else # use new commands ( >= 14.4.0 )
		sox_word='-b 16'
		sox_int='-e signed-integer'
		sox_nop='-n'
		soxi=1
	fi
	logecho "[dvd-slideshow] using sox options $sox_word $sox_nop"
fi

# ImageMagick
it=`which convert 2> /dev/null`
if [ -z "$it" ] ; then # no convert
               myecho "[dvd-slideshow] ERROR:  no ImageMagick found for audio processing"
               myecho "[dvd-slideshow]         You need to download and install ImageMagick."
               myecho "[dvd-slideshow]         http://ImageMagick.sourceforge.net"
               myecho "[dvd-slideshow]         Debian/Ubuntu: sudo apt-get install imagemagick"
		program_needed=1
#		cleanup ; exit 0
else
	progver=`convert -help | head -n 1 | awk '{ print $3 }'`
	logecho "[dvd-slideshow] Found ImageMagick version $progver"
fi
	
# GraphicsMagick
it=`which gm 2> /dev/null`
if [ -z "$it" ] && [ "$commandline_gm" -eq 1 ] ; then # no graphicsmagick
        myecho "[dvd-slideshow] WARNING: no GraphicsMagick found."
        myecho "[dvd-slideshow]         You need to download and install GraphicsMagick."
        myecho "[dvd-slideshow]         http://GraphicsMagick.sourceforge.net"
	myecho "[dvd-slideshow]         Debian/Ubuntu: sudo apt-get install graphicsmagick"
	myecho "[dvd-slideshow]		Reverting to ImageMagick commands"
	graphicsmagick=0
	gm_cmd=''
	gm_repage='+repage'
	gm_compose='src-over'
elif [ -n "$it" ] && [ "$commandline_gm" -eq 1 ] ; then
#elif [ -n "$it" ] ; then
	progver=`gm version | head -n 1 | awk '{ print $2 }'`
	logecho "[dvd-slideshow] Using GraphicsMagick version $progver"
	graphicsmagick=1
	gm_cmd="gm"
	gm_repage=""
	gm_compose='over'
else
	# don't use graphicsmagick
	graphicsmagick=0
	gm_cmd=''
	gm_repage='+repage'
	gm_compose='src-over'
fi


# dvdauthor
it=`which dvdauthor 2> /dev/null`
if [ -z "$it" ] ; then # no dvdauthor
               myecho "[dvd-slideshow] ERROR:  no dvdauthor found for audio processing"
               myecho "[dvd-slideshow]         You need to download and install dvdauthor."
               myecho "[dvd-slideshow]         http://dvdauthor.sourceforge.net"
		myecho "[dvd-slideshow]         Debian/Ubuntu: sudo apt-get install dvdauthor"
		program_needed=1
#		cleanup ; exit 0
else
	progver=`dvdauthor -h 2>&1 | head -n 1 | awk '{ print $3 }'`
	logecho "[dvd-slideshow] Found dvdauthor version $progver"
fi

if [ "$mpeg_encoder" == 'avconv' ] ; then
	# avconv
	it=`which avconv 2> /dev/null`
	if [ -z "$it" ] ; then
	        # no avconv!  use mp2 audio instead:
	        myecho "[dvd-slideshow] Warning: no avconv found for AC3 audio encoding."
	        myecho "[dvd-slideshow]         Using MP2 audio instead."
	        myecho "[dvd-slideshow]         MP2 audio is less compatible with DVD player hardware."
	        myecho "[dvd-slideshow]         TIP: Install avconv for faster video encoding also!"
		myecho "[dvd-slideshow]		http://avconv.sourceforge.net"
		myecho "[dvd-slideshow]         Debian/Ubuntu: sudo apt-get install avconv"
	        ac3=0
		mpeg_encoder='mpeg2enc'
	else
		# found avconv
		logecho "[dvd-slideshow]	`avconv -version 2>&1 | head -n 1 `"
		## check to see if we have mpeg2video output option:
		it=`avconv -f mpeg2video 2>&1 | grep 'Unknown input or output format: mpeg2video'`
		if [ -z "$it" ] ; then
			# mpeg2video should be ok
			[ "$mpeg_encoder" == 'avconv' ] && mpeg_encoder='avconv'
		else
			[ "$mpeg_encoder" == 'avconv' ] && mpeg_encoder='mpeg2enc'
			myecho "[dvd-slideshow] Warning:  avconv is not compiled with the mpeg2video option"
			myecho "[dvd-slideshow] 	  required for making dvds!  Using mpeg2enc instead."
			mpeg_encoder='mpeg2enc'
		fi
	fi
fi
if [ "$program_needed" -eq 1 ] ; then
		cleanup ; exit 0
fi
################################################## done finding programs

if [ -f "$tmpdir/slide_1.ppm" ] || [ -f "$tmpdir/slideshow_background.ppm" ] || [ -f "$tmpdir/fade_0001.ppm" ] ; then
	myecho "[dvd-slideshow] Found old files in output directory. Removing them..."
	cleanup
fi


logecho "[dvd-slideshow] ####################################"
myecho "[dvd-slideshow] Parsing input file $input_txtfile"

## loop over input .txt file to include any other files:
## thanks to Thomas Weber for this feature!
## modified slightly by Scott Dylewski
# create a tepmorary text file

tmptxtfile="tmp_txtfile.txt"
rm -f "$tmpdir/$tmptxtfile"

total_lines=`wc -l "$input_txtfile" | awk '{print $1}'`
#total_lines=$(( $total_lines + 1 ))
line=1

#while [ $line -ne $total_lines -a $total_lines -ne 0 ];
while read thisline  ## read $input_txtfile
do
  # Search for included files:
#  thisline=`sed -n "$line"p "$input_txtfile"`
  mygrep=`echo "$thisline" | grep -i ^include`
  mygrep_kb=`echo "$thisline" | grep -i :kenburns:`
  if [ -n "$mygrep" ]; then
	  # Extract file name out of line: Correct statement is include:filename.txt
	  incfile=`echo $thisline | awk -F: '{print $2}'`
	  # Check if the incfile is present
	  if [ -r "$incfile" ]; then
	    # Append contents of the incfile to the temporary file
	    myecho "[dvd-slideshow] Including input file $incfile"
	    cat "$incfile" >> "$tmpdir/$tmptxtfile"
## cat removed the backslashes protecting special characters?
#	    sed -e '/*/p' >> "$tmpdir/$tmptxtfile"
      	  else
          	myecho "[dvd-slideshow] Input file $incfile not found."
          	cleanup; exit 1
	  fi
  elif [ -n "$mygrep_kb" ]; then
	  # found kenburns syntax:  1,5,1
	# convert to crop, kb, crop
	kb_image=`echo "${thisline}" | cut -d: -f1`
	kb_duration=`echo "${thisline}" | cut -d: -f2`
	kb_duration1=`echo $kb_duration | cut -s -d, -f1`
	kb_duration2=`echo $kb_duration | cut -s -d, -f2`
	kb_duration3=`echo $kb_duration | cut -s -d, -f3`
	kb_subtitle=`echo "${thisline}" | cut -d: -f3`
	kb_effect1=`echo "${thisline}" | cut -d: -f4`
#	echo "duration1=$kb_duration1. duration2=$kb_duration2. duration3=$kb_duration3."
	if [ "$kb_effect1" == 'kenburns' ] && [ -n "$kb_duration1" ] && [ -n "$kb_duration2" ] && [ -n "$kb_duration3" ] ; then  # just to be sure
		kb_effect1_params=`echo "${thisline}" | cut -d: -f5 | awk -F' #' '{print $1}' | tr -d \[:blank:\]`
		kb_start_size=`echo $kb_effect1_params | awk -F';' '{print $1}'`
		kb_start_loc=`echo $kb_effect1_params | awk -F';' '{print $2}'`
		kb_end_size=`echo $kb_effect1_params | awk -F';' '{print $3}'`
		kb_end_loc=`echo $kb_effect1_params | awk -F';' '{print $4}'`
#	    echo "[dvd-slideshow] Converting kenburns syntax $kb_duration to crop $kb_duration1,kb $kb_duration2, crop $kb_duration3"
	    logecho "[dvd-slideshow] Converting kenburns syntax $kb_duration to crop $kb_duration1,kb $kb_duration2, crop $kb_duration3"
		echo "$kb_image:$kb_duration1:$kb_subtitle:crop:$kb_start_size;$kb_start_loc" >> "$tmpdir"/"$tmptxtfile"
		echo "$kb_image:$kb_duration2:$kb_subtitle:kenburns:$kb_start_size;$kb_start_loc;$kb_end_size;$kb_end_loc"  >> "$tmpdir"/"$tmptxtfile"
		echo "$kb_image:$kb_duration3:$kb_subtitle:crop:$kb_end_size;$kb_end_loc"  >> "$tmpdir"/"$tmptxtfile"
	else
	   # Print lines in the temporary file
	   sed -n "$line"p "$input_txtfile" >> "$tmpdir"/"$tmptxtfile"
	fi
  else
	   # Print lines in the temporary file
	   sed -n "$line"p "$input_txtfile" >> "$tmpdir"/"$tmptxtfile"
  fi
  line=$(( $line + 1 ))
done  < "$input_txtfile"
echo " " >> "$tmpdir"/"$tmptxtfile"  # make sure last line has a return character.


lastbar=0 # required for progressbar
## loop over input .txt file, looking first for config variables
let i=0
total_video_length=0
audio_inside_txtfile=0
imagefiles=0 ; moviefiles=0 ; audiofiles=0
background_slides=0; transitions=0; titles=0
manual_chapter_markers=0 # default, set to 1 if/when "chapter" keyword is found
spumux_header=0

## let's parse the txtfile:
total_lines=`wc -l "$tmpdir/$tmptxtfile" | awk '{print $1}'`
#total_lines=$(( $total_lines + 1 ))
let line=1

echo -n "[dvd-slideshow] "  # for progressbar
#while [ $line -ne $total_lines -a $total_lines -ne 0 ];
while read crap  ## read $tmpdir/$tmptxtfile
do
	progressbar $line $total_lines
        # change @: which is "escaped" : to something else so that
        # it doesn't separate parameters.
	line[$i]="$line"  # save for debugging later
        thisline=`sed -n "$line"p "$tmpdir/$tmptxtfile" | sed -e 's/\\\:/xxx_xxx/g'`
	if [ "${thisline:0:1}" == '#' ] ; then
		line=$(( $line + 1 )); continue # commented line. ignore it.
	elif [ -z `echo "$thisline" | tr -d \[:blank:\]` ] ; then
		line=$(( $line + 1 )); continue # blank line. ignore it.
	elif [ "$thisline" == 'exit' ] ; then
		line=$(( $line + 1 )); break # skip ahead
	fi 
	# check for theme variables:
#	  set_theme "${thisline}" 1
	  it=`set_theme "${thisline}" 0`
	  if [ -n "$it" ] ; then
		logecho "[dvd-slideshow] Set theme to $it"
		if [ "$it" != 'default' ] ; then
			read_theme "$it" 1
		fi
		## need to ignore these lines from now on!
		line=$(( $line + 1 )) ; continue
	  fi

	# check for system variables:
	  set_system_variables "${thisline}" 1
	  it=`set_system_variables "${thisline}" 0`
	  if [ -n "$it" ] ; then
		logecho "[dvd-slideshow] Set system variable $it"
		## need to ignore these lines from now on!
		line=$(( $line + 1 )) ; continue
	  fi

	image[$i]=`echo "${thisline}" | awk -F' #' '{print $1}' | cut -d: -f1 | tr -d \"`
	filetype[$i]=`echo "${image[$i]}" | awk -F. '{print tolower($NF)}'`
	duration[$i]=`echo "${thisline}" | cut -d: -f2 | awk -F' #' '{print $1}'`
	[ -z "${duration[$i]}" ] && duration[$i]=0
	subtitle[$i]=`echo "${thisline}" | cut -d: -f3 | awk -F' #' '{print $1}'`

	## check for other variable settings:
	it=`set_variables "${thisline}" 0`  
	if [ -n "$it" ] ; then
		## need to process these lines still!  Variable was found.
		image_file[$i]=0 ; audio_file[$i]=0 ; avi_file[$i]=0
		duration[$i]=0
        	subtitle[$i]=''
		i=$(( $i+1 )) ; line=$(( $line + 1 )) ; continue
	fi

	## check data file type and build arrays
        # change "xxx_xxx" back to ":"
        # - this should only be needed in subtitle
        subtitle[$i]=`echo ${subtitle[$i]} | sed -e 's/xxx_xxx/:/g'`

	if [ "${image[$i]}" == 'background' ] ; then  # trap potential # before hex color:
		effect1[$i]=`echo "${thisline}" | cut -d: -f4 | awk -F':#' '{print $1}' | awk -F' #' '{print $1}'`
	else
		effect1[$i]=`echo "${thisline}" | cut -d: -f4 | awk -F' #' '{print $1}'`
		# effect1 is used for the titlebar line 2, so we need to escape colons here also:
        	effect1[$i]=`echo ${effect1[$i]} | sed -e 's/xxx_xxx/:/g'`
	fi
	if [ "${filetype[$i]}" == 'musictitle' ] || [ "${filetype[$i]}" == 'title' ] || [ "${filetype[$i]}" == 'Title' ] ; then
		effect1_params[$i]=`echo "${thisline}" | cut -d: -f5 | awk -F' #' '{print $1}'`
	else
		effect1_params[$i]=`echo "${thisline}" | cut -d: -f5 | awk -F' #' '{print $1}' | tr -d \[:blank:\]`
	fi
	effect2[$i]=`echo "${thisline}" | cut -d: -f6 | awk -F' #' '{print $1}'`
	effect2_params[$i]=`echo "${thisline}" | cut -d: -f7 | awk -F' #' '{print $1}' | tr -d \[:blank:\]`
	effect3[$i]=`echo "${thisline}" | cut -d: -f8 | awk -F' #' '{print $1}'`
	effect_params3[$i]=`echo "${thisline}" | cut -d: -f9 | awk -F' #' '{print $1}' | tr -d \[:blank:\]`
	effect4[$i]=`echo "${thisline}" | cut -d: -f10 | awk -F' #' '{print $1}'`
	effect_params4[$i]=`echo "${thisline}" | cut -d: -f11 | awk -F' #' '{print $1}' | tr -d \[:blank:\]`

	if [ "${filetype[$i]}" == 'jpg' ] || [ "${filetype[$i]}" == 'png' ] || [ "${filetype[$i]}" == 'jpeg' ] || [ "${filetype[$i]}" == 'tif' ] ; then
		## make sure file exists:
                if [ ! -f "${image[$i]}" ] ; then
			myecho ""
                	myecho "[dvd-slideshow] ERROR: Image ${image[$i]} does not exist"
                	exit 1
                fi
		image_file[$i]=1 ; audio_file[$i]=0 ; avi_file[$i]=0
                ## optinally copy images to new directory for backup onto dvd:
                newname=`echo "${slideshow_name}" | sed -e 's/ /_/g'`
                if [ "$copy" -eq 1 ] ; then
                        mkdir -p "$outdir/$newname"_pics
                fi
                if [ "$copy" -eq 1 ] ; then
                        cp "${image[$i]}" "$outdir/$newname"_pics
                fi
		if [ "${effect1[$i]}" == 'kenburns' ] ; then  # add crop before/after kenburns
			## check for x,D,y duration syntax for kenburns effect:
			duration_fields=$( echo "${duration[$i]}" | awk -F, '{print NF}' )
			if [ "$duration_fields" -eq 3 ] ; then
				duration1=`echo ${duration[$i]} | cut -d, -f1 | awk -F' #' '{print $1}'`
				duration[$i]=`echo ${duration[$i]} | cut -d, -f2 | awk -F' #' '{print $1}'`
				duration3=`echo ${duration[$i]} | cut -d, -f3 | awk -F' #' '{print $1}'`
			elif [ "$duration_fields" -eq 2 ] ; then
				duration1=`echo ${duration[$i]} | cut -d, -f1 | awk -F' #' '{print $1}'`
				duration[$i]=`echo ${duration[$i]} | cut -d, -f2 | awk -F' #' '{print $1}'`
				duration3=0
			else
				duration1=0
				duration3=0
			fi	
		fi
		if [ "${duration[$i]}" == '0' ] ; then
			myecho ""
			myecho "[dvd-slideshow] ERROR: Bad duration time of zero:"
			myecho "[dvd-slideshow]	$thisline"
			myecho "[dvd-slideshow] You need to specify a non-zero duration"
			cleanup; exit 1
		fi
		duration_ms=`seconds2ms ${duration[$i]}`
		total_video_length="$(( $total_video_length + $duration_ms ))"
		imagefiles=$(( $imagefiles + 1 ))
		## check for common syntax errors:
		## forgetting subtitle in crop/scroll/kenburns:
		if [ "${subtitle[$i]}" == 'crop' ] && [ "${effect1[$i]}" != 'crop' ] ; then
			myecho ""
			myecho "[dvd-slideshow] ERROR: Bad syntax in line:"
			myecho "[dvd-slideshow]	$thisline"
			myecho "[dvd-slideshow] You probably forgot to add an empty subtitle placeholder:"
			myecho "[dvd-slideshow] image.jpg:duration::crop:50%;middle"
			myecho "[dvd-slideshow] image.jpg:duration:my subtitle:crop:50%;middle"
			cleanup; exit 1
		fi
		if [ "${subtitle[$i]}" == 'scroll' ] && [ "${effect1[$i]}" != 'scroll' ] ; then
			myecho ""
			myecho "[dvd-slideshow] ERROR: Bad syntax in line:"
			myecho "[dvd-slideshow]	$thisline"
			myecho "[dvd-slideshow] You probably forgot to add an empty subtitle placeholder:"
			myecho "[dvd-slideshow] image.jpg:duration::scroll:right"
			myecho "[dvd-slideshow] image.jpg:duration:my subtitle:sroll:right"
			cleanup; exit 1
		fi
		if [ "${subtitle[$i]}" == 'kenburns' ] && [ "${effect1[$i]}" != 'kenburns' ] ; then
			myecho ""
			myecho "[dvd-slideshow] ERROR: Bad syntax in line:"
			myecho "[dvd-slideshow]	$thisline"
			myecho "[dvd-slideshow] You probably forgot to add an empty subtitle placeholder:"
			myecho "[dvd-slideshow] image.jpg:duration::kenburns:50%;middle:75%:right"
			myecho "[dvd-slideshow] image.jpg:duration:my subtitle:kenburns:50%;middle:75%:right"
			cleanup; exit 1
		fi
		#######################################################################
		## Roate?
		## rotate image first, then apply other effects?
#		for e in `seq 2 -1 1`; do
		for (( e=2; e>=1 ; e-- )) ; do
			if [ "$e" -eq 1 ] ; then
				this_effect="${effect1[$i]}"
				this_effect_params="${effect1_params[$i]}"
			elif [ "$e" -eq 2 ] ; then
				this_effect="${effect2[$i]}"
				this_effect_params="${effect2_params[$i]}"
			fi
	#		myecho "effect=$this_effect params=$this_effect_params"
			if [ "${image_file[$i]}" -eq 1 ] && [ "$this_effect" == 'rotate' ] ; then 
				logecho "[dvd-slideshow] Rotating ${image[$i]} $this_effect_params"
				## get basename of image:
				suffix=`echo "${image[$i]}" | awk -F. '{print tolower($NF)}'`	
				it=`basename "${image[$i]}" .$suffix`
				convert "${image[$i]}" -background transparent -bordercolor transparent -rotate "$this_effect_params" -quality 100 "$tmpdir"/"$it"_rotated.png
				image[$i]="$tmpdir"/"$it"_rotated.png
				if [ "$e" -eq 1 ] ; then
					effect1[$i]="${effect2[$i]}"
					effect1_params[$i]="${effect2_params[$i]}"
					effect2[$i]=''
					effect2_params[$i]=''
				elif [ "$e" -eq 2 ] ; then
					effect2[$i]=''
					effect2_params[$i]=''
				fi
			fi
		done
		#######################################################################

	elif [ "${image[$i]}" == 'fadein' ] || [ "${image[$i]}" == 'fadeout' ] || [ "${image[$i]}" == 'crossfade' ] || [ "${image[$i]}" == 'wipe' ] ; then
		image_file[$i]=0 ; audio_file[$i]=0 ; avi_file[$i]=0
		if [ "${duration[$i]}" == '0' ] ; then
			myecho ""
			myecho "[dvd-slideshow] ERROR: Bad duration time of zero:"
			myecho "[dvd-slideshow]	$thisline"
			myecho "[dvd-slideshow] You need to specify a non-zero duration"
			cleanup; exit 1
		fi	
		duration_ms=`seconds2ms ${duration[$i]}`
#		total_video_length="$(( $total_video_length + $duration_ms ))"
		transitions=$(( $transitions + 1 ))
	elif [ "${image[$i]}" == 'title' ] || [ "${image[$i]}" == 'Title' ] ; then
                if [ -z "${subtitle[$i]}" ] && [ -z "${effect1[$i]}" ] ; then
			echo ""
			myecho "[dvd-slideshow] ERROR: no title text found in line:"
			myecho "[dvd-slideshow] ${thisline}"
			myecho "[dvd-slideshow] The correct syntax is:"
			myecho "[dvd-slideshow] image.jpg:duration:title_text"
			cleanup; exit 1
		fi
		if [ "${duration[$i]}" == '0' ] ; then
			myecho ""
			myecho "[dvd-slideshow] ERROR: Bad duration time of zero:"
			myecho "[dvd-slideshow]	$thisline"
			myecho "[dvd-slideshow] You need to specify a non-zero duration"
			myecho "[dvd-slideshow] The correct syntax is:"
			myecho "[dvd-slideshow] image.jpg:duration:title_text"
			cleanup; exit 1
		fi
		image_file[$i]=0 ; audio_file[$i]=0 ; avi_file[$i]=0
		duration_ms=`seconds2ms ${duration[$i]}`
		total_video_length="$(( $total_video_length + $duration_ms ))"
		titles=$(( $titles + 1 ))
        elif [ "${image[$i]}" == 'titlebar' ] || [ "${image[$i]}" == 'Titlebar' ] ; then
                if [ -z "${subtitle[$i]}" ] && [ -z "${effect1[$i]}" ] ; then
			echo ""
			myecho "[dvd-slideshow] ERROR: no titlebar text found in line:"
			myecho "[dvd-slideshow] ${thisline}"
			myecho "[dvd-slideshow] The correct syntax is:"
			myecho "[dvd-slideshow] image.jpg:duration:Upper_title:Lower_title"
			cleanup; exit 1
		fi
                if [ "${duration[$i]}" == '0' ] ; then
                        myecho ""
                        myecho "[dvd-slideshow] ERROR: Bad duration time of zero:"
                        myecho "[dvd-slideshow] $thisline"
                        myecho "[dvd-slideshow] You need to specify a non-zero duration"
			myecho "[dvd-slideshow] The correct syntax is:"
			myecho "[dvd-slideshow] image.jpg:duration:Upper_title:Lower_title"
                        cleanup; exit 1
                fi
                image_file[$i]=0 ; audio_file[$i]=0 ; avi_file[$i]=0
                duration_ms=`seconds2ms ${duration[$i]}`
                total_video_length="$(( $total_video_length + $duration_ms ))"
                titles=$(( $titles + 1 ))
        elif [ "${image[$i]}" == 'musictitle' ] ; then
		image_file[$i]=0 ; audio_file[$i]=0 ; avi_file[$i]=0
		duration_ms=`seconds2ms ${duration[$i]}`
		total_video_length="$(( $total_video_length + $duration_ms ))"
	elif [ "`echo $file | tr -d \[:blank:\]`" == 'chapter' ] ; then   # CHAPTER
		image_file[$i]=0 ; audio_file[$i]=0 ; avi_file[$i]=0
		duration[$i]=0;
		duration_ms=`seconds2ms ${duration[$i]}`
#		total_video_length="$(( $total_video_length + $duration_ms ))"
	elif [ "${image[$i]}" == 'background' ] ; then
		if [ "${duration[$i]}" != 0 ] ; then
			background_slides=$(( $background_slides + 1 ))
		fi
		image_file[$i]=0 ; audio_file[$i]=0 ; avi_file[$i]=0
		duration_ms=`seconds2ms ${duration[$i]}`
		total_video_length="$(( $total_video_length + $duration_ms ))"
        elif [ "${filetype[$i]}" == 'avi' ] ; then
                image_file[$i]=0 ; audio_file[$i]=0 ; avi_file[$i]=1
		### need to get the length of the video here and set the duration
		### so the audio is the correct length!
		checkforprog tcprobe
		if [ -n "${duration[$i]}" ] ; then
			# user specified something in duration field:
			if [ "${duration[$i]}" == 'noaudio' ] ; then
				# do not use audio contained in video
				audio_track[$i]='noaudio'
			else
				audio_track[$i]='audio'
			fi
		fi
		effect1[$i]=`echo "${thisline}" | cut -s -d: -f3 | awk -F' #' '{print $1}'`  
		effect1_params[$i]=`echo "${thisline}" | cut -s -d: -f4 | awk -F' #' '{print $1}' | tr -d \[:blank:\]`
		effect2[$i]=`echo "${thisline}" | cut -s -d: -f5 | awk -F' #' '{print $1}'`
		effect2_params[$i]=`echo "${thisline}" | cut -s -d: -f6 | awk -F' #' '{print $1}' | tr -d \[:blank:\]`
        	video_length=`tcprobe -i "${image[$i]}" 2> /dev/null | grep 'duration=' | awk -F'duration=' '{print $2}'`
		it=`hms2seconds "$video_length"`
		duration_ms=`seconds2ms $it`
		duration[$i]="`hms2seconds $video_length`"
		total_video_length="$(( $total_video_length + $duration_ms ))"
		echo ""
        	myecho "[dvd-slideshow] Found AVI video ${image[$i]} length=$video_length duration=${duration[$i]}"
		myechon "[dvd-slideshow] "
		## optionally copy images to new directory for backup onto dvd:
		newname=`echo "${slideshow_name}" | sed -e 's/ /_/g'`
		if [ "$copy" -eq 1 ] ; then
			mkdir -p "$outdir/$newname"_pics
		fi
		if [ "$copy" -eq 1 ] ; then
			cp -af "${image[$i]}" "$outdir/$newname"_pics
		fi
		moviefiles=$(( $moviefiles + 1 ))
	elif [ "${filetype[$i]}" == 'ogg' ] || [ "${filetype[$i]}" == 'mp3' ] || [ "${filetype[$i]}" == 'wav' ] || [ "${image[$i]}" == 'silence' ] || [ "${filetype[$i]}" == 'm4a' ] || [ "${filetype[$i]}" == 'aac' ] ; then
		## make sure audio file exists (if not silence):
                if [ "${image[$i]}" != 'silence' -a ! -f "${image[$i]}" ] ; then
			myecho ""
                	myecho "[dvd-slideshow] ERROR: Audio file ${image[$i]} does not exist"
                	cleanup; exit 1
                fi
		audio_inside_txtfile=1
		audio_file[$i]=1 ; image_file[$i]=0 ; avi_file[$i]=0
		effect1[$i]=`echo "${thisline}" | cut -d: -f3 | awk -F' #' '{print $1}'`  # no subtitle for audio 
		effect1_params[$i]=`echo "${thisline}" | cut -d: -f4 | awk -F' #' '{print $1}' | tr -d \[:blank:\]`
		effect2[$i]=`echo "${thisline}" | cut -d: -f5 | awk -F' #' '{print $1}'`
		effect2_params[$i]=`echo "${thisline}" | cut -d: -f6 | awk -F' #' '{print $1}' | tr -d \[:blank:\]`
		if [ "${effect1[$i]}" != 'fadein' ] && [ -n "${effect1[$i]}" ]; then
			myecho ""
			myecho "[dvd-slideshow] ERROR: First audio effect must be fadein"
                        myecho "[dvd-slideshow] $thisline"
			cleanup; exit 1
		fi
		if [ "${effect2[$i]}" != 'fadeout' ] && [ -n "${effect2[$i]}" ]; then
			myecho ""
			myecho "[dvd-slideshow] ERROR: Second audio effect must be fadeout"
                        myecho "[dvd-slideshow] $thisline"
			cleanup; exit 1
		fi
		## get audio track number:
		if [ -z "${duration[$i]}" ] ; then 
			# duration is the field for the audio track numuber
			# if empty, assume track=1
			audio_track[$i]='1'
		elif [ "${duration[$i]}" -gt 2 ]; then
			myecho ""
			myecho "[dvd-slideshow] ERROR: Only 2 audio tracks supported at this time."
			myecho "[dvd-slideshow]        Fix this audio file track number!"
			myecho "[dvd-slideshow]        $thisline"
			cleanup; exit 1
		else
			# use the duration as the audio track number:
			audio_track[$i]="${duration[$i]}"
		fi
		## get filetype:
		if [ "${filetype[$i]}" == 'ogg' ] ; then
			checkfor_oggdec
		fi
		if [ "${filetype[$i]}" == 'mp3' ] ; then
			checkfor_lame
		fi
		if [ "${filetype[$i]}" == 'm4a' ] || [ "${filetype[$i]}" == 'aac' ] ; then
			checkfor_faad
		fi
		duration[$i]=0
		audiofiles=$(( $audiofiles + 1 ))
	else
#		echo "else:  no image found"
#		echo "line=${image[$i]}".
		image_file[$i]=0 ; audio_file[$i]=0 ; avi_file[$i]=0
		duration_ms=`seconds2ms ${duration[$i]}`
		total_video_length="$(( $total_video_length + $duration_ms ))"
	fi
	[ $debug -ge 3 ] && echo "[dvd-slideshow:parsetxtfile] Total video length = $total_video_length"
#	echo "line=$i"
	line=$(( $line + 1 ))
	i=$(( $i + 1 ))
#done  ## end of loop over input .txt file  ##################################
done < "$tmpdir"/"$tmptxtfile"
finish_progressbar $line $total_lines

# check to see if any functions had errors:
if [ $function_error -eq 1 ] ; then
	myecho "[dvd-slideshow] Function error..."
	cleanup
	exit 1
fi

##############################################
#  Set default font:
if [ -d "$font_dir" ] ; then
	#default_font1=`find -L $font_dir -name $default_fontname1 | head -n 1` 
	default_font1=`find $find_L $font_dir $find_follow -name $default_fontname1 | head -n 1` 
fi
if [ -d "$font_dir2" ] ; then
	#default_font2=`find -L $font_dir2 -name $default_fontname1 | head -n 1`
	default_font2=`find $find_L $font_dir2 $find_follow -name $default_fontname1 | head -n 1`
fi
if [ -d "$font_dir3" ] ; then
	#default_font3=`find -L $font_dir3 -name $default_fontname1 | head -n 1`
	default_font3=`find $find_L $font_dir3 $find_follow -name $default_fontname1 | head -n 1`
fi
if [ -d "$font_dir" ] ; then
	#default_font4=`find -L $font_dir -name $default_fontname2 | head -n 1` 
	default_font4=`find $find_L $font_dir $find_follow -name $default_fontname2 | head -n 1` 
fi

# verify fonts exist:
if [ -f "$default_font1" ] ; then 
	default_font="$default_font1"
elif [ -f "$default_font2" ] ; then
	default_font="$default_font2"
elif [ -f "$default_font3" ] ; then
	default_font="$default_font3"
elif [ -f "$default_font4" ] ; then
	default_font="$default_font4"
else
	default_font="Helvetica-Bold"
	myecho "[dvd-slideshow] Cannot find default fonts. Using default ImageMagick font."
fi

if [ -n "$title_font" ] ; then   # title font passed
        if [ ! -f "$title_font" ] ; then  # look in font directory
#                myecho title_font="`find -L "$font_dir" -name "$title_font" | head -n 1`"
                myecho title_font="`find $find_L "$font_dir" $find_follow -name "$title_font" | head -n 1`"
#                title_font="`find -L "$font_dir" -name "$title_font" | head -n 1`"
                title_font="`find $find_L "$font_dir" $find_follow -name "$title_font" | head -n 1`"
                if [ ! -f "$title_font" ] ; then
                        echo "Error:  bad title_font filename"
                fi
        fi
fi
if [ -n "$subtitle_font" ] ; then   # title font passed
        if [ ! -f "$subtitle_font" ] ; then  # look in font directory
#                myecho subtitle_font="`find -L "$font_dir" -name "$subtitle_font" | head -n 1`"
                myecho subtitle_font="`find $find_L "$font_dir" $find_follow -name "$subtitle_font" | head -n 1`"
                #subtitle_font="`find -L "$font_dir" -name "$subtitle_font" | head -n 1`"
                subtitle_font="`find $find_L "$font_dir" $find_follow -name "$subtitle_font" | head -n 1`"
                if [ ! -f "$subtitle_font" ] ; then
                        echo "Error:  bad subtitle_font filename"
                fi
        fi
fi

if [ -z "$title_font" ] ; then  # no user font passed in variables
	title_font="$default_font"
else
	title_font="$title_font"
fi
logecho "[dvd-slideshow] Title font is $title_font"

if [ -z "$subtitle_font" ] ; then  # no user font passed in variables
	subtitle_font="$default_font"
else
	subtitle_font="$subtitle_font"
fi
logecho "[dvd-slideshow] Subtitle font is $subtitle_font"


#############################################################################

## summarize scan of .txt file:
if [ -n "$themefile" ] ; then
	myecho "[dvd-slideshow] Using theme $( truncate_filename $themefile )"
fi
if [ $commandline_audiofiles -eq 0 ] ; then
	myecho "[dvd-slideshow] Found $imagefiles images."
	myecho "[dvd-slideshow] Found $audiofiles audio files."
elif [ $audiofiles -eq 0 ] ; then
	myecho "[dvd-slideshow] Found $imagefiles images."
	myecho "[dvd-slideshow] Found $commandline_audiofiles audio files."
else
	myecho "[dvd-slideshow] Found $imagefiles images"
	myecho "[dvd-slideshow] Found $commandline_audiofiles audio files on command-line."
	myecho "[dvd-slideshow] Found $audiofiles audio files in .txtfile."
fi
myecho "[dvd-slideshow] Found $background_slides background slides."
myecho "[dvd-slideshow] Found $titles title slides."
myecho "[dvd-slideshow] Found $transitions" 'transitions (fadein/fadeout/crossfade/wipe).'
##  myecho ", and $moviefiles videos"

# setup audio parameters


## setup video parameters:
if [ "$output_format" == 'flv' ] ; then  # FLV
	# need to change this to be dynamic (proportinal to size)
	# video_bitrate=$(( 6000 * $dvd_width / 480 ))
	if [ $high_quality -eq 1 ] ; then
		video_bitrate=2000000  # this works ok for 320x240. 
		qscale='-qscale 1'
		framerate=30;
		frames_per_ms=30000;
		ppmtoy4m_frc='30:1'  # 30 fps
	elif [ $low_quality -eq 1 ] ; then
		video_bitrate=500000  # this works ok for 320x240. 
		qscale='-qscale 7'
	else
		video_bitrate=1000000  # this works ok for 320x240. 
		qscale='-qscale 5'
		framerate='15'  # is this needed for .flv?
		frames_per_ms=15000  # in ms
		ppmtoy4m_frc='15:1'  # 15 fps
	fi
	## video_bitrate will be scaled if user specifies -s 240x180, for example, by about 1/2
	video_suffix='flv'
	ppmtoy4m_aspect='1:1'  # square pixels
		# see http://www.uwasa.fi/~f76998/video/conversion
	dvd_width='320' ; dvd_height='240'
	aspect_ratio="4:3"  #   what is used when output size is not this aspect ratio?
	audio_sample_rate=44100
	audio_bitrate=64
	avconv_options=''
elif [ "$output_format" == 'swf' ] ; then
	#video_bitrate=100
	if [ $high_quality -eq 1 ] ; then
		qscale='-qscale 2'
	elif [ $low_quality -eq 1 ] ; then
		qscale='-qscale 7'
	else
		qscale='-qscale 5'
	fi
	video_suffix='swf'
	framerate='15'  # is this needed for .swf?
	frames_per_ms=15000  # in ms
	ppmtoy4m_frc='15:1'  # 15 fps
	ppmtoy4m_aspect='1:1'  # square pixels
		# see http://www.uwasa.fi/~f76998/video/conversion
	dvd_width='320' ; dvd_height='240'  # default
	aspect_ratio="4:3"
	audio_sample_rate=44100
	audio_bitrate=128
	avconv_options=''
elif [ "$output_format" == 'mp4' ] ; then
	video_bitrate=1200000
	if [ $high_quality -eq 1 ] ; then
		qscale='-qscale 2'
	elif [ $low_quality -eq 1 ] ; then
		qscale='-qscale 7'
	else
		qscale='-qscale 5'
	fi
	video_suffix='mp4'
	framerate='29.97'  
	frames_per_ms=29970  # in ms
	ppmtoy4m_frc='30000:1001'
#	ppmtoy4m_aspect='10:11'  # 4:3
	ppmtoy4m_aspect='1:1'  # square pixels
		# see http://www.uwasa.fi/~f76998/video/conversion
	dvd_width='320' ; dvd_height='240'  # default
	aspect_ratio="4:3"
	audio_sample_rate=44100
	audio_bitrate=128
	avconv_options=''
elif [ "$output_format" == 'mp4_ipod' ] ; then
	# copied this from mp4 options, but probably don't need all these
	#video_bitrate=1200000
	if [ $high_quality -eq 1 ] ; then
		qscale='-qscale 2'
	elif [ $low_quality -eq 1 ] ; then
		qscale='-qscale 7'
	else
		qscale='-qscale 5'
	fi
	video_suffix='mp4'
	framerate='20'  
	frames_per_ms=20000  # in ms
	ppmtoy4m_frc='20:1'  # 15 fps
	ppmtoy4m_aspect='1:1'  # square pixels
		# see http://www.uwasa.fi/~f76998/video/conversion
	dvd_width='320' ; dvd_height='240'  # default
	aspect_ratio="4:3"
	audio_sample_rate=44100
	audio_bitrate=96k
	ac3=1  # force ac3
	#avconv_options='-level 41 crf 25 -bufsize 20000k -maxrate 25000k -g 250 -coder 1 -flags +loop -cmp +chroma -partitions +parti4x4+partp8x8+partb8x8 -flags2 +brdo+dct8x8+bpyramid -me umh -subq 7 -me_range 16 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -rc_eq '\''blurCplx^(1-qComp)'\'' -bf 16 -b_strategy 1 -bidir_refine 1 -refs 6 -deblockalpha 0 -deblockbeta 0'
	# avconv options for h.264 from http://flowplayer.org/tutorials/avconv.html but not working yet
	avconv_options='-vcodec xvid -b 300 -qmin 3 -qmax 5 -bufsize 4096 -g 300 -acodec libfaac'
elif [ "$output_format" == 'ogv' ] ; then
	video_bitrate=1200000
	if [ $high_quality -eq 1 ] ; then
		qscale='-qscale 2'
	elif [ $low_quality -eq 1 ] ; then
		qscale='-qscale 7'
	else
		qscale='-qscale 5'
	fi
	video_suffix='ogv'
	framerate='29.97'  
	frames_per_ms=29970  # in ms
	ppmtoy4m_frc='30000:1001'
#	ppmtoy4m_aspect='10:11'  # 4:3
	ppmtoy4m_aspect='1:1'  # square pixels
		# see http://www.uwasa.fi/~f76998/video/conversion
	dvd_width='320' ; dvd_height='240'  # default
	aspect_ratio="4:3"
	audio_sample_rate=44100
	audio_bitrate=128
	ac3=1  # force ac3
	avconv_options=''
else  # assume mpeg2 video output (dvd, vcd, svcd or other)
	video_suffix='mpg'
	avconv_options=''
	if [ "$pal" -eq 1 ] ; then
		framerate='25'
		frames_per_ms=25000  # in ms
		ppmtoy4m_frc='25:1'
		ppmtoy4m_aspect='59:54'
			# see http://www.uwasa.fi/~f76998/video/conversion
		if [ "$vcd" -eq 1 ] ; then
			dvd_width='352' ; dvd_height='288'
			avconv_target='pal-vcd'
		elif [ "$svcd" -eq 1 ] ; then
			dvd_width='480' ; dvd_height='576'
			avconv_target='pal-svcd'
		elif [ "$high_quality" -eq 1 ] ; then
			dvd_width='720' ; dvd_height='576'
			avconv_target='pal-dvd'
		elif [ "$low_quality" -eq 1 ] ; then
			dvd_width='352' ; dvd_height='288'
			avconv_target='pal-dvd'
		else
			dvd_width='720' ; dvd_height='576'
			avconv_target='pal-dvd'
		fi
	else  ## NTSC
		framerate='29.97'
		frames_per_ms=29970  # in ms
		ppmtoy4m_frc='30000:1001'
		ppmtoy4m_aspect='10:11'
			# see http://www.uwasa.fi/~f76998/video/conversion
		if [ "$vcd" -eq 1 ] ; then
			dvd_width='352' ; dvd_height='240'
			avconv_target='ntsc-vcd'
		elif [ "$svcd" -eq 1 ] ; then
			dvd_width='480' ; dvd_height='480'
			avconv_target='ntsc-svcd'
		elif [ "$high_quality" -eq 1 ] ; then
			dvd_width='720' ; dvd_height='480'
			avconv_target='ntsc-dvd'
		elif [ "$low_quality" -eq 1 ] ; then
			dvd_width='352' ; dvd_height='240'
			avconv_target='ntsc-dvd'
		else
			dvd_width='720' ; dvd_height='480'
			avconv_target='ntsc-dvd'
		fi
	fi
	mplex_bitrate=9500
	if [ "$vcd" -eq 1 ] ; then
	        ac3=0  # force mp2
       		audio_bitrate=224
		video_bitrate='1152'
	        audio_sample_rate=44100
		mplex_type=1
		aspect_ratio="4:3"
		mpeg2enc_params="-v 0 -4 2 -2 1 -H -b 1150 -n n -s -f $mplex_type"
	elif [ "$svcd" -eq 1 ] ; then
		ac3=0  # force mp2
		audio_bitrate=128
		video_bitrate='4500'
	        audio_sample_rate=44100
		mplex_type=4
		aspect_ratio="4:3"
		mpeg2enc_params="-v 0 -4 2 -2 1 -H -b 2500 -n n -s -f $mplex_type"
	else # default dvd method
	        audio_bitrate=256
		video_bitrate='3800'
	        audio_sample_rate=48000 
		mplex_type=8
		if [ "$widescreen" -eq 1 ] ; then
			aspect_ratio="16:9"
			mpeg2enc_params="-v 0 -a 3 -q 4 -4 2 -2 1 -s -M 0 -f $mplex_type"
		else
			aspect_ratio="4:3"
			mpeg2enc_params="-v 0 -a 2 -q 4 -4 2 -2 1 -s -M 0 -f $mplex_type -E -N -R 2"
		fi
	fi
	video_buffer='-b 1000'
	if [ "$output_format" == 'mpg' ] ; then  # assume computer output:
		ppmtoy4m_aspect='1:1'  # square pixels
	        ac3=0  # force mp2 ?
	        audio_bitrate=192
		video_bitrate=$(( 6000 * $dvd_width / 480 ))
		echo "video_bitrate=$video_bitrate"
	        audio_sample_rate=48000
		mplex_type=3
		aspect_ratio="1:1"
		mpeg2enc_params="-v 0 -4 2 -2 1 -H -b $video_bitrate -n n -s -f $mplex_type"
	fi
fi

resize_factor=`awk -vw=$dvd_width -vh=$dvd_height -var=$aspect_ratio 'BEGIN{if (ar=="4:3"){ar=4/3} else {ar=16/9};printf "%0.2f", (100/((h/w)*(ar)));exit;}' | sed 's/,/\./g'`
# resize_factor is 93.75 for PAL
# resize_factor is 112.50 for NTSC
sq_to_dvd_pixels="${resize_factor}x100%"
[ $debug -ge 2 ] && myecho "[dvd-slideshow] sq_to_dvd_pixels=$sq_to_dvd_pixels"

# use qscale insteadi of video_bitrate!
if [ -n "$output_size" ] ; then
	# used user-set size, instead of defaults!
	orig_dvd_width=$dvd_width ; orig_dvd_height=$dvd_height
	dvd_width=$( echo "$output_size" | cut -dx -f1 | tr -d \[:blank:\] )
	dvd_height=$( echo "$output_size" | cut -dx -f2 | tr -d \[:blank:\] )
	# make sure the sizes are at least factors of 2:
	if [ `is_even $dvd_width` -ne 1 ] ; then
		myecho "[dvd-slideshow] ERROR: User-specified width=$dvd_width must be a factor of 2"
		cleanup; exit 1;
	fi
	if [ `is_even $dvd_height` -ne 1 ] ; then
		myecho "[dvd-slideshow] ERROR: User-specified height=$dvd_height must be a factor of 2"
		cleanup; exit 1;
	fi
	if [ "$output_format" == 'flv' ] || [ "$output_format" == 'swf' ] || [ "$output_format" == 'mp4' ] || [ "$output_format" == 'mp4_ipod' ] || [ "$output_format" == 'ogv' ]  ; then
#		video_bitrate=$(( $video_bitrate * ( $dvd_width * $dvd_height ) / ( $orig_dvd_width * $orig_dvd_height ) ))
#		video_bitrate=500000
		myecho "[dvd-slideshow] dvd_width=$dvd_width dvd_height=$dvd_height"
		myecho "[dvd-slideshow] output_size=$output_size ratio=$(( ( $dvd_width * $dvd_height ) / ( $orig_dvd_width * $orig_dvd_height ) ))"
		myecho "[dvd-slideshow] Set new video bitrate to $video_bitrate b/s"
	fi
fi

if [ -n "$output_framerate" ] ; then
	framerate="$output_framerate"
	frames_per_ms=$( echo "$output_framerate * 1000" | bc )
	frames_per_ms=$( printf %3.0f $frames_per_ms )
	myecho "[dvd-slideshow] Frames per sec * 1000 = $frames_per_ms"
	ppmtoy4m_frc="$framerate:1"  # fps  need to fix this to allow any option!
	myecho "[dvd-slideshow] ppmtoy4m frc=$ppmtoy4m_frc"
fi

[ -n "$border" ] && frame_border=$border || frame_border=0
frame_width=$(( $dvd_width - 2 * $frame_border ))
frame_height=$(( $dvd_height - 2 * $frame_border ))

if [ -n "$sharpen" -a "$sharpen" == "1" ] ; then
	sharpen='-unsharp 4.8x2.2+0.5+0.05'
else
	sharpen=''
fi

## summarize configuration:
[ "$pal" -eq 1 ] && ntsc_or_pal="PAL" || ntsc_or_pal="NTSC"
[ -n "$VIDEO_FORMAT" ] && original_video_format="$VIDEO_FORMAT" || original_video_format=''
export VIDEO_FORMAT="$ntsc_or_pal"  # required for dvdauthor and spumux
[ "$ac3" -eq 1 ] && mp2_or_ac3="AC3" || mp2_or_ac3="MP2"

#myecho "[dvd-slideshow] Configuration summary:"
[ "$vcd" -eq 1 ] && myecho "[dvd-slideshow] VCD mode"
[ "$svcd" -eq 1 ] && myecho "[dvd-slideshow] SVCD mode"
myecho "[dvd-slideshow] Video: $ntsc_or_pal $dvd_width"x"$dvd_height $framerate"fps" $aspect_ratio"
myecho "[dvd-slideshow] Audio: $mp2_or_ac3 $audio_sample_rate $audio_bitrate"k 
myecho "[dvd-slideshow] Debug=$debug  Autocrop=$autocrop Subtitles=$subtitle_type Border=$frame_border"
if [ "$manual_chapter_markers" == 1 ] ; then
	myecho "[dvd-slideshow] Chapter markers= Manual"
fi	
if [ "$mpeg_encoder" == 'mpeg2enc' ] ; then
	myecho "[dvd-slideshow] Using mpeg2enc instead of FFmpeg"
fi	
if [ "$graphicsmagick" == 1 ] ; then
	myecho "[dvd-slideshow] Using GraphicsMagick commands when possible"
fi	
if [ "$smp" == 1 ] ; then
	myecho "[dvd-slideshow] Using SMP optimizations for multi-processor machines"
fi	
if [ "$nocleanup" == 1 ] ; then
	myecho "[dvd-slideshow] Leaving all temporary files in temp directory"
fi	
myecho "[dvd-slideshow] Title_font=$(truncate_filename "$title_font")"
myecho "[dvd-slideshow] Subtitle_font=$(truncate_filename "$subtitle_font")"

if [ -n "$logo" ] ; then
	myecho "[dvd-slideshow] Logo=$(truncate_filename "$logo")"
fi

###########################################################
# Preprocessing:  calcuate times 
# 		and do initial syntax / sanity check
###########################################################
# ERRORCHECK
myecho "[dvd-slideshow] Running initial error check..."

audiosmp=1  # default to do audio in background...
lastbar=0 # required for progressbar
if [ $debug -lt 2 ] ; then
	echo -n "[dvd-slideshow] "  # for progressbar
fi

i=0
progressbar_indicator='#'
for file in "${image[@]}"; do
	di=`addzeros $i`
	if [ $debug -lt 2 ] ; then
		progressbar $i "${#image[@]}" "$progressbar_indicator"
	fi
	progressbar_indicator='#'  # it may be changed by the audio decoding
	[ $debug -ge 2 ] && myecho "line ${line[$i]} file=$file duration=${duration[$i]} subtitle=${subtitle[$i]} effect1=${effect1[$i]}"
	
	##### Set slide duration
	if [ -z "${duration[$i]}" ] ; then
		myecho "[dvd-slideshow] WARNING:  No duration specified for ${image[$i]}"
		myecho "[dvd-slideshow]	     Using default duration of 5 seconds"
		duration[$i]=5
		duration[$i]=`seconds2ms ${duration[$i]}`  # duration in thousandths of a sec.
	elif [ "${duration[$i]}" == 'audio' ] ; then
		## make the duration the length of the last audio track
		# because audio is rendered in the baackground now, we need
		# to wait for it to finish so the .wav file is present:
		waitforfile "$tmpdir/audio$track"_"$audio_index_padded.wav" # last audio file
		song_length_ms=`wavlength "$tmpdir/audio$track"_"$audio_index_padded.wav"`
		if [ -z "$song_length_ms" ] ; then
			myecho "[dvd-slideshow] ERROR line ${line[$i]}. You must have an audio track before a slide specifying 'audio'"
			cleanup; exit 1
		fi
		duration[$i]="$song_length_ms"  # duration in thousandths of a sec.
	else  # duration should be ok
		duration[$i]=`seconds2ms ${duration[$i]}`  # duration in thousandths of a sec.
	fi
        frames=`div1000 $(( $frames_per_ms * ${duration[$i]} / 1000 ))` # both duration and fps are in ms

	if [ "${image_file[$i]}" == 1 ] && [ -z "${effect1[$i]}" ] ; then  # JPG
		nothing="nothing"
		if [ -z "${frames_extended[$i]}" ] ; then  # not set yet
			frames_extended[$i]=$frames
		fi
	elif [ "$file" == 'fadein' ] ; then  # FADEIN
		next_transition_increment="`nextTransitionIncrement`"
		if [ "$next_transition_increment" -ne 0 ] ; then
			myecho "[dvd-slideshow] ERROR line ${line[$i]}. Cannot fadein to another fade!"
			cleanup; exit 1
		fi
		increment=`nextslideincrement`
		if [ -z "$increment" ] ; then
			myecho "[dvd-slideshow] ERROR line ${line[$i]}: no next slide found to fadein to!"
			cleanup ; exit 1
		fi
	elif [ "$file" == 'crossfade' ] ; then  # CROSSFADE
		## error checks:
		nextslide=`nextslidename`
		if [ -z "$nextslide" ] ; then
			myecho "[dvd-slideshow] ERROR line ${line[$i]}: No next slide to crossfade to!"
			cleanup ; exit 1 
		fi
		previous_increment="`previousslideincrement`"
		if [ -z "$previous_increment" ] ; then 
			myecho "[dvd-slideshow] ERROR line ${line[$i]}: No previous slide to crossfade from!"
			cleanup ; exit 1 
		fi
		next_transition_increment=`nextTransitionIncrement`
		if [ "$next_transition_increment" -ne 0 ] ; then
			myecho "[dvd-slideshow] ERROR line ${line[$i]}: Cannot crossfade to another fade!"
			cleanup; exit 1
		fi

		## Now calculate new slide times when using crossfade:
		if [ "$previous_increment" -ne 0 ] ; then
			previous_duration="${duration[$i-$previous_increment]}" # already in thousandths.
			previous_frames=`div1000 $(( $frames_per_ms * $previous_duration / 1000 ))` 
		fi
		previous_slide="${image[$i-$previous_increment]}"
		[ -z "$previous_slide" ] && previous_slide=0

		next_increment="`nextslideincrement`"
		next_slide="${image[$i+$next_increment]}"
		if [ "$next_increment" -ne 0 ] ; then
			next_duration=`seconds2ms ${duration[$i+$next_increment]}`  # duration in thousandths of sec
			next_frames=`div1000 $(( $frames_per_ms * $next_duration / 1000 ))` 
		fi
		[ -z "$next_slide" ] && next_slide=0

		# add half of the crossfade time to the previous image
		if [ -z "${frames_extended[$i-$previous_increment]}" ] ; then
			frames_extended[$i-$previous_increment]=$(( $previous_frames + $frames / 2 ))
		else
			frames_extended[$i-$previous_increment]=$(( ${frames_extended[$i-$previous_increment]} + $frames / 2 ))
		fi
		# add half of the crossfade time to the next image
		frames_extended[$i+$next_increment]=$(( $next_frames + $frames / 2 ))

	elif [ "$file" == 'wipe' ] ; then  # WIPE
		nextslide=`nextslidename`
		if [ -z "$nextslide" ] ; then
			myecho "[dvd-slideshow] ERROR line ${line[$i]}: No next slide to wipe to!"
			cleanup ; exit 1 
		fi
		previous_increment="`previousslideincrement`"
		if [ -z "$previous_increment" ] ; then 
			myecho "[dvd-slideshow] ERROR line ${line[$i]}: No previous slide to wipe from"
			cleanup ; exit 1 
		fi
		next_transition_increment=`nextTransitionIncrement`
		if [ "$next_transition_increment" -ne 0 ] ; then
			myecho "[dvd-slideshow] ERROR line ${line[$i]}: Cannot wipe to another fade or wipe!"
			cleanup; exit 1
		fi

		## Now calculate new slide times when using wipe:
		if [ "$previous_increment" -ne 0 ] ; then
			previous_duration="${duration[$i-$previous_increment]}" # already in thousandths.
			previous_frames=`div1000 $(( $frames_per_ms * $previous_duration / 1000 ))` 
		fi
		previous_slide="${image[$i-$previous_increment]}"
		[ -z "$previous_slide" ] && previous_slide=0

		next_increment="`nextslideincrement`"
		next_slide="${image[$i+$next_increment]}"
		if [ "$next_increment" -ne 0 ] ; then
			next_duration=`seconds2ms ${duration[$i+$next_increment]}`  # duration in thousandths of sec
			next_frames=`div1000 $(( $frames_per_ms * $next_duration / 1000 ))` 
		fi
		[ -z "$next_slide" ] && next_slide=0

		# add half of the wipe time to the previous image
		if [ -z "${frames_extended[$i-$previous_increment]}" ] ; then
			frames_extended[$i-$previous_increment]=$(( $previous_frames + $frames / 2 ))
		else
			frames_extended[$i-$previous_increment]=$(( ${frames_extended[$i-$previous_increment]} + $frames / 2 ))
		fi
		# add half of the wipe time to the next image
		frames_extended[$i+$next_increment]=$(( $next_frames + $frames / 2 ))
	elif [ "$file" == 'fadeout' ] ; then  # FADEOUT
		previous_increment="`previousslideincrement`"
		if [ -z "$previous_increment" ] ; then 
			myecho "[dvd-slideshow] ERROR line ${line[$i]}: No previous slide to fadeout from"
			cleanup ; exit 1 
		fi
		next_transition_increment=`nextTransitionIncrement`
		if [ "$next_transition_increment" != 0 ] && ([ "${image[$i+$next_transition_increment]}" == 'crossfade' ] || [ "${image[$i+$next_transition_increment]}" == 'fadeout' ]) ; then
			myecho "[dvd-slideshow] ERROR line ${line[$i]}: Cannot fadeout to a crossfade or another fadeout!"
			cleanup; exit 1
		fi
	elif [ "${effect1[$i]}" == 'kenburns' ] ; then  # KENBURNS check
		if [ -z "${frames_extended[$i]}" ] ; then
			frames_extended[$i]=$frames
		fi
		previous_transition_increment="`previousTransitionIncrement`"
		previous_slide="${image[$i-$previous_transition_increment]}"
		if [ "$previous_transition_increment" -ne 0 ] ; then
			previous_duration="${duration[$i-$previous_transition_increment]}" # already in thousandths.
			previous_frames=`div1000 $(( $frames_per_ms * $previous_duration / 1000 ))` 
		fi
#		next_transition_increment="`nextTransitionIncrement`"
#		next_slide="${image[$i+$next_transition_increment]}"
	elif [ "${effect1[$i]}" == 'scroll' ] ; then  # SCROLL check
		if [ -z "${frames_extended[$i]}" ] ; then
			frames_extended[$i]=$frames
		fi
		previous_transition_increment="`previousTransitionIncrement`"
		previous_slide="${image[$i-$previous_transition_increment]}"
		if [ "$previous_transition_increment" -ne 0 ] ; then
			previous_duration="${duration[$i-$previous_transition_increment]}" # already in thousandths.
			previous_frames=`div1000 $(( $frames_per_ms * $previous_duration / 1000 ))` 
		fi
#		next_transition_increment="`nextTransitionIncrement`"
#		next_slide="${image[$i+$next_transition_increment]}"
        elif [ "$file" == 'title' -o "$file" == 'Title' ] ; then # TITLE  #####
                if [ -z "${subtitle[$i]}" ] && [ -z "${effect1[$i]}" ] ; then
			myecho "[dvd-slideshow] ERROR line ${line[$i]}. no title text found in line:"
			myecho "[dvd-slideshow] ${thisline}"
			cleanup; exit 1
		fi
	elif [ "$file" == 'titlebar' ] ; then  # TITLEBAR
		nothing="nothing"
	elif [ "$file" == 'musictitle' ] ; then  # MUSICTITLE
		nothing="nothing"
	elif [ "${avi_file[$i]}" == 1 ] ; then  # AVI
		previous_transition_increment="`previousTransitionIncrement`"
		next_transition_increment="`nextTransitionIncrement`"
		if [ "${image[$i-$previous_transition_increment]}" == 'fadein' ] || [ "${image[$i-$previous_transition_increment]}" == 'crossfade' ] || [ "${image[$i-$previous_transition_increment]}" == 'wipe' ] ; then 
			myecho "[dvd-slideshow] WARNING line ${line[$i]}. Cannot fadein or crossfade to a .avi file (yet)"
#			exit 1
		fi
		if [ "${image[$i+$next_transition_increment]}" == 'fadeout' ] || [ "${image[$i+$next_transition_increment]}" == 'crossfade' ] || [ "${image[$i+$next_transition_increment]}" == 'wipe' ]; then
			myecho "[dvd-slideshow] WARNING line ${line[$i]}. Cannot fadeout or crossfade from a .avi file (yet)"
#			exit 1
		fi
	elif [ "${audio_file[$i]}" -eq 1 ] ; then  # AUDIO FILE CHECK
		progressbar_indicator='a'
		[ "$debug" -ge 2 ] && myecho "[dvd-slideshow] Decoding audiofile $( truncate_filename "$file") "
		if [ "${audio_track[$i]}" -eq 1 ] ; then
			audio_1[$i_audio]="${file}"
			audio1_effect1[$i_audio]="${effect1[$i]}"
			audio1_effect1_params[$i_audio]="${effect1_params[$i]}"
			audio1_effect2[$i_audio]="${effect2[$i]}"
			audio1_effect2_params[$i_audio]="${effect2_params[$i]}"
			audio_index="$i_audio"
			audio_index_padded=`addzeros "$i_audio"`
			i_audio=$(( $i_audio + 1 ))
		elif [ "${audio_track[$i]}" -eq 2 ] ; then
			audio_2[$j_audio]="${file}"
			audio2_effect1[$j_audio]="${effect1[$i]}"
			audio2_effect1_params[$j_audio]="${effect1_params[$i]}"
			audio2_effect2[$j_audio]="${effect2[$i]}"
			audio2_effect2_params[$j_audio]="${effect2_params[$i]}"
			audio_index="$j_audio"
			audio_index_padded=`addzeros "$j_audio"`
			j_audio=$(( $j_audio + 1 ))
		else
			myecho "[dvd-slideshow] ERROR: Bad audio track number."
			myecho "[dvd-slideshow]        only use audio track 1 or 2"
			cleanup; exit 1
		fi
		track="${audio_track[$i]}"
		suffix=`echo "$file" | awk -F. '{print tolower($NF)}'`
		if [ "$suffix" == "mp3" ] ; then
#			myecho "[dvd-slideshow] decoding mp3 audio file... be patient..."
			if [ "$audiosmp" -eq 1 ] ; then
				avconv -threads "$cores" -i "$file" -y -vn -ab "$audio_bitrate"k -f wav -ar $audio_sample_rate -ac 2 "$tmpdir/audio$track"_"$audio_index_padded.wav" >> "$avconv_out" 2>&1 &
			else
				avconv -threads "$cores" -i "$file" -y -vn -ab "$audio_bitrate"k -f wav -ar $audio_sample_rate -ac 2 "$tmpdir/audio$track"_"$audio_index_padded.wav" >> "$avconv_out" 2>&1
			fi
		elif [ "$suffix" == "m4a" ] || [ "$suffix" == "aac" ] ; then
#			myecho "[dvd-slideshow] decoding mp4 audio... be patient."
			if [ "$audiosmp" -eq 1 ] ; then
				faad -o "$tmpdir/audio$track"_"$audio_index_padded.wav" "$file" &
			else
				faad -o "$tmpdir/audio$track"_"$audio_index_padded.wav" "$file" 
			fi
		elif [ "$suffix" == "ogg" ] ; then
#			myecho "[dvd-slideshow] decoding ogg audio... be patient."
			if [ "$audiosmp" -eq 1 ] ; then
				oggdec --quiet -o "$tmpdir/audio$track"_"$audio_index_padded.wav" "${file}" &
			else
				oggdec --quiet -o "$tmpdir/audio$track"_"$audio_index_padded.wav" "${file}"
			fi
		elif [ "$suffix" == "wav" ] ; then
#			myecho "[dvd-slideshow] processing wav audio... we will splice it later."
			cp "${file}" "$tmpdir/audio$track"_"$audio_index_padded.wav"
		elif [ "$file" == 'silence' ]; then
			if [ "$audiosmp" -eq 1 ] ; then
				sox -t raw -s $sox_word -c 2 -r $audio_sample_rate /dev/zero -t wav -c 2 -r $audio_sample_rate "$tmpdir/audio$track"_"$audio_index_padded.wav" trim 0 1 &
			else
				sox -t raw -s $sox_word -c 2 -r $audio_sample_rate /dev/zero -t wav -c 2 -r $audio_sample_rate "$tmpdir/audio$track"_"$audio_index_padded.wav" trim 0 1
			fi
		else
			myecho "[dvd-slideshow] ERROR:  Unknown audio file format. Must be mp3, ogg, mp4/aac, wav, or silence"
		fi
#	else  
#		myecho "[dvd-slideshow] Unrecognized or malformed line in your input file:"
#		myecho "[dvd-slideshow] $file. effect=${effect1[$i]} effect_params=${effect1_params[$i]}"
#		myecho "Fix it and try again."
#		cleanup; exit 1
	fi
	i=$(( $i + 1 ))
done  ## end of error checking loop
if [ $debug -lt 2 ] ; then
	finish_progressbar $i "${#image[@]}"
fi
######################################################################3

i_audio=0  # reset loop back to zero?
j_audio=0
## convert command-line audio files to wav format first, so we know how long they are:
if [ -n "${passed_audio[0]}" ] && [ $audio_inside_txtfile -eq 0 ] ; then  ## only command-line passed audio
	total_audio_length=0
	track=1 ; i=1
	myecho "[dvd-slideshow] Decoding command-line passed audio files..."
	for file in "${passed_audio[@]}"; do
		## verify files exist:
		if [ ! -f "$file" ] ; then
			myecho "[dvd-slideshow] ERROR: file $file does not exist."
			cleanup ; exit 1
		fi
		suffix=`echo "$file" | awk -F. '{print tolower($NF)}'`
		audio_index_padded=`addzeros "$i_audio"`
		if [ "$suffix" == "mp3" ] ; then
			myecho "[dvd-slideshow] Decoding mp3 audio: $file"
			# use avconv instead of lame!
			avconv -threads "$cores" -i "$file" -y -vn -ab "$audio_bitrate"k -f wav -ar $audio_sample_rate -ac 2 "$tmpdir/audio$track"_"$audio_index_padded.wav" >> "$avconv_out" 2>&1
#			lame --decode "$file" "$tmpdir/audio$track"_"$audio_index_padded.wav" 2> /dev/null
		elif [ "$suffix" == "ogg" ] ; then
			checkfor_oggdec
			myecho "[dvd-slideshow] Decoding ogg audio: $file"
			oggdec --quiet -o "$tmpdir/audio$track"_"$audio_index_padded.wav" "$file"
		elif [ "$suffix" == "m4a" ] || [ "$suffix" == "aac" ] ; then
			checkfor_faad
			myecho "[dvd-slideshow] Decoding m4a audio: $file"
			faad -o "$tmpdir/audio$track"_"$audio_index_padded.wav" "$file"
		elif [ "$suffix" == "wav" ] ; then
			myecho "[dvd-slideshow] Processing wav audio $file"
			cp "$file" "$tmpdir/audio$track"_"$audio_index_padded.wav"
		else
			myecho "[dvd-slideshow] ERROR:  Unknown audio file format. Must be mp3, ogg, aac/mp4 or wav"
		fi	
		waitforfile "$tmpdir/audio$track"_"$audio_index_padded.wav"
		length=`wavlength "$tmpdir/audio$track"_"$audio_index_padded.wav"`
		length_array[$i]=`hms $length`
		total_audio_length="$(( $total_audio_length + $length ))"
#		myecho "[dvd-slideshow] length=$length total_audio_length=$total_audio_length"
		let i=$i+1
		i_audio=$(( $i_audio + 1 ))
	done
#	i=1
#	for file in "${passed_audio[@]}"; do
#		myecho "[dvd-slideshow] ${length_array[$i]} `basename \"$file\"`"
#		let i=$i+1
#	done
	# estimate total audio length:
	length_hms=`hms $total_audio_length`
elif [ -n "${passed_audio[0]}" ] && [ $audio_inside_txtfile -eq 1 ] ; then  ## only command-line passed audio
	myecho "[dvd-slideshow] WARNING:  You specified audio on the command line, and"
	myecho "[dvd-slideshow]           you have audio files inside your input .txt file"
	myecho "[dvd-slideshow]           Use one or the other, but not both!"
	myecho "[dvd-slideshow]           Ignoring command-line passed audio!"
	passed_audio=''
fi

video_time_hms=`hms $total_video_length`
myecho "[dvd-slideshow] Total audio length = $length_hms"
myecho "[dvd-slideshow] Total video length = $video_time_hms"

if [ ! -d "$outdir" ] ; then	
	myecho "creating directory $outdir"
	mkdir -p "$outdir"  # create directory
fi

#mpeg2enc_params='-v 0 -a 2 -q 8 -s -M 0 -f $mplex_type -b 6000 -I 0'
#mpeg2enc_params='-v 0 -a 2 -s -M 0 -f $mplex_type -b 6000'


if [ "$low_quality" -eq 1 ] ; then
	myecho "[dvd-slideshow] WARNING: Using low-quality mode."
	myecho "[dvd-slideshow]   This mode is for testing only."
	myecho "[dvd-slideshow]   output resolution is $dvd_width"x"$dvd_height"
	myecho "[dvd-slideshow]   Ignore [mpeg2enc] warnings (usually)"
elif [ "$high_quality" -eq 1 ] ; then
	myecho "[dvd-slideshow] Using high-quality mode. "
elif [ "$svcd" -eq 1 ] ; then
	myecho "[dvd-slideshow] Using svcd mode. "
elif [ "$vcd" -eq 1 ] ; then
	myecho "[dvd-slideshow] Using vcd mode. "
fi
has_subtitles=0
has_subtitles2=0
frame_time=0
total_slideshow_frames=0

#orig_slideshow_name="${slideshow_name}"
#slideshow_name=`echo "${slideshow_name}" | sed -e 's/ /_/g'`
#if [ "$orig_slideshow_name" != "$slideshow_name" ] ; then
#	myecho "[dvd-slideshow] Output filename is $slideshow_name"
#fi
myecho "[dvd-slideshow] Temp dir is $( truncate_filename "$outdir"/"dvd-slideshow_temp_$$" )"

# create the mpeg2enc pipeline here if we are in $yuvcat mode
# create the fifo
rm -f "$tmpdir/$yuvfifo"
mkfifo "$tmpdir/$yuvfifo"

if [ "$mpeg_encoder" == 'avconv' ] ; then
	if [ "$output_format" == 'flv' ] ; then
		# do pass one first, then add audio at the end during pass 2?
		# don't do mplex, do second pass instead.
		# it seems that specifying the aspect ratio makes avconv fail, so keep it out.
		myecho "[dvd-slideshow] Exporting .flv file"
		avconv -f yuv4mpegpipe -i "$tmpdir"/$yuvfifo -r $framerate -b $video_bitrate -an -s "$dvd_width"x"$dvd_height" -y -f flv "$tmpdir/video.flv" >> "$avconv_out" 2>&1 &
	elif [ "$output_format" == 'swf' ] ; then
		# do pass one first, then add audio at the end during pass 2?
		# don't do mplex, do second pass instead.
		myecho "[dvd-slideshow] Exporting .swf file"
		avconv -threads "$cores" -f yuv4mpegpipe -i "$tmpdir"/$yuvfifo -r $framerate $qscale -an -s "$dvd_width"x"$dvd_height" -y -f flv "$tmpdir/video.swf" 1> /dev/null 2>> "$avconv_out" &
	elif [ "$output_format" == 'mp4' ] ; then   
		myecho '[dvd-slideshow] Exporting .mp4 file'
		avconv -threads "$cores" -f yuv4mpegpipe -i "$tmpdir"/$yuvfifo -r $framerate $qscale -an -s "$dvd_width"x"$dvd_height" -y -f mp4 -vcodec mpeg4 "$tmpdir/video.mp4" >> "$avconv_out" 2>&1 &
	elif [ "$output_format" == 'mp4_ipod' ] ; then   
		myecho "[dvd-slideshow] Exporting ipod .mp4 file"
		avconv -y -f yuv4mpegpipe -i "$tmpdir"/$yuvfifo -an -threads 0 -vcodec libx264 -refs 5 -subq 5 -crf 30 -maxrate 768000 -bufsize 244 -r $framerate -level 13 -s "$dvd_width"x"$dvd_height" -f mp4 "$tmpdir/video.mp4" >> "$avconv_out" 2>&1 &
	elif [ "$output_format" == 'ogv' ] ; then   
		myecho "[dvd-slideshow] Exporting .ogv file"
		avconv -threads "$cores" -f yuv4mpegpipe -i "$tmpdir"/$yuvfifo -r $framerate $qscale -an -s "$dvd_width"x"$dvd_height" -y -f ogg -vcodec libtheora "$tmpdir/video.ogv" >> "$avconv_out" 2>&1 &
	elif [ "$output_format" == 'mpg' ] ; then
		# do pass one first, then add audio at the end during pass 2?
		# don't do mplex, do second pass instead.
		myecho "[dvd-slideshow] Exporting .mpg file"
		avconv -threads "$cores" -f yuv4mpegpipe -i "$tmpdir"/$yuvfifo -r $framerate -an -aspect $aspect_ratio -s "$dvd_width"x"$dvd_height" -y -f mpeg2video "$tmpdir/video.mpg" >> "$avconv_out" 2>&1 &
	else  # default mpeg2 video for dvd/vcd
		avconv -threads "$cores" -f yuv4mpegpipe -i "$tmpdir"/$yuvfifo -target $avconv_target -r $framerate -an -aspect $aspect_ratio -s "$dvd_width"x"$dvd_height" -y -bf 2 -f mpeg2video "$tmpdir/video.mpg" >> "$avconv_out" 2>&1 &
	fi
else
	if [ "$output_format" == 'mpg' -o "$output_format" == 'mpeg2' ] ; then
		mpeg2enc $mpeg2enc_params -o "$tmpdir/video.mpg" < "$tmpdir"/$yuvfifo >> "$outdir/$logfile" 2>&1 & 
	else
		myecho "[dvd-slideshow] ERROR: mpeg2enc only encodes .mpg video"
		cleanup; exit 1;
	fi	
fi
yuvpid=${!}

# open the fifo for writing as file descriptor #9 (unlikely to be used!)
exec 9> "$tmpdir/$yuvfifo"

## make both a slideshow_background file and a title_background file
if [ -f "${bgfile}" ] ; then
	background "$bgfile"
else
	background "black"
fi

# prepare transparent background file:
transparent_bg="$tmpdir"/transparent_background.png
normal_bg="$tmpdir/slideshow_background.ppm"
convert -size "$dvd_width"'x'"$dvd_height" xc:transparent -type TrueColorMatte -depth 8 "$transparent_bg"

#if [ "$debug" -gt 0 ] || [ "$quiet" == 0 ] ; then
	myecho "[dvd-slideshow]############################################################"
#fi

total_slideshow_time=0
total_slideshow_frames=0

let i=0 # full
let v=0 # vob
image_number=1
for file in "${image[@]}"; do
	di=`addzeros $i`
	## check for variable settings first:
#	echo "i=$i file=$file duration=${duration[$i]}"
	set_variables "$file" 1
	it=`set_variables "$file" 0`
	if [ -n "$it" ] ; then
		myecho "[dvd-slideshow] Set variable $it"
		i=$(( $i+1 )) ; continue
	fi
	
	frames=$( duration2frames ${duration[$i]} )
	rendered_frames="$frames"
	## get start frame & time:
	slide_start_frame=$(( $total_slideshow_frames ))
	slide_start_time=$(( $slide_start_frame *1000 * 1000 / $frames_per_ms )) ## in thousandths of a sec.
	slide_start_hms=`hms "$slide_start_time"`
	if [ $debug -ge 1 ] ; then
		myecho "[dvd-slideshow] start_frame_number=$slide_start_frame start_time=$slide_start_hms"
#		myecho "[dvd-slideshow] This line duration=`echo ${duration[$i]} | tr -d \[:blank:\]` ms"
	fi


	if [ $debug -ge 2 ] ; then
		[ -n "${effect1[$i]}" ] && myecho "[dvd-slideshow] effect1='${effect1[$i]}' effect_params='${effect1_params[$i]}'"
		[ -n "${effect1[$i]}" ] && myecho "[dvd-slideshow] effect2='${effect2[$i]}' effect_params='${effect2_params[$i]}'"
	fi
        if [ "$file" == 'title' -o "$file" == 'Title' ] ; then # TITLE
                if [ -n "${effect1[$i]}" ] ; then
                        myecho "[dvd-slideshow] WARNING: This keyword has changed since dvd-slideshow 0.7.5"
                        myecho "[dvd-slideshow]       Title only has one argument. Use titlebar for"
                        myecho "[dvd-slideshow]       the same menu type as before. See documentation."
                        myecho "[dvd-slideshow]       Only using one title line, centered in the screen."
                fi
                if [ -n "${subtitle[$i]}" ] ; then
                	title="${subtitle[$i]}"
		elif [ -n "${effect1[$i]}" ] ; then
                	title="${effect1[$i]}"
		else
			myecho "[dvd-slideshow] ERROR: no title text found in line:"
			myecho "[dvd-slideshow] ${thisline}"
			cleanup; exit 1
		fi
                myecho "[dvd-slideshow] Title `hms ${duration[$i]}`"
                myecho "[dvd-slideshow]         Title=$title"

		if [ "$first_title" == 1 ] ; then
			first_title=0
			hilight_title="$title"
#			hilight_image="$image"
		fi
		# calculate actual frames rendered:
		previous_transition_increment="`previousTransitionIncrement`"
		previous_duration="${duration[$i-$previous_transition_increment]}" # already in thousandths.
		previous_slide="${image[$i-$previous_transition_increment]}"
		next_transition_increment="`nextTransitionIncrement`"
		next_duration="${duration[$i+$next_transition_increment]}" # already in thousandths.
		next_slide="${image[$i+$next_transition_increment]}"
		[ -z "$previous_slide" ] && previous_slide=0
		[ -z "$next_slide" ] && next_slide=0
#		echo "duration=${duration[$i]}  previous_inc=$previous_transition_increment previous_slide=$previous_slide previous_duration=$previous_duration"
		if [ "$previous_slide" == 'crossfade' ] || [ "$previous_slide" == 'wipe' ] ; then
			# subtract 1/2 time from rendered time:
			rendered_time=$(( ${duration[$i]} - $previous_duration / 2 )) 
			old_rendered_time=$(( ${duration[$i]} + $previous_duration ))
		elif [ "$previous_slide" == 'fadein' ] ; then
			rendered_time=$(( ${duration[$i]} - $previous_duration )) 
			old_rendered_time=$(( ${duration[$i]} + $previous_duration ))
		else  # no previous fade
			rendered_time=${duration[$i]}
			old_rendered_time=$rendered_time
		fi
#		echo "duration=${duration[$i]}  next_transition_increment=$next_transition_increment next_slide=$next_slide next_duration=$next_duration"
		if [ "$next_slide" == 'crossfade' ] || [ "$next_slide" == 'wipe' ] ; then
			# subtract time from rendered time:
			rendered_time=$(( $rendered_time - $next_duration / 2 )) 
			old_rendered_time=$(( $rendered_time + $next_duration )) 
		elif [ "$next_slide" == 'fadeout' ] ; then
			rendered_time=$(( $rendered_time - $next_duration )) 
			old_rendered_time=$(( $rendered_time + $next_duration )) 
		else  # no next fade
			rendered_time=$rendered_time	
			old_rendered_time=$old_rendered_time
		fi

		set_end_frame_time $rendered_time
		rendered_frames="$frames_to_render"

		[ $debug -ge 2 ] && echo "[dvd-slideshow] rendered_frames=$rendered_frames"
		if [ "$rendered_frames" -le 0 ] ; then
			echo "[dvd-slideshow] WARNING: Frames rendered are less than 1!"
			echo "[dvd-slideshow] 	Either you specified a duration = 0 "
			echo "[dvd-slideshow] 	or the fade time(s) are longer than the slide time."
			echo "[dvd-slideshow] 	!! This timing changed in dvd-slideshow 0.8.0."
			echo "[dvd-slideshow] 	!! so now the fades get applied on top of the slides"
			echo "[dvd-slideshow] 	!! and thus fades do not add time to the slideshow."
			echo "[dvd-slideshow] 	MODIFYING SLIDE TIME to $(hms $old_rendered_time)"
			set_end_frame_time $old_rendered_time
			rendered_frames="$frames_to_render"
		fi
                subtitle[$i]=''  # set subtitle to nothing so we don't get a subtitle
                ## now the slide may already exist if we had a fadein or crossfade before
                if [ ! -f "$tmpdir/slide_$i.ppm" ] ; then
                        titleslide "$title"
                        waitforfile "$tmpdir/title.ppm"
                        cp "$tmpdir/title.ppm" "$tmpdir/slide_$i.ppm"
                fi
		if [ -n "$logo" ] ; then  # optionally add logo layer
			add_logo "$logo" slide_$i.ppm "$logo_gravity"
		fi
		encode "$tmpdir/slide_$i.ppm" $rendered_frames
                [ "$manual_chapter_markers" -eq 0 ] && write_chap=1
		[ $debug -ge 1 ] &&  myecho "[dvd-slideshow] end_frame_number=$slide_end_frame end_time=$slide_end_hms"
                myecho "[dvd-slideshow]############################################################"
        elif [ "$file" == 'titlebar' -o "$file" == 'Titlebar' ] ; then # TITLEBAR
                title1="${subtitle[$i]}"
                subtitle[$i]=''  # set subtitle to nothing so we don't get a subtitle
                title2="${effect1[$i]}"
                myecho "[dvd-slideshow] Titlebar `hms ${duration[$i]}`"
	        myecho "[dvd-slideshow]         Title1=$title1"
		myecho "[dvd-slideshow]         Title2=$title2"

		# calculate actual frames rendered:
		previous_transition_increment="`previousTransitionIncrement`"
		previous_duration="${duration[$i-$previous_transition_increment]}" # already in thousandths.
		previous_slide="${image[$i-$previous_transition_increment]}"
		next_transition_increment="`nextTransitionIncrement`"
		next_duration="${duration[$i+$next_transition_increment]}" # already in thousandths.
		next_slide="${image[$i+$next_transition_increment]}"
		[ -z "$previous_slide" ] && previous_slide=0
		[ -z "$next_slide" ] && next_slide=0
#		echo "duration=${duration[$i]}  previous_inc=$previous_transition_increment previous_slide=$previous_slide previous_duration=$previous_duration"
		if [ "$previous_slide" == 'crossfade' ] || [ "$previous_slide" == 'wipe' ] ; then
			# subtract 1/2 time from rendered time:
			rendered_time=$(( ${duration[$i]} - $previous_duration / 2 )) 
			old_rendered_time=$(( ${duration[$i]} + $previous_duration ))
		elif [ "$previous_slide" == 'fadein' ] ; then
			rendered_time=$(( ${duration[$i]} - $previous_duration )) 
			old_rendered_time=$(( ${duration[$i]} + $previous_duration ))
		else  # no previous fade
			rendered_time=${duration[$i]}
			old_rendered_time=$rendered_time
		fi
#		echo "duration=${duration[$i]}  next_transition_increment=$next_transition_increment next_slide=$next_slide next_duration=$next_duration"
		if [ "$next_slide" == 'crossfade' ] || [ "$next_slide" == 'wipe' ] ; then
			# subtract time from rendered time:
			rendered_time=$(( $rendered_time - $next_duration / 2 )) 
			old_rendered_time=$(( $rendered_time + $next_duration )) 
		elif [ "$next_slide" == 'fadeout' ] ; then
			rendered_time=$(( $rendered_time - $next_duration )) 
			old_rendered_time=$(( $rendered_time + $next_duration )) 
		else  # no next fade
			rendered_time=$rendered_time	
			old_rendered_time=$old_rendered_time
		fi

		set_end_frame_time $rendered_time
		rendered_frames="$frames_to_render"

		if [ "$rendered_frames" -le 0 ] ; then
			echo "[dvd-slideshow] WARNING: Frames rendered are less than 1!"
			echo "[dvd-slideshow] 	Either you specified a duration = 0 "
			echo "[dvd-slideshow] 	or the fade time(s) are longer than the slide time."
			echo "[dvd-slideshow] 	!! This timing changed in dvd-slideshow 0.8.0."
			echo "[dvd-slideshow] 	!! so now the fades get applied on top of the slides"
			echo "[dvd-slideshow] 	!! and thus fades do not add time to the slideshow."
			echo "[dvd-slideshow] 	MODIFYING SLIDE TIME to $(hms $old_rendered_time)"
			set_end_frame_time $old_rendered_time
			rendered_frames="$frames_to_render"
		fi

                ## now the slide may already exist if we had a fadein or crossfade before
                if [ ! -f "$tmpdir/slide_$i.ppm" ] ; then
                        titlebarslide "$title1" "$title2"
                        waitforfile "$tmpdir/title.ppm"
                        cp "$tmpdir/title.ppm" "$tmpdir/slide_$i.ppm"
                fi
		if [ -n "$logo" ] ; then  # optionally add logo layer
			add_logo "$logo" slide_$i.ppm "$logo_gravity"
		fi
		encode "$tmpdir/slide_$i.ppm" $rendered_frames
                [ "$manual_chapter_markers" -eq 0 ] && write_chap=1
		[ $debug -ge 1 ] &&  myecho "[dvd-slideshow] end_frame_number=$slide_end_frame end_time=$slide_end_hms"
               	myecho "[dvd-slideshow]############################################################"
	elif [ "$file" == 'musictitle' ] ; then # MUSICTITLE
		## add a music-video style title page
		## format is:
		## musictitle:duration:subtitle:MusicTitle:MusicArtist;MusicAlbum
		Title="Title: ${effect1[$i]}"
		Artist="Artist: `echo ${effect1_params[$i]} | awk -F';' '{print $1}'`"
		Album="Album: `echo ${effect1_params[$i]} | awk -F';' '{print $2}'`"
#		subtitle[$i]=''  # set subtitle to nothing so we don't get a subtitle
		myecho "[dvd-slideshow] Making musictitle slide:"
		myecho "[dvd-slideshow] $Title $Artist $Album"
		[ -n "${subtitle[$i]}" ] && myecho "[dvd-slideshow] Subtitle""= ${subtitle[$i]}"

		# calculate actual frames rendered:
		previous_transition_increment="`previousTransitionIncrement`"
		previous_duration="${duration[$i-$previous_transition_increment]}" # already in thousandths.
		previous_slide="${image[$i-$previous_transition_increment]}"
		next_transition_increment="`nextTransitionIncrement`"
		next_duration="${duration[$i+$next_transition_increment]}" # already in thousandths.
		next_slide="${image[$i+$next_transition_increment]}"
		[ -z "$previous_slide" ] && previous_slide=0
		[ -z "$next_slide" ] && next_slide=0
#		echo "duration=${duration[$i]}  previous_inc=$previous_transition_increment previous_slide=$previous_slide previous_duration=$previous_duration"
		if [ "$previous_slide" == 'crossfade' ] || [ "$previous_slide" == 'wipe' ] ; then
			# subtract 1/2 time from rendered time:
			rendered_time=$(( ${duration[$i]} - $previous_duration / 2 )) 
			old_rendered_time=$(( ${duration[$i]} + $previous_duration ))
		elif [ "$previous_slide" == 'fadein' ] ; then
			rendered_time=$(( ${duration[$i]} - $previous_duration )) 
			old_rendered_time=$(( ${duration[$i]} + $previous_duration ))
		else  # no previous fade
			rendered_time=${duration[$i]}
			old_rendered_time=$rendered_time
		fi
#		echo "duration=${duration[$i]}  next_transition_increment=$next_transition_increment next_slide=$next_slide next_duration=$next_duration"
		if [ "$next_slide" == 'crossfade' ] || [ "$next_slide" == 'wipe' ] ; then
			# subtract time from rendered time:
			rendered_time=$(( $rendered_time - $next_duration / 2 )) 
			old_rendered_time=$(( $rendered_time + $next_duration )) 
		elif [ "$next_slide" == 'fadeout' ] ; then
			rendered_time=$(( $rendered_time - $next_duration )) 
			old_rendered_time=$(( $rendered_time + $next_duration )) 
		else  # no next fade
			rendered_time=$rendered_time	
			old_rendered_time=$old_rendered_time
		fi

		set_end_frame_time $rendered_time
		rendered_frames="$frames_to_render"

		if [ "$rendered_frames" -le 0 ] ; then
			echo "[dvd-slideshow] WARNING: Frames rendered are less than 1!"
			echo "[dvd-slideshow] 	Either you specified a duration = 0 "
			echo "[dvd-slideshow] 	or the fade time(s) are longer than the slide time."
			echo "[dvd-slideshow] 	!! This timing changed in dvd-slideshow 0.8.0."
			echo "[dvd-slideshow] 	!! so now the fades get applied on top of the slides"
			echo "[dvd-slideshow] 	!! and thus fades do not add time to the slideshow."
			echo "[dvd-slideshow] 	MODIFYING SLIDE TIME to $(hms $old_rendered_time)"
			set_end_frame_time $old_rendered_time
			rendered_frames="$frames_to_render"
		fi

                ## now the slide may already exist if we had a fadein or crossfade before
                if [ ! -f "$tmpdir/slide_$i.ppm" ] ; then
                        musictitleslide "$Title" "$Artist" "$Album"
                        waitforfile "$tmpdir/title.ppm"
                        mv "$tmpdir/title.ppm" "$tmpdir/slide_$i.ppm"
                fi
		if [ -n "$logo" ] ; then  # optionally add logo layer
			add_logo "$logo" slide_$i.ppm "$logo_gravity"
		fi
		encode "$tmpdir/slide_$i.ppm" $rendered_frames
		[ "$manual_chapter_markers" -eq 0 ] && write_chap=1
		[ $debug -ge 1 ] &&  myecho "[dvd-slideshow] end_frame_number=$slide_end_frame end_time=$slide_end_hms"
                myecho "[dvd-slideshow]############################################################"
        elif [ "${avi_file[$i]}" -eq 1 ] ; then  ##########  AVI 
		## use avconv to encode video. No audio.
		myecho "[dvd-slideshow] AVI file passed."
		[ "$manual_chapter_markers" -eq 0 ] && write_chap=1
		# check for bad syntax:
		previous_transition_increment="`previousTransitionIncrement`"
		previous_duration="${duration[$i-$previous_transition_increment]}" # already in thousandths.
		next_transition_increment="`nextTransitionIncrement`"
		next_duration="${duration[$i+$next_transition_increment]}" # already in thousandths.
		if [ "${image[$i-$previous_transition_increment]}" == 'fadein' ] || [ "${image[$i-$previous_transition_increment]}" == 'crossfade' ] || [ "${image[$i-$previous_transition_increment]}" == 'wipe' ] ; then 
			myecho "[dvd-slideshow] WARNING: Cannot fadein or crossfade to a .avi file (yet)"
#			exit 1
		fi
		if [ "${image[$i+$next_transition_increment]}" == 'fadeout' ] || [ "${image[$i+$next_transition_increment]}" == 'crossfade' ] || [ "${image[$i+$next_transition_increment]}" == 'wipe' ]; then
			myecho "[dvd-slideshow] WARNING: Cannot fadeout or crossfade from a .avi file (yet)"
#			exit 1
		fi
		## encode video
#		myecho "[dvd-slideshow] Encoding ${image[$i]} to video.mpg"
		# let's re-encode it just to make sure every video works:
		# this is really inefficient, but it should work. 
		if [ "$pal" -eq 1 ] ; then
			avconv -threads "$cores" -i "${image[$i]}" -target pal-dvd "$tmpdir"/tmp.avi >> "$avconv_out" 2>&1
		else
			avconv -threads "$cores" -i "${image[$i]}" -target ntsc-dvd "$tmpdir"/tmp.avi >> "$avconv_out" 2>&1
		fi
		encode_video "$tmpdir"/tmp.avi
		# now remove the temporary file (thanks for fix by Marc Wäckerlin)
		rm "$tmpdir"/tmp.avi

		# convert audio to wav format?  
		echo "audio_track[$i] = ${audio_track[$i]}"
		if [ "${audio_track[$i]}" != 'noaudio' ] ; then
			myecho "[dvd-slideshow] Processing audio from video file..."
			## now set the starting and ending point of this audio track:
			audio_track[$i]=1
			audio1_effect1[$i_audio]="${effect1[$i]}"
			audio1_effect1_params[$i_audio]="${effect1_params[$i]}"
			audio1_effect2[$i_audio]="${effect2[$i]}"
			audio1_effect2_params[$i_audio]="${effect2_params[$i]}"
			audio_index="$i_audio"
			audio_index_padded=`addzeros "$i_audio"`
			audio_1[$i_audio]="$tmpdir/audio1_$audio_index_padded.wav"
#			echo "i_audio=$i_audio audio_index=$audio_index padded=$audio_index_padded"
#			echo "audio_1=${audio_1[$i_audio]}"
			i_audio=$(( $i_audio + 1 ))  # increment for next file

			avconv -threads "$cores" -i "${image[$i]}" -y -vn -ar $audio_sample_rate -ac 2 "$tmpdir/audio1_$audio_index_padded".wav >> "$avconv_out" 2>&1
			if [ $? -ne 0 ] ; then
				## avconv errored
				myecho "[dvd-slideshow] ERROR during avconv execution!"
				myecho "[dvd-slideshow] see $outdir/$logfile for details"
				cleanup; exit 1
			fi
		        set_end_frame_time ${duration[$i]} # compute end of video which is end of audio
			audio1_start[$audio_index]="$slide_start_time"   # in ms
			## set ending point of the previous audio track:
			if [ "$audio_index" -gt 0 ] ; then # not first audio track
				audio1_end[$(($audio_index-1))]="$slide_start_time"   # in ms from last slide
				myecho "[dvd-slideshow] Set end time for audio file $audio_index to `hms $slide_end_time`"
			else # set audio end to zero for now...
				audio1_end[$audio_index]=0   # in ms from last slide
			fi
			myecho "[dvd-slideshow] slide track=${audio_track[$i]} audio_start=$slide_start_time audio_end=$slide_end_time"
			waitforfile "$tmpdir/audio1_$audio_index_padded".wav
			song_length_ms=`wavlength "$tmpdir/audio1_$audio_index_padded".wav`
			song_length_hms=`hms "$song_length_ms"`
			echo "[dvd-slideshow] Audio length ms=$song_length_ms  $song_length_hms"
		else
			set_end_frame_time ${duration[$i]} #
		fi
		subtitle[$i]=''  # set subtitle to nothing so we don't get a subtitle
		[ $debug -ge 1 ] &&  myecho "[dvd-slideshow] end_frame_number=$slide_end_frame end_time=$slide_end_hms"
		myecho "[dvd-slideshow]############################################################"
	elif [ "${image_file[$i]}" -eq 1 ] && [ -z "${effect1[$i]}" ] ; then  # JPG IMAGE
		## use real jpeg. 
		## now the slide may already exist if we had a fadein or crossfade before
		if [ "$quiet" == 0 ] ; then
			myecho "[dvd-slideshow] $image_number/$imagefiles $(truncate_filename "$file") `hms ${duration[$i]}`"
		fi
		[ -n "${subtitle[$i]}" ] && myecho "[dvd-slideshow] Subtitle= ${subtitle[$i]}"
		if [ "$first_image" == 1 ] && [ "${image[$i]}" != 'background' ] ; then
			first_image=0
			hilight_image="${image[$i]}"
		fi

		# calculate actual frames rendered:
		previous_transition_increment="`previousTransitionIncrement`"
		previous_duration="${duration[$i-$previous_transition_increment]}" # already in thousandths.
		previous_slide="${image[$i-$previous_transition_increment]}"
		next_transition_increment="`nextTransitionIncrement`"
		next_duration="${duration[$i+$next_transition_increment]}" # already in thousandths.
		next_slide="${image[$i+$next_transition_increment]}"
		[ -z "$previous_slide" ] && previous_slide=0
		[ -z "$next_slide" ] && next_slide=0
#		echo "duration=${duration[$i]}  previous_inc=$previous_transition_increment previous_slide=$previous_slide previous_duration=$previous_duration"
		if [ "$previous_slide" == 'crossfade' ] || [ "$previous_slide" == 'wipe' ] ; then
			# subtract 1/2 time from rendered time:
			rendered_time=$(( ${duration[$i]} - $previous_duration / 2 )) 
			old_rendered_time=$(( ${duration[$i]} + $previous_duration ))
		elif [ "$previous_slide" == 'fadein' ] ; then
			rendered_time=$(( ${duration[$i]} - $previous_duration )) 
			old_rendered_time=$(( ${duration[$i]} + $previous_duration ))
		else  # no previous fade
			rendered_time=${duration[$i]}
			old_rendered_time=$rendered_time
		fi
#		echo "duration=${duration[$i]}  next_transition_increment=$next_transition_increment next_slide=$next_slide next_duration=$next_duration"
		if [ "$next_slide" == 'crossfade' ] || [ "$next_slide" == 'wipe' ] ; then
			# subtract time from rendered time:
			rendered_time=$(( $rendered_time - $next_duration / 2 )) 
			old_rendered_time=$(( $rendered_time + $next_duration )) 
		elif [ "$next_slide" == 'fadeout' ] ; then
			rendered_time=$(( $rendered_time - $next_duration )) 
			old_rendered_time=$(( $rendered_time + $next_duration )) 
		else  # no next fade
			rendered_time=$rendered_time	
			old_rendered_time=$old_rendered_time
		fi

		set_end_frame_time "$rendered_time"
		rendered_frames="$frames_to_render"

		[ $debug -ge 3 ] && echo "[dvd-slideshow] previous_transition_increment=$previous_transition_increment next_transition_increment=$next_transition_increment"
		[ $debug -ge 3 ] && echo "[dvd-slideshow] previous_duration=$previous_duration next_duration=$next_duration"
		[ $debug -ge 3 ] && echo "[dvd-slideshow] rendered_frames=$rendered_frames frames=$frames"
		[ $debug -ge 1 ] && echo "[dvd-slideshow] Rendering $rendered_frames frames at this time."
		if [ "$rendered_frames" -lt 0 ] ; then
			echo "[dvd-slideshow] WARNING: Frames rendered are less than 0!"
			echo "[dvd-slideshow] 	Either you specified a duration = 0 "
			echo "[dvd-slideshow] 	or the fade time(s) are longer than the slide time."
			echo "[dvd-slideshow] 	!! This timing changed in dvd-slideshow 0.8.0."
			echo "[dvd-slideshow] 	!! so now the fades get applied on top of the slides"
			echo "[dvd-slideshow] 	!! and thus fades do not add time to the slideshow."
			echo "[dvd-slideshow] 	MODIFYING SLIDE TIME to $(hms $old_rendered_time)"
			set_end_frame_time $old_rendered_time
			rendered_frames="$frames_to_render"
		fi

		
		if [ ! -f "$tmpdir/slide_$i.ppm" ] ; then 
			create_slide "$file" "$tmpdir/slide_$i.ppm"
		fi
		if [ -n "$logo" ] ; then  # optionally add logo layer
			if [ -z "$logo_gravity" ] ; then
				logo_gravity="southeast"
			fi	
			if [ -f "$logo" ] ; then
				composite -compose src-over -gravity $logo_gravity -type TrueColorMatte -depth 8 "$logo" "$tmpdir"/slide_"$i".ppm "$tmpdir"/slide_"$i".ppm
			else
				echo "[dvd-slideshow] ERROR: Logo specified but file not found:"
				echo "[dvd-slideshow] $logo"
			fi
		fi
		# optionally add subtitle to image:
		subtitle1[$i]="$( echo "${subtitle[$i]}" | awk -F';' '{print $1}' )"
		if [ -n "${subtitle1[$i]}" -a "$subtitle_type" == 'render' ] ; then
			subtitle "${subtitle1[$i]}" $i transparent # just creates the .png file for overlay
			composite -compose src-over -type TrueColorMatte -depth 8 "$tmpdir"/subtitle_"$i".png "$tmpdir"/slide_"$i".ppm "$tmpdir"/slide_"$i".ppm
		fi
		if [ -n "$logo" ] ; then  # optionally add logo layer
			add_logo "$logo" slide_$i.ppm "$logo_gravity"
		fi
		if [ "$frames_to_render" -ge 1 ] ; then
			encode "$tmpdir/slide_$i.ppm" $frames_to_render
		fi
		image_number=$(( $image_number + 1 ))
		[ "$manual_chapter_markers" -eq 0 ] && write_chap=1
		[ $debug -ge 1 ] &&  myecho "[dvd-slideshow] end_frame_number=$slide_end_frame end_time=$slide_end_hms"
#		if [ "${image[$i+$next_transition_increment]}" == 'fadeout' ] ; then
#                	echo -n ""
#		else
			if [ "$quiet" == 0 ] ; then
                		myecho "[dvd-slideshow]############################################################"
			else
				echo -n "#"
			fi
#		fi
	elif [ "$file" == 'fadein' ] ; then  # FADEIN
		## ok, let's copy the background and just fade the foreground:
		## check to make sure the next slide is an image:
		next_transition_increment="`nextTransitionIncrement`"
		myecho "[dvd-slideshow] Applying Fadein to next image `hms ${duration[$i]}`"
		# we should check this while parsing the .txt file!
		if [ "$next_transition_increment" -ne 0 ] ; then
			myecho "[dvd-slideshow] ERROR: Cannot fadein to another fade!"
			cleanup; exit 1
		fi
		[ -n "${subtitle[$i]}" ] && myecho "[dvd-slideshow] Fadein Subtitle=\"${subtitle[$i]}\""
		nextslide=`nextslidename`
		increment=`nextslideincrement`
		if [ -z "$increment" ] ; then
			myecho "[dvd-slideshow] ERROR: no next slide found to fadein to!"
			cleanup ; exit 1
		fi
		nextslide_effect="${effect1[$i+$increment]}"
		if [ "${avi_file[$i+$increment]}" == "1" ]; then
			myecho "[dvd-slideshow] WARNING: Skipping Fadein to .avi file"
                	myecho "[dvd-slideshow]############################################################"
			let i=$i+1
			continue
		fi
		rm -f "$tmpdir/slide_$(($i+$increment)).ppm" # make sure it doesn't already exist!
		## we need to prepare the NEXT image now:
                if [ "$nextslide" == 'title' ] || [ "$nextslide" == 'Title' ] ; then
	                if [ -n "${subtitle[$i+$increment]}" ] ; then
	                	title="${subtitle[$i+$increment]}"
			elif [ -n "$nextslide_effect" ] ; then
	                	title="$nextslide_effect"
			else
				myecho "[dvd-slideshow] ERROR: no title text found in line:"
				myecho "[dvd-slideshow] ${thisline}"
				cleanup; exit 1
			fi
                        titleslide "$title"
                        waitforfile "$tmpdir/title.ppm"
                        mv "$tmpdir"/title.ppm "$tmpdir"/"slide_$(($i+$increment)).ppm"
                elif [ "$nextslide" == 'titlebar' ] || [ "$nextslide" == 'Titlebar' ] ; then
                        title1="${subtitle[$i+$increment]}"
                        title2="$nextslide_effect"
                        titlebarslide "$title1" "$title2"
                        waitforfile "$tmpdir/title.ppm"
                        mv "$tmpdir"/title.ppm "$tmpdir"/"slide_$(($i+$increment)).ppm"
                elif [ "$nextslide" == 'musictitle' ] ; then
			Title="Title: $nextslide_effect"
			Artist="Artist: `echo ${effect1_params[$i+$increment]} | awk -F';' '{print $1}'`"
			Album="Album: `echo ${effect1_params[$i+$increment]} | awk -F';' '{print $2}'`"
                        musictitleslide "$Title" "$Artist" "$Album"
                        waitforfile "$tmpdir/title.ppm"
                        mv "$tmpdir"/title.ppm "$tmpdir"/"slide_$(($i+$increment)).ppm"
		elif [ "$nextslide_effect" == 'crop' ] ; then  # if next picture is specifically cropped
			window=`echo "${effect1_params[$i+$increment]}" | awk -F';' '{print $1";"$2}'`
			parse_window "$window" "${image[$i+$increment]}"
			mycrop  # takes the parameters from <parse_window> and returns: 
			convert "${image[$i+$increment]}" -filter $filtermethod -resize "$sq_to_dvd_pixels" -crop "$c_width"x"$c_height+$xc0+$yc0" +repage -resize "$frame_width"x"$frame_height" miff:- | composite -compose src-over -geometry "+$(( $xci + $frame_border ))+$(( $yci + $frame_border ))" -type TrueColorMatte -depth 8 - "$normal_bg" "$tmpdir/slide_$(($i+$increment)).ppm"
		elif [ "$nextslide_effect" == 'kenburns' ] ; then  # if next picture has kenburns effect
			myecho "[dvd-slideshow] Pre-rendering kenburns effect for fadein..."
			[ -f "$tmpdir"/fade_0001.ppm ] && \rm "$tmpdir"/fade_????.ppm  # remove any old files
			window_start=`echo "${effect1_params[$i+$increment]}" | awk -F';' '{print $1";"$2}'`
			window_end=`echo "${effect1_params[$i+$increment]}" | awk -F';' '{print $3";"$4}'`
			## number of frames in kenburns effect:
			next_frames="${frames_extended[$i+$increment]}"
			kenburns "$window_start" "$window_end" "${image[$i+$increment]}" "$next_frames" 1 "$frames" "$normal_bg" "."
		elif [ "$nextslide_effect" == 'scroll' ] ; then  # if next picture has scroll effect
			myecho "[dvd-slideshow] Pre-rendering scroll effect for fadein..."
			[ -f "$tmpdir"/fade_0001.ppm ] && \rm "$tmpdir"/fade_????.ppm  # remove any old files
			direction="${effect1_params[$i+$increment]}"
			next_frames="${frames_extended[$i+$increment]}"
			scroll "$direction" "${image[$i+$increment]}" "$normal_bg" "$next_frames" 1 "$frames" "."
		elif [ "$nextslide" == 'background' ] && [ "${duration[$i+$increment]}" -ne 0 ] ; then
			bg="$nextslide_effect"
			if [ -n "$bg" ] ; then
				background "$bg"   # calls the background image subroutine
				cp "$normal_bg" "$tmpdir/slide_$(($i+$increment)).ppm"
			else
				myecho "[dvd-slideshow] ERROR: Cannot fadein to the same background!"
				cleanup; exit 1
			fi
		else # no manual cropping next picture and it's not a title or background
			# need to read next variables BEFORE making next slide!
			read_next_variables
			create_slide "${image[$i+$increment]}" "$tmpdir/slide_$(($i+$increment)).ppm"
#			if [ -n "$logo" ] ; then  # optionally add logo layer
#				add_logo "$logo" slide_$(($i+$increment)).ppm "$logo_gravity"
#			fi
			subtitle1[$i+$increment]="$( echo "${subtitle[$i+$increment]}" | awk -F';' '{print $1}' )"
#			echo "subtitle1=${subtitle1[$i+$increment]}"
			if [ -n "${subtitle1[$i+$increment]}" -a "$subtitle_type" == 'render' ] ; then
				subtitle "${subtitle1[$i+$increment]}" "$(( $i + $increment))" transparent # creates subtitle_$(($i+$increment)).png
				composite -compose src-over -type TrueColorMatte -depth 8 "$tmpdir"/subtitle_"$(($i+$increment))".png "$tmpdir"/slide_"$(($i+$increment))".ppm "$tmpdir"/slide_"$(($i+$increment))".ppm
			fi
		fi

		if [ "$low_quality" -eq 1 ] ; then
			stepsize=3
		elif [ "$high_quality" -eq 1 ] ; then
			stepsize=1
		elif [ "$nextslide_effect" == 'kenburns' ] || [ "$nextslide_effect" == 'scroll' ] ; then
			stepsize=1
			myecho "[dvd-slidsehow] Fading..."
		else
			stepsize=1
		fi
		set_end_frame_time ${duration[$i]}
		[ $debug -ge 1 ] &&  myecho "[dvd-slideshow] end_frame_number=$slide_end_frame end_time=$slide_end_hms"
		lastbar=0 # required for progressbar reset
		echo -n  "[dvd-slideshow]" # i.e., no kenburns
		for (( fr=1 ; fr<=frames ; fr=fr+stepsize )) ; do
			dj=`addzeros $fr`
			progressbar $fr $frames
			percent=$(( 100 * $fr / $frames ))
#			echo "fr=$fr frames=$frames percent=$percent"
			if [ "$nextslide_effect" == 'kenburns' ] || [ "$nextslide_effect" == 'scroll' ] ; then
				if [ "$smp" -eq 1 ] ; then
				(mv "$tmpdir"/fade_$dj.ppm "$tmpdir"/kb_$dj.ppm ; $gm_cmd composite -compose $gm_compose -gravity center -type TrueColorMatte -depth 8 -dissolve $percent "$tmpdir/kb_$dj.ppm" "$normal_bg" "$tmpdir/fade_$dj.ppm" ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames ) &
				else
				(mv "$tmpdir"/fade_$dj.ppm "$tmpdir"/kb_$dj.ppm ; $gm_cmd composite -compose $gm_compose -gravity center -type TrueColorMatte -depth 8 -dissolve $percent "$tmpdir/kb_$dj.ppm" "$normal_bg" "$tmpdir/fade_$dj.ppm" ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames )
				fi
			elif [ "$smp" -eq 1 ] ; then
				( $gm_cmd composite -compose $gm_compose -gravity center -type TrueColorMatte -depth 8 -dissolve $percent "$tmpdir/slide_$(($i+$increment)).ppm" "$normal_bg" "$tmpdir/fade_$dj.ppm" ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames ) &
			else
				( $gm_cmd composite -compose $gm_compose -gravity center -type TrueColorMatte -depth 8 -dissolve $percent "$tmpdir/slide_$(($i+$increment)).ppm" "$normal_bg" "$tmpdir/fade_$dj.ppm" ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames )
			fi
		done
		waitforfiles "$tmpdir/fade" ppm $dj
		encode_fade
		finish_progressbar "$fr" $frames
		if [ "$nextslide_effect" == 'kenburns' ] || [ "$nextslide_effect" == 'scroll' ] ; then
			rm "$tmpdir"/kb_????.ppm
		fi
		rm "$tmpdir"/fade_????.ppm
	elif [ "$file" == 'crossfade' ] ; then  # CROSSFADE
		## ok, for crossfades, we need to fade both the foreground and background.
		## check to make sure the next slide is an image:
		## now make this get the last real image and the next real image
		## get next image:
#		progressbar_fr=0 ; progrssbar_frames=0
		nextslide=`nextslidename`
		if [ -z "$nextslide" ] ; then
			myecho "[dvd-slideshow] ERROR: No next slide to crossfade to!"
			cleanup ; exit 1 
		fi
		increment=`nextslideincrement` 
		nextslide_effect="${effect1[$i+$increment]}"
		previous_increment="`previousslideincrement`"
		if [ -z "$previous_increment" ] ; then 
			myecho "[dvd-slideshow] ERROR: No previous slide to crossfade from!"
			cleanup ; exit 1 
		fi
		previousslide_effect="${effect1[$i-$previous_increment]}"
		next_transition_increment=`nextTransitionIncrement`
		previous_frames=0; next_frames=0;
		# this should be done while parsing the .txt file!
		if [ "$next_transition_increment" -ne 0 ] ; then
			myecho "[dvd-slideshow] ERROR: Cannot crossfade to another fade!"
			cleanup; exit 1
		fi
		myecho "[dvd-slideshow] Applying Crossfade between images `hms ${duration[$i]}`"
		if [ "${avi_file[$i-$previous_increment]}" == "1" ] || [ "${avi_file[$i+$increment]}" == "1" ]; then
			myecho "[dvd-slideshow] WARNING: Skipping Crossfade from/to .avi file"
                	myecho "[dvd-slideshow]############################################################"
			let i=$i+1
			continue
		fi
		[ -n "${subtitle[$i]}" ] && myecho "[dvd-slideshow] Crossfade Subtitle= ${subtitle[$i]}"
#		myecho "[dvd-slideshow] next slide=$nextslide. increment=$increment."

		## need to break this up for new version:
		## first, render any previous effects (fixed slides should already exist)
		## then, render any next effects and/or fixed slides, including cropped slides.
		if [ "$previousslide_effect" == 'kenburns' ] ; then
			myecho "[dvd-slideshow] Rendering previous kenburns effect for crossfade..."
			# render end of last kenburns effect first:
			window_start=`echo "${effect1_params[$i-$previous_increment]}" | awk -F';' '{print $1";"$2}'`
			window_end=`echo "${effect1_params[$i-$previous_increment]}" | awk -F';' '{print $3";"$4}'`
			previous_frames="${frames_extended[$i-$previous_increment]}"
			## number of frames in kenburns effect:
			start_frame="$(( $previous_frames - $frames + 1 ))"
			kenburns "$window_start" "$window_end" "${image[$i-$previous_increment]}" "$previous_frames" "$start_frame" "$previous_frames" "$normal_bg" "."
			for (( fr=1 ; fr<=$frames ; fr=fr+1 )) ; do
				dj=`addzeros $fr`
				kb_dj=`addzeros $(( $start_frame + $fr - 1 ))`
				mv "$tmpdir/fade_$kb_dj.ppm" "$tmpdir/kb_prev_$dj.ppm"
			done
		elif [ "$previousslide_effect" == 'scroll' ] ; then
			myecho "[dvd-slideshow] Rendering previous scroll effect for crossfade..."
			direction="${effect1_params[$i-$previous_increment]}"
			previous_frames="${frames_extended[$i-$previous_increment]}"
			start_frame="$(( $previous_frames - $frames + 1 ))"
			scroll "$direction" "${image[$i-$previous_increment]}" "$normal_bg" "$previous_frames" "$start_frame"  "$previous_frames" "."
			for (( fr=1 ; fr<=$frames ; fr=fr+1 )) ; do
				dj=`addzeros $fr`
				kb_dj=`addzeros $(( $start_frame + $fr - 1 ))`
				mv "$tmpdir/fade_$kb_dj.ppm" "$tmpdir/kb_prev_$dj.ppm"
			done
		elif [ "$previousslide_effect" == 'wipe' ] ; then
			myecho "[dvd-slideshow] Not possible to crossfade from a wipe!"
			exit 1
		fi  # all other frames are static and should alaready be rendered
		#### Now prepare next frames:
		lastbar=0 # required for progressbar reset
		if [ "$nextslide" == 'title' ] || [ "$nextslide" == 'Title' ] ; then
	                if [ -n "${subtitle[$i+$increment]}" ] ; then
	                	title="${subtitle[$i+$increment]}"
			elif [ -n "$nextslide_effect" ] ; then
	                	title="$nextslide_effect"
			else
				myecho "[dvd-slideshow] ERROR: no title text found in line:"
				myecho "[dvd-slideshow] ${thisline}"
				cleanup; exit 1
			fi
			titleslide "$title"
			waitforfile "$tmpdir/title.ppm"
			mv "$tmpdir"/title.ppm "$tmpdir"/"slide_$(($i+$increment)).ppm"
                elif [ "$nextslide" == 'titlebar' ] || [ "$nextslide" == 'Titlebar' ] ; then
                        title1="${subtitle[$i+$increment]}"
                        title2="$nextslide_effect"
                        titlebarslide "$title1" "$title2"
                        waitforfile "$tmpdir/title.ppm"
                        mv "$tmpdir"/title.ppm "$tmpdir"/"slide_$(($i+$increment)).ppm"
                elif [ "$nextslide" == 'musictitle' ] ; then
			Title="Title: $nextslide_effect"
			Artist="Artist: `echo ${effect1_params[$i+$increment]} | awk -F';' '{print $1}'`"
			Album="Album: `echo ${effect1_params[$i+$increment]} | awk -F';' '{print $2}'`"
                        musictitleslide "$Title" "$Artist" "$Album"
                        waitforfile "$tmpdir/title.ppm"
                        mv "$tmpdir"/title.ppm "$tmpdir"/"slide_$(($i+$increment)).ppm"
		elif [ "$nextslide_effect" == 'crop' ] ; then  # if next picture is specifically cropped
			window=`echo "${effect1_params[$i+$increment]}" | awk -F';' '{print $1";"$2}'`
			parse_window "$window" "${image[$i+$increment]}"
			mycrop  # takes the parameters from <parse_window> and returns: 
			[ $debug -ge 2 ] && myecho "[dvd-slideshow] Crop $c_width"x"$c_height"+"$xc0"+"$yc0 composite" +"$xci"+$yci
			convert "${image[$i+$increment]}" -filter $filtermethod -resize "$sq_to_dvd_pixels" -crop "$c_width"x"$c_height+$xc0+$yc0" +repage -resize "$frame_width"x"$frame_height" -type TrueColorMatte -depth 8 miff:- | \
			composite -compose src-over -geometry "+$(( $xci + $frame_border ))+$(( $yci + $frame_border ))" -type TrueColorMatte -depth 8 - "$normal_bg" "$tmpdir/slide_$(($i+$increment)).ppm"
		elif [ "$nextslide_effect" == 'kenburns' ] ; then
			myecho "[dvd-slideshow] Rendering next kenburns effect for crossfade..."
			window_start=`echo "${effect1_params[$i+$increment]}" | awk -F';' '{print $1";"$2}'`
			window_end=`echo "${effect1_params[$i+$increment]}" | awk -F';' '{print $3";"$4}'`
			next_frames="${frames_extended[$i+$increment]}"
			kenburns "$window_start" "$window_end" "${image[$i+$increment]}" "$next_frames" 1 "$frames" "$normal_bg" '.'
			for (( fr=1 ; fr<=frames ; fr=fr+1 )) ; do
				dj=`addzeros $fr`
				mv "$tmpdir/fade_$dj.ppm" "$tmpdir/kb_next_$dj.ppm"
			done
		elif [ "$nextslide_effect" == 'scroll' ] ; then  # if next picture has scroll effect
			myecho "[dvd-slideshow] Rendering next scroll effect for crossfade..."
			direction="${effect1_params[$i+$increment]}"
			next_frames="${frames_extended[$i+$increment]}"
			scroll "$direction" "${image[$i+$increment]}" "$normal_bg" "$next_frames" 1 "$frames" "."
			for (( fr=1 ; fr<=frames ; fr=fr+1 )) ; do
				dj=`addzeros $fr`
				mv "$tmpdir/fade_$dj.ppm" "$tmpdir/kb_next_$dj.ppm"
			done
		elif [ "$nextslide_effect" == 'wipe' ] ; then  # if next picture has scroll effect
			myecho "[dvd-slideshow] Not possible to crossfade to a wipe!"
			exit 1
		elif [ "$nextslide" == 'background' ] && [ "${duration[$i+$increment]}" -ne 0 ] ; then
			bg="$nextslide_effect"
			background "$bg"   # calls the background image subroutine
			cp "$normal_bg" "$tmpdir/slide_$(($i+$increment)).ppm"
		else # no manual cropping next picture and it's not a title
			read_next_variables
			create_slide "$nextslide" "$tmpdir/slide_$(($i+$increment)).ppm"
#			if [ -n "$logo" ] ; then  # optionally add logo layer
#				add_logo "$logo" slide_$(($i+$increment)).ppm "$logo_gravity"
#			fi
			subtitle1[$i+$increment]="$( echo "${subtitle[$i+$increment]}" | awk -F';' '{print $1}' )"
			if [ -n "${subtitle1[$i+$increment]}" -a "$subtitle_type" == 'render' ] ; then
				subtitle "${subtitle1[$i+$increment]}" "$(( $i + $increment))" transparent # creates subtitle_$(($i+$increment)).png
				composite -compose src-over -type TrueColorMatte -depth 8 "$tmpdir"/subtitle_"$(($i+$increment))".png "$tmpdir"/slide_"$(($i+$increment))".ppm "$tmpdir"/slide_"$(($i+$increment))".ppm
			fi
		fi	
		## now do actual crossfade
		if [ "$low_quality" -eq 1 ] ; then
			stepsize=3
		elif [ "$high_quality" -eq 1 ] ; then
			stepsize=1
		elif [ "$previousslide_effect" == 'kenburns' ] || [ "$nextslide_effect" == 'kenburns' ] || [ "$previousslide_effect" == 'scroll' ] || [ "$nextslide_effect" == 'scroll' ] ; then
			stepsize=1
			myecho "[dvd-slidsehow] Crossfading..."
		else
			stepsize=2
		fi
		lastslide="`previousslideppm`"
		both=0
		if [ "$previousslide_effect" == 'scroll' ] && [ "$nextslide_effect" == 'scroll' ] ; then
			both=1
		elif [ "$previousslide_effect" == 'kenburns' ] && [ "$nextslide_effect" == 'kenburns' ] ; then
			both=1
		elif [ "$previousslide_effect" == 'scroll' ] && [ "$nextslide_effect" == 'kenburns' ] ; then
			both=1
		elif [ "$previousslide_effect" == 'kenburns' ] && [ "$nextslide_effect" == 'scroll' ] ; then
			both=1
		fi
		if [ -n "$lastcrossfade_pid" ] ; then
			# wait for last crossfade process to finish before starting a new one!
			# this might stop the random hangs in long slideshows...
#			echo "[dvd-slideshow] Waiting for last crossfade to finish rendering..."
			if [ -n "$( jobs -p | grep -F "$lastcrossfade_pid" )" ] ; then
				echo "[dvd-slideshow] Waiting for fade process $lastcrossfade_pid to finish" >> "$outdir"/"$logfile"
				wait "$lastcrossfade_pid" >> "$outdir"/"$logfile" 2>&1
			fi
		fi
		set_end_frame_time ${duration[$i]}
		[ $debug -ge 1 ] &&  myecho "[dvd-slideshow] end_frame_number=$slide_end_frame end_time=$slide_end_hms"
		lastbar=0 # required for progressbar reset
		echo -n  "[dvd-slideshow]" # i.e., no kenburns
		for (( fr=1 ; fr<=frames ; fr=fr+stepsize )) ; do
			progressbar $fr $frames 
			dj=`addzeros $fr`
			percent=$(( 100 * $fr / $frames ))
			if [ "$both" -eq 1 ] ; then
				if [ "$smp" -eq 1 ] ; then
				( $gm_cmd composite -compose $gm_compose -gravity center -type TrueColorMatte -depth 8 -dissolve $percent "$tmpdir/kb_next_$dj.ppm" "$tmpdir/kb_prev_$dj.ppm" "$tmpdir/fade_$dj.ppm" ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames ; rm "$tmpdir/kb_prev_$dj.ppm" ; rm "$tmpdir/kb_next_$dj.ppm" ) &
				lastcrossfade_pid="$!"
				else
				( $gm_cmd composite -compose $gm_compose -gravity center -type TrueColorMatte -depth 8 -dissolve $percent "$tmpdir/kb_next_$dj.ppm" "$tmpdir/kb_prev_$dj.ppm" "$tmpdir/fade_$dj.ppm" ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames ; rm "$tmpdir/kb_prev_$dj.ppm" ; rm "$tmpdir/kb_next_$dj.ppm" ) 
				fi
			elif [ "$previousslide_effect" == 'kenburns' ] || [ "$previousslide_effect" == 'scroll' ] ; then
				if [ "$smp" -eq 1 ] ; then
				( $gm_cmd composite -compose $gm_compose -gravity center -type TrueColorMatte -depth 8 -dissolve $percent "$tmpdir/slide_$(($i+$increment)).ppm" "$tmpdir/kb_prev_$dj.ppm" "$tmpdir/fade_$dj.ppm" ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames ; rm "$tmpdir/kb_prev_$dj.ppm" ) &
				lastcrossfade_pid="$!"
				else
				( $gm_cmd composite -compose $gm_compose -gravity center -type TrueColorMatte -depth 8 -dissolve $percent "$tmpdir/slide_$(($i+$increment)).ppm" "$tmpdir/kb_prev_$dj.ppm" "$tmpdir/fade_$dj.ppm" ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames ; rm "$tmpdir/kb_prev_$dj.ppm" ) 
				fi
			elif [ "$nextslide_effect" == 'kenburns' ] || [ "$nextslide_effect" == 'scroll' ] ; then
				if [ "$smp" -eq 1 ] ; then
				( $gm_cmd composite -compose $gm_compose -gravity center -type TrueColorMatte -depth 8 -dissolve $percent "$tmpdir/kb_next_$dj.ppm" "$lastslide" "$tmpdir/fade_$dj.ppm" ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames ; rm "$tmpdir/kb_next_$dj.ppm" ) &
				lastcrossfade_pid="$!"
				else
				( $gm_cmd composite -compose $gm_compose -gravity center -type TrueColorMatte -depth 8 -dissolve $percent "$tmpdir/kb_next_$dj.ppm" "$lastslide" "$tmpdir/fade_$dj.ppm" ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames ; rm "$tmpdir/kb_next_$dj.ppm" ) 
				fi
			else 	# no special effects, just images before and after crossfade
				if [ "$smp" -eq 1 ] ; then
				( $gm_cmd composite -compose $gm_compose -gravity center -type TrueColorMatte -depth 8 -dissolve $percent "$tmpdir/slide_$(($i+$increment)).ppm" "$lastslide" "$tmpdir/fade_$dj.ppm" ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames ) &
				lastcrossfade_pid="$!"
				else
				$gm_cmd composite -compose $gm_compose -gravity center -type TrueColorMatte -depth 8 -dissolve $percent "$tmpdir/slide_$(($i+$increment)).ppm" "$lastslide" "$tmpdir/fade_$dj.ppm" ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames
				fi
			fi
		done
		waitforfiles "$tmpdir/fade" ppm "$dj"
		encode_fade
		finish_progressbar $fr $frames
		find "$tmpdir" -name "fade*.ppm" -type f -print0 | xargs -0 rm -f  # remove old files
		find "$tmpdir" -name "kb_*" -type f -print0 | xargs -0 rm -f  # remove old files
	elif [ "$file" == 'fadeout' ] ; then  # FADEOUT
		## ok, let's copy the background and just fade the foreground:
		## number of frames to render is $frames
		myecho "[dvd-slideshow] Applying Fadeout from previous image `hms ${duration[$i]}`"
		[ -n "${subtitle[$i]}" ] && myecho "[dvd-slideshow] Fadeout Subtitle= ${subtitle[$i]}"
		previous_increment="`previousslideincrement`"
		if [ -z "$previous_increment" ] ; then 
			myecho "[dvd-slideshow] ERROR: No previous slide to fadeout from"
			cleanup ; exit 1 
		fi
		previousslide_effect="${effect1[$i-$previous_increment]}"
		previous_frames=0; 
		next_transition_increment=`nextTransitionIncrement`
		if [ "${avi_file[$i-$previous_increment]}" == "1" ]; then
			myecho "[dvd-slideshow] WARNING: Skipping Fadeout from .avi file"
                	myecho "[dvd-slideshow]############################################################"
			let i=$i+1
			continue
		fi
		if [ "$next_transition_increment" != 0 ] && ([ "${image[$i+$next_transition_increment]}" == 'crossfade' ] || [ "${image[$i+$next_transition_increment]}" == 'fadeout' ]) ; then
			myecho "[dvd-slideshow] ERROR: Cannot fadeout to a crossfade or another fadeout!"
			cleanup; exit 1
		fi
		start_frame=1
		# check if we're fading out from a kenburns or scroll effect:
		if [ "$previous_increment" -ne 0 ] ; then
			previous_frames="${frames_extended[$i-$previous_increment]}"
		fi
		if [ "$previousslide_effect" == 'kenburns' ] ; then
			myecho "[dvd-slideshow] Rendering previous kenburns effect for fadeout..."
			# render end of last kenburns effect first:
			window_start=`echo "${effect1_params[$i-$previous_increment]}" | awk -F';' '{print $1";"$2}'`
			window_end=`echo "${effect1_params[$i-$previous_increment]}" | awk -F';' '{print $3";"$4}'`
			previous_frames="${frames_extended[$i-$previous_increment]}"
			## number of frames in kenburns effect:
			start_frame="$(( $previous_frames - $frames  + 1 ))"
			kenburns "$window_start" "$window_end" "${image[$i-$previous_increment]}" "$previous_frames" "$start_frame" "$previous_frames" "$normal_bg" "."
			for (( fr=1 ; fr<=frames ; fr=fr+1 )) ; do
				dj=`addzeros $fr`
				kb_dj=`addzeros $(( $start_frame + $fr - 1 ))`
				mv "$tmpdir/fade_$kb_dj.ppm" "$tmpdir/kb_prev_$dj.ppm"
			done
		elif [ "$previousslide_effect" == 'scroll' ] ; then
			myecho "[dvd-slideshow] Rendering previous scroll effect for fadeout..."
			direction="${effect1_params[$i-$previous_increment]}"
			previous_frames="${frames_extended[$i-$previous_increment]}"
			start_frame="$(( $previous_frames - $frames  + 1 ))"
			scroll "$direction" "${image[$i-$previous_increment]}" "$normal_bg" "$previous_frames" "$start_frame"  "$previous_frames" "."
			for (( fr=1 ; fr<=frames ; fr=fr+1 )) ; do
				dj=`addzeros $fr`
				kb_dj=`addzeros $(( $start_frame + $fr - 1 ))`
				mv "$tmpdir/fade_$kb_dj.ppm" "$tmpdir/kb_prev_$dj.ppm"
			done
		else
			## get last slide first?
			lastslide="`previousslideppm`"
			if [ ! -f "$lastslide" ] ; then
				myecho "[dvd-slideshow] ERROR: $lastslide doesn't exist!"
				myecho "[dvd-slideshow]        you probably are fading without having"
				myecho "[dvd-slideshow]        specified a real image first."
				cleanup; exit 1
			fi
#			convert "$lastslide" "$tmpdir/temp_slideshow_image.mpc"
		fi

		if [ "$low_quality" -eq 1 ] ; then
			stepsize=3
		elif [ "$high_quality" -eq 1 ] ; then
			stepsize=1
		elif [ "$previousslide_effect" == 'kenburns' ] || [ "$previousslide_effect" == 'scroll' ] ; then
			stepsize=1
			myecho "[dvd-slidsehow] Fading..."
		else
			stepsize=1
		fi
		set_end_frame_time ${duration[$i]}
		[ $debug -ge 1 ] &&  myecho "[dvd-slideshow] end_frame_number=$slide_end_frame end_time=$slide_end_hms"
		echo -n "[dvd-slideshow]"
		lastbar=0 # required for progressbar
		for (( fr=1 ; fr<=frames ; fr=fr+stepsize )) ; do
			kb_dj=`addzeros $(( $fr + $start_frame - 1 ))`
			dj=`addzeros $fr`
			progressbar $fr $frames 
			percent=$(( 100 - 100 * $fr / $frames ))
#			echo "fr=$fr kb_fr=$kb_dj frames=$frames percent=$percent"
			if [ "$previousslide_effect" == 'kenburns' ] || [ "$previousslide_effect" == 'scroll' ] ; then
				if [ "$smp" -eq 1 ] ; then
				( $gm_cmd composite -compose $gm_compose -gravity center -type TrueColorMatte -depth 8 -dissolve $percent "$tmpdir/kb_prev_$dj.ppm" "$normal_bg" "$tmpdir/fade_$dj.ppm" ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames ) &
				else
				( $gm_cmd composite -compose $gm_compose -gravity center -type TrueColorMatte -depth 8 -dissolve $percent "$tmpdir/kb_prev_$dj.ppm" "$normal_bg" "$tmpdir/fade_$dj.ppm" ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames ) 
				fi
			elif [ "$smp" -eq 1 ] ; then
				( $gm_cmd composite -compose $gm_compose -gravity center -type TrueColorMatte -depth 8 -dissolve $percent "$lastslide" "$normal_bg" "$tmpdir/fade_$dj.ppm" ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames ) &
			else
				( $gm_cmd composite -compose $gm_compose -gravity center -type TrueColorMatte -depth 8 -dissolve $percent "$lastslide" "$normal_bg" "$tmpdir/fade_$dj.ppm" ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames )
			fi
		done
		waitforfiles "$tmpdir/fade" ppm $dj
		encode_fade
		finish_progressbar $fr $frames '#'
		find "$tmpdir" -name "fade*.ppm" -type f -print0 | xargs -0 rm -f  # remove old files
		find "$tmpdir" -name "kb_*" -type f -print0 | xargs -0 rm -f  # remove old files
	elif [ "$file" == 'wipe' ] ; then  # WIPE
		# wipe:duration:subtitle:[right|left|up|down]
		## This will wipe from left to right or right to left
		## check to make sure the next slide is an image:
		## now make this get the last real image and the next real image
		## get next image:
#		progressbar_fr=0 ; progrssbar_frames=0
		nextslide=`nextslidename`
		if [ -z "$nextslide" ] ; then
			myecho "[dvd-slideshow] ERROR: No next slide to wipe to!"
			cleanup ; exit 1 
		fi
		increment=`nextslideincrement` 
		nextslide_effect="${effect1[$i+$increment]}"
		previous_increment="`previousslideincrement`"
		if [ -z "$previous_increment" ] ; then 
			myecho "[dvd-slideshow] ERROR: No previous slide to wipe from"
			cleanup ; exit 1 
		fi
		previousslide_effect="${effect1[$i-$previous_increment]}"
		previousslide="${image[$i-$previous_increment]}"
		next_transition_increment=`nextTransitionIncrement`
		previous_frames=0; next_frames=0;
		# this should be done while parsing the .txt file!
		if [ "$next_transition_increment" -ne 0 ] ; then
			myecho "[dvd-slideshow] ERROR: Cannot wipe to another fade or wipe!"
			cleanup; exit 1
		fi
		myecho "[dvd-slideshow] Applying wipe between images `hms ${duration[$i]}`"
		if [ "${avi_file[$i-$previous_increment]}" == "1" ] || [ "${avi_file[$i+$increment]}" == "1" ]; then
			myecho "[dvd-slideshow] WARNING: Skipping Wipe from/to .avi file"
                	myecho "[dvd-slideshow]############################################################"
			let i=$i+1
			continue
		fi
		[ -n "${subtitle[$i]}" ] && myecho "[dvd-slideshow] Wipe Subtitle= ${subtitle[$i]}"
#		myecho "[dvd-slideshow] next slide=$nextslide. increment=$increment."

		## need to break this up for new version:
		## first, render any previous effects (fixed slides should already exist)
		## then, render any next effects and/or fixed slides, including cropped slides.
		## Set temporary background to tranaparent?
		no_effects=0
		last_outfile="$tmpdir"/last_slideshow_image_scaled.mpc
		next_outfile="$tmpdir"/next_slideshow_image_scaled.mpc
		if [ "$previousslide" == 'title' ] || [ "$previousslide" == 'Title' ] ; then
			if [ -z "$title" ] ; then
				myecho "[dvd-slideshow] ERROR: no title text found in line"
				cleanup; exit 1
			fi
			titleslide "$title" "$last_outfile" "$transparent_bg"
			no_effects=1
                elif [ "$previousslide" == 'titlebar' ] || [ "$previousslide" == 'Titlebar' ] ; then
                        titlebarslide "$title1" "$title2" "$last_outfile" "$transparent_bg"
			no_effects=1
                elif [ "$previousslide" == 'musictitle' ] ; then
			Title="Title: $previousslide_effect"
			Artist="Artist: `echo ${effect1_params[$i-$previous_increment]} | awk -F';' '{print $1}'`"
			Album="Album: `echo ${effect1_params[$i-$previous_increment]} | awk -F';' '{print $2}'`"
                        musictitleslide "$Title" "$Artist" "$Album" "$last_outfile" "$transparent_bg"
			no_effects=1
		elif [ "$previousslide_effect" == 'crop' ] ; then  # if previous picture is specifically cropped
			window=`echo "${effect1_params[$i-$previous_increment]}" | awk -F';' '{print $1";"$2}'`
			parse_window "$window" "${image[$i-$previous_increment]}"
			mycrop  # takes the parameters from <parse_window> and returns: 
			convert "${image[$i-$previous_increment]}" -filter $filtermethod -resize "$sq_to_dvd_pixels" -crop "$c_width"x"$c_height+$xc0+$yc0" +repage -resize "$frame_width"x"$frame_height" -type TrueColorMatte -depth 8 miff:- | \
			composite -compose src-over -geometry "+$(( $xci + $frame_border ))+$(( $yci + $frame_border ))" -type TrueColorMatte -depth 8 - "$transparent_bg" "$last_outfile"
			no_effects=1
		elif [ "$previousslide_effect" == 'kenburns' ] ; then
			myecho "[dvd-slideshow] Rendering previous kenburns effect for wipe..."
			# render end of last kenburns effect first:
			window_start=`echo "${effect1_params[$i-$previous_increment]}" | awk -F';' '{print $1";"$2}'`
			window_end=`echo "${effect1_params[$i-$previous_increment]}" | awk -F';' '{print $3";"$4}'`
			previous_frames="${frames_extended[$i-$previous_increment]}"
			## number of frames in kenburns effect:
			start_frame="$(( $previous_frames - $frames + 1 ))"
			kenburns "$window_start" "$window_end" "${image[$i-$previous_increment]}" "$previous_frames" "$start_frame" "$previous_frames" "$transparent_bg" "."
			for (( fr=1 ; fr<=$frames ; fr=fr+1 )) ; do
				dj=`addzeros $fr`
				kb_dj=`addzeros $(( $start_frame + $fr - 1 ))`
				mv "$tmpdir/fade_$kb_dj.png" "$tmpdir/kb_prev_$dj.png"
			done
		elif [ "$previousslide_effect" == 'scroll' ] ; then
			myecho "[dvd-slideshow] Rendering previous scroll effect for wipe..."
			direction="${effect1_params[$i-$previous_increment]}"
			previous_frames="${frames_extended[$i-$previous_increment]}"
			start_frame="$(( $previous_frames - $frames + 1 ))"
			scroll "$direction" "${image[$i-$previous_increment]}" "$transparent_bg" "$previous_frames" "$start_frame"  "$previous_frames" "."
			for (( fr=1 ; fr<=$frames ; fr=fr+1 )) ; do
				dj=`addzeros $fr`
				kb_dj=`addzeros $(( $start_frame + $fr - 1 ))`
				mv "$tmpdir/fade_$kb_dj.png" "$tmpdir/kb_prev_$dj.png"
			done
		else # no manual cropping next picture and it's not a title
			no_effects=1
			file1="$tmpdir/slide_$(($i-$previous_increment)).png"
			create_slide "${image[$i-$previous_increment]}" "$last_outfile" "$transparent_bg"
		fi  # all other frames are static and should alaready be rendered
		#### Now prepare next frames:
#		lastbar=0 # required for progressbar reset
		if [ "$nextslide" == 'title' ] || [ "$nextslide" == 'Title' ] ; then
	                if [ -n "${subtitle[$i+$increment]}" ] ; then
	                	title="${subtitle[$i+$increment]}"
			elif [ -n "$nextslide_effect" ] ; then
	                	title="$nextslide_effect"
			else
				myecho "[dvd-slideshow] ERROR: no title text found in line:"
				myecho "[dvd-slideshow] ${thisline}"
				cleanup; exit 1
			fi
			titleslide "$title" "$next_outfile" "$transparent_bg"
			if [ "$no_effects" -eq 1 ] ; then
				no_effects=2
				convert "$last_outfile" "$next_outfile" +append -type TrueColorMatte -depth 8 "$tmpdir"/temp_slideshow_image_scaled.mpc		
			fi
                elif [ "$nextslide" == 'titlebar' ] || [ "$nextslide" == 'Titlebar' ] ; then
                        title1="${subtitle[$i+$increment]}"
                        title2="$nextslide_effect"
                        titlebarslide "$title1" "$title2" "$next_outfile" "$transparent_bg"
			if [ "$no_effects" -eq 1 ] ; then
				no_effects=2
				convert "$last_outfile" "$next_outfile" +append -type TrueColorMatte -depth 8 "$tmpdir"/temp_slideshow_image_scaled.mpc		
			fi
                elif [ "$nextslide" == 'musictitle' ] ; then
			Title="Title: $nextslide_effect"
			Artist="Artist: `echo ${effect1_params[$i+$increment]} | awk -F';' '{print $1}'`"
			Album="Album: `echo ${effect1_params[$i+$increment]} | awk -F';' '{print $2}'`"
                        musictitleslide "$Title" "$Artist" "$Album" "$next_outfile" "$transparent_bg"
			if [ "$no_effects" -eq 1 ] ; then
				no_effects=2
				convert "$last_outfile" "$next_outfile" +append -type TrueColorMatte -depth 8 "$tmpdir"/temp_slideshow_image_scaled.mpc		
			fi
		elif [ "$nextslide_effect" == 'crop' ] ; then  # if next picture is specifically cropped
			window=`echo "${effect1_params[$i+$increment]}" | awk -F';' '{print $1";"$2}'`
			parse_window "$window" "${image[$i+$increment]}"
			mycrop  # takes the parameters from <parse_window> and returns: 
			convert "${image[$i+$increment]}" -filter $filtermethod -resize "$sq_to_dvd_pixels" -crop "$c_width"x"$c_height+$xc0+$yc0" +repage -resize "$frame_width"x"$frame_height" -type TrueColorMatte -depth 8 miff:- | \
			composite -compose src-over -geometry "+$(( $xci + $frame_border ))+$(( $yci + $frame_border ))" -type TrueColorMatte -depth 8 - "$transparent_bg" "$next_outfile"
		elif [ "$nextslide_effect" == 'kenburns' ] ; then
			myecho "[dvd-slideshow] Rendering next kenburns effect for wipe..."
			window_start=`echo "${effect1_params[$i+$increment]}" | awk -F';' '{print $1";"$2}'`
			window_end=`echo "${effect1_params[$i+$increment]}" | awk -F';' '{print $3";"$4}'`
			next_frames="${frames_extended[$i+$increment]}"
			kenburns "$window_start" "$window_end" "${image[$i+$increment]}" "$next_frames" 1 "$frames" "$transparent_bg" '.'
			for (( fr=1 ; fr<=frames ; fr=fr+1 )) ; do
				dj=`addzeros $fr`
				mv "$tmpdir/fade_$dj.png" "$tmpdir/kb_next_$dj.png"
			done
		elif [ "$nextslide_effect" == 'scroll' ] ; then  # if next picture has scroll effect
			myecho "[dvd-slideshow] Rendering next scroll effect for wipe..."
			direction="${effect1_params[$i+$increment]}"
			next_frames="${frames_extended[$i+$increment]}"
			scroll "$direction" "${image[$i+$increment]}" "$transparent_bg" "$next_frames" 1 "$frames" "."
			for (( fr=1 ; fr<=frames ; fr=fr+1 )) ; do
				dj=`addzeros $fr`
				mv "$tmpdir/fade_$dj.png" "$tmpdir/kb_next_$dj.png"
			done
		elif [ "$nextslide" == 'background' ] && [ "${duration[$i+$increment]}" -ne 0 ] ; then
			bg="$nextslide_effect"
			background "$bg"   # calls the background image subroutine
			cp "$normal_bg" "$tmpdir/slide_$(($i+$increment)).ppm"
		else # no manual cropping next picture and it's not a title
			create_slide "${image[$i+$increment]}" "$next_outfile" "$transparent_bg"
			if [ "$no_effects" -eq 1 ] ; then
				no_effects=2
				convert "$last_outfile" "$next_outfile" +append -type TrueColorMatte -depth 8 "$tmpdir"/temp_slideshow_image_scaled.mpc		
			fi
		fi	
		lastslide="`previousslideppm`"
		both=0
		if [ "$previousslide_effect" == 'scroll' ] && [ "$nextslide_effect" == 'scroll' ] ; then
			both=1
		elif [ "$previousslide_effect" == 'kenburns' ] && [ "$nextslide_effect" == 'kenburns' ] ; then
			both=1
		elif [ "$previousslide_effect" == 'scroll' ] && [ "$nextslide_effect" == 'kenburns' ] ; then
			both=1
		elif [ "$previousslide_effect" == 'kenburns' ] && [ "$nextslide_effect" == 'scroll' ] ; then
			both=1
		fi
		set_end_frame_time ${duration[$i]}
## now, all previous and next frames are created if they need to. Prepare for loop/composite:
		direction="$( echo "${effect1[$i]}" | tr -d \[:blank:\] )"
		[ -z "$direction" ] && direction='left'
		if [ "$direction" == 'right' ] ; then
#			myecho "[dvd-slideshow] Doing wipe right effect"
			xs1=0 ; ys1=0 # Image 1
			xe1=$(( $dvd_width - 0 )) ; ye1=0
			xs2=$(( -1 * $dvd_width + 0 )) ; ys2=0
			xe2=0 ; ye2=0 # Image 2
		elif [ "$direction" == 'left' ] ; then
#			myecho "[dvd-slideshow] Doing wipe left effect"
			xs1=0 ; ys1=0 # Image 1
			xe1=$(( -1 * $dvd_width + 0 )) ; ye1=0
			xs2=$(( $dvd_width - 0 )) ; ys2=0  # image 2
			xe2=0 ; ye2=0
		elif [ "$direction" == 'up' ] ; then
#			myecho "[dvd-slideshow] Doing wipe up effect"
			xs1=0 ; ys1=0 # Image 1
			ye1=$(( -1 * $dvd_height + 0 )) ; xe1=0
			ys2=$(( $dvd_height - 0 )) ; xs2=0  # image 2
			xe2=0 ; ye2=0
		elif [ "$direction" == 'down' ] ; then
#			myecho "[dvd-slideshow] Doing wipe down effect"
			xs1=0 ; ys1=0 # Image 1
			ye1=$(( $dvd_height - 0 )) ; xe1=0
			ys2=$(( -1 * $dvd_height + 0 )) ; xs2=0
			xe2=0 ; ye2=0 # Image 2
		else
			myecho "[dvd-slideshow] ERROR: bad effect parameters $direction."
			cleanup; exit 1
		fi
		[ "$debug" -ge 2 ] && myecho "[dvd-slideshow] params=$xs1,$ys1 ; $xs2,$ys2 ; $xe1,$ye1 ; $xe2,$ye2"
		if [ "$low_quality" -eq 1 ] ; then
			stepsize=3; interp=0
		elif [ "$previousslide_effect" == 'kenburns' ] || [ "$nextslide_effect" == 'kenburns' ] || [ "$previousslide_effect" == 'scroll' ] || [ "$nextslide_effect" == 'scroll' ] ; then
			stepsize=1; interp=0
			myecho "[dvd-slidsehow] Wiping..."
		elif [ "$high_quality" -eq 1 ] ; then
			stepsize=1; interp=1
		else
#			[ "$frames" -lt 45 ] && stepsize=1 || stepsize=2 
			stepsize=1; interp=0
		fi
		[ $debug -ge 1 ] &&  myecho "[dvd-slideshow] end_frame_number=$slide_end_frame end_time=$slide_end_hms"
		## smooth start and end parameters:
		F1=$(( $frames * 45 / 100 ))  # 20 percent smoothing
		F2=$(( $frames - $F1 ))	
		V1x=$( echo "scale=9; 2 * ( $xe1 - $xs1 ) / ( $frames + $F2 - $F1 )" | bc ) 
		V1y=$( echo "scale=9; 2 * ( $ye1 - $ys1 ) / ( $frames + $F2 - $F1 )" | bc )
		V2x=$( echo "scale=9; 2 * ( $xe2 - $xs2 ) / ( $frames + $F2 - $F1 )" | bc )
		V2y=$( echo "scale=9; 2 * ( $ye2 - $ys2 ) / ( $frames + $F2 - $F1 )" | bc )
		pi='3.14159265'
		echo -n "[dvd-slideshow]"
		lastbar=0 # required for progressbar
		for (( fr=1 ; fr<=frames ; fr=fr+stepsize )) ; do
			dj=`addzeros $fr`
			if [ $fr -le $F1 ] ; then   # inputs are relatively simple:  make function?
				# region 1
				x1=$( echo "scale=3; $xs1 + $V1x/2 *($fr - $F1/$pi *s($pi*$fr/$F1))" | bc -l )
				y1=$( echo "scale=3; $ys1 + $V1y/2 *($fr - $F1/$pi *s($pi*$fr/$F1))" | bc -l )
				[ $debug -ge 2 ] && myecho "[dvd-slideshow:wipe] $fr x1=$x1 y1=$y1 region 1"
				D1x1=$x1; D1y1=$y1
				x1_dec=`printf %3.3f "$x1" | awk -F. '{print "0."$2}'`; 
				y1_dec=`printf %3.3f "$y1" | awk -F. '{print "0."$2}'`;
				## Fix numbers without leading zeros:
				it=`printf %3f "$x1" | awk -F. '{print $1}'` ; [ -z "$it" ] && x1_whole=0 || x1_whole="$it"
				it=`printf %3f "$y1" | awk -F. '{print $1}'` ; [ -z "$it" ] && y1_whole=0 || y1_whole="$it"
				x1=$x1_whole ; y1=$y1_whole
				x2=$( echo "scale=3; $xs2 + $V2x/2 *($fr - $F1/$pi *s($pi*$fr/$F1))" | bc -l )
				y2=$( echo "scale=3; $ys2 + $V2y/2 *($fr - $F1/$pi *s($pi*$fr/$F1))" | bc -l )
				[ $debug -ge 2 ] && myecho "[dvd-slideshow:wipe] $fr x2=$x2 y2=$y2 region 1"
				D1x2=$x2; D1y2=$y2
				x2_dec=`printf %3.3f $x2 | awk -F. '{print "0."$2}'`; 
				y2_dec=`printf %3.3f $y2 | awk -F. '{print "0."$2}'`;
				## Fix numbers without leading zeros:
				it=`printf %3f "$x2" | awk -F. '{print $1}'` ; [ -z "$it" ] && x2_whole=0 || x2_whole="$it"
				it=`printf %3f "$y2" | awk -F. '{print $1}'` ; [ -z "$it" ] && y2_whole=0 || y2_whole="$it"
				x2=$x2_whole ; y2=$y2_whole
			elif [ $fr -ge $(( $F2 + 1 )) ] ; then
				# region 3
				x1=$( echo "scale=3; $D2x1 + $V1x/2 *( ($fr-$F2) + ($frames-$F2)/$pi*s(($fr-$F2)*$pi/($frames-$F2)) )" | bc -l )
				y1=$( echo "scale=3; $D2y1 + $V1y/2 *( ($fr-$F2) + ($frames-$F2)/$pi*s(($fr-$F2)*$pi/($frames-$F2)) )" | bc -l )
				[ $debug -ge 2 ] && myecho "[dvd-slideshow:wipe] $fr x1=$x1 y1=$y1 region 3"
				x1_dec=`printf %3.3f $x1 | awk -F. '{print "0."$2}'`; 
				y1_dec=`printf %3.3f $y1 | awk -F. '{print "0."$2}'`;
				## Fix numbers without leading zeros:
				it=`printf %3f "$x1" | awk -F. '{print $1}'` ; [ -z "$it" ] && x1_whole=0 || x1_whole="$it"
				it=`printf %3f "$y1" | awk -F. '{print $1}'` ; [ -z "$it" ] && y1_whole=0 || y1_whole="$it"
				x1=$x1_whole ; y1=$y1_whole
				x2=$( echo "scale=3; $D2x2 + $V2x/2 *( ($fr-$F2) + ($frames-$F2)/$pi*s(($fr-$F2)*$pi/($frames-$F2)) )" | bc -l )
				y2=$( echo "scale=3; $D2y2 + $V2y/2 *( ($fr-$F2) + ($frames-$F2)/$pi*s(($fr-$F2)*$pi/($frames-$F2)) )" | bc -l )
				[ $debug -ge 2 ] && myecho "[dvd-slideshow:wipe] $fr x2=$x2 y2=$y2 region 3"
				x2_dec=`printf %3.3f $x2 | awk -F. '{print "0."$2}'`; 
				y2_dec=`printf %3.3f $y2 | awk -F. '{print "0."$2}'`;
				## Fix numbers without leading zeros:
				it=`printf %3f "$x2" | awk -F. '{print $1}'` ; [ -z "$it" ] && x2_whole=0 || x2_whole="$it"
				it=`printf %3f "$y2" | awk -F. '{print $1}'` ; [ -z "$it" ] && y2_whole=0 || y2_whole="$it"
				x2=$x2_whole ; y2=$y2_whole
			else
				# middle region 2
				x1=$( echo "scale=3; $D1x1 + $V1x*($fr-$F1)" | bc )
				y1=$( echo "scale=3; $D1y1 + $V1y*($fr-$F1)" | bc )
				D2x1=$x1 ; D2y1=$y1
				[ $debug -ge 2 ] && myecho "[dvd-slideshow:wipe] $fr x1=$x1 y1=$y1 region 2"
				x1_dec=`printf %3.3f $x1 | awk -F. '{print "0."$2}'`; 
				y1_dec=`printf %3.3f $y1 | awk -F. '{print "0."$2}'`;
				## Fix numbers without leading zeros:
				it=`printf %3f "$x1" | awk -F. '{print $1}'` ; [ -z "$it" ] && x1_whole=0 || x1_whole="$it"
				it=`printf %3f "$y1" | awk -F. '{print $1}'` ; [ -z "$it" ] && y1_whole=0 || y1_whole="$it"
				x1=$x1_whole ; y1=$y1_whole
				x2=$( echo "scale=3; $D1x2 + $V2x*($fr-$F1)" | bc )
				y2=$( echo "scale=3; $D1y2 + $V2y*($fr-$F1)" | bc )
				D2x2=$x2 ; D2y2=$y2
				[ $debug -ge 2 ] && myecho "[dvd-slideshow:wipe] $fr x2=$x2 y2=$y2 region 2"
				x2_dec=`printf %3.3f $x2 | awk -F. '{print "0."$2}'`; 
				y2_dec=`printf %3.3f $y2 | awk -F. '{print "0."$2}'`;
				## Fix numbers without leading zeros:
				it=`printf %3f "$x2" | awk -F. '{print $1}'` ; [ -z "$it" ] && x2_whole=0 || x2_whole="$it"
				it=`printf %3f "$y2" | awk -F. '{print $1}'` ; [ -z "$it" ] && y2_whole=0 || y2_whole="$it"
				x2=$x2_whole ; y2=$y2_whole
			fi

## old method:
#			x1=`div1000 $(( 1000 * $xs1 + $(($xe1-$xs1)) * 1000 * $fr / $frames ))`
#			y1=`div1000 $(( 1000 * $ys1 + $(($ye1-$ys1)) * 1000 * $fr / $frames ))`
			[ "$x1" -eq 0 ] && x1="+0"
			[ "$y1" -eq 0 ] && y1="+0"
			[ "$x1" -gt 0 ] && x1="+$x1"
			[ "$y1" -gt 0 ] && y1="+$y1"
#			x2=`div1000 $(( 1000 * $xs2 + $(($xe2-$xs2)) * 1000 * $fr / $frames ))`
#			y2=`div1000 $(( 1000 * $ys2 + $(($ye2-$ys2)) * 1000 * $fr / $frames ))`
			[ "$x2" -eq 0 ] && x2="+0"
			[ "$y2" -eq 0 ] && y2="+0"
			[ "$x2" -gt 0 ] && x2="+$x2"
			[ "$y2" -gt 0 ] && y2="+$y2"

			progressbar $fr $frames '#'
			## optionally prepare interp image:
			if [ "$both" -eq 1 ] ; then
				if [ "$smp" -eq 1 ] ; then
				(composite -compose src-over -geometry "$x1""$y1" -type TrueColorMatte -depth 8 "$tmpdir/kb_prev_$dj.png" "$normal_bg" - | composite -compose src-over -geometry "$x2""$y2" -type TrueColorMatte -depth 8 "$tmpdir/kb_next_$dj.png" - "$tmpdir"/fade_$dj.ppm ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames ) &
				else
				composite -compose src-over -geometry "$x1""$y1" -type TrueColorMatte -depth 8 "$tmpdir/kb_prev_$dj.png" "$normal_bg" - | composite -compose src-over -geometry "$x2""$y2" -type TrueColorMatte -depth 8 "$tmpdir/kb_next_$dj.png" - "$tmpdir"/fade_$dj.ppm ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames
				fi
			elif [ "$previousslide_effect" == 'kenburns' ] || [ "$previousslide_effect" == 'scroll' ] ; then
				if [ "$smp" -eq 1 ] ; then
				(composite -compose src-over -geometry "$x1""$y1" -type TrueColorMatte -depth 8 "$tmpdir/kb_prev_$dj.png" "$normal_bg" - | composite -compose src-over -geometry "$x2""$y2" -type TrueColorMatte -depth 8 "$next_outfile" - "$tmpdir"/fade_$dj.ppm ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames ) &
				else
				composite -compose src-over -geometry "$x1""$y1" -type TrueColorMatte -depth 8 "$tmpdir/kb_prev_$dj.png" "$normal_bg" - | composite -compose src-over -geometry "$x2""$y2" -type TrueColorMatte -depth 8 "$next_outfile" - "$tmpdir"/fade_$dj.ppm ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames 
				fi
			elif [ "$nextslide_effect" == 'kenburns' ] || [ "$nextslide_effect" == 'scroll' ] ; then
				if [ "$smp" -eq 1 ] ; then
				(composite -compose src-over -geometry "$x1""$y1" -type TrueColorMatte -depth 8 "$last_outfile" "$normal_bg" - | composite -compose src-over -geometry "$x2""$y2" -type TrueColorMatte -depth 8 "$tmpdir/kb_next_$dj.png" - "$tmpdir"/fade_$dj.ppm ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames ) &
				else
				composite -compose src-over -geometry "$x1""$y1" -type TrueColorMatte -depth 8 "$last_outfile" "$normal_bg" - | composite -compose src-over -geometry "$x2""$y2" -type TrueColorMatte -depth 8 "$tmpdir/kb_next_$dj.png" - "$tmpdir"/fade_$dj.ppm ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames
				fi
			else  # flat files. Optionally do interp
				if [ "$smp" -eq 1 ] ; then
					(composite -compose src-over -geometry "$x1""$y1" -type TrueColorMatte -depth 8 "$last_outfile" "$normal_bg" - | composite -compose src-over -geometry "$x2""$y2" -type TrueColorMatte -depth 8 "$next_outfile" - "$tmpdir"/fade_$dj.ppm ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames ) &
				else
					(composite -compose src-over -geometry "$x1""$y1" -type TrueColorMatte -depth 8 "$last_outfile" "$normal_bg" - | composite -compose src-over -geometry "$x2""$y2" -type TrueColorMatte -depth 8 "$next_outfile" - "$tmpdir"/fade_$dj.ppm ; add_logo "$logo" fade_$dj.ppm "$logo_gravity" ; extracopies $fr $frames )
				fi
			fi  # end of pre/post options
		done
		waitforfiles "$tmpdir/fade" ppm $dj
		encode_fade
		finish_progressbar $fr $frames
		find "$tmpdir" -name "fade*.ppm" -type f -print0 | xargs -0 rm -f  # remove old files
		find "$tmpdir" -name "fade*.png" -type f -print0 | xargs -0 rm -f # remove old files
		find "$tmpdir" -name "kb_*" -type f -print0 | xargs -0 rm -f # remove old files
	elif [ "${image_file[$i]}" -eq 1 ] && [ "${effect1[$i]}" == 'crop' ] ; then  ## CROP
		myecho "[dvd-slideshow] $image_number/$imagefiles `truncate_filename $file` `hms ${duration[$i]}`"
		myecho "[dvd-slideshow] Crop ${effect1_params[$i]}"
		[ -n "${subtitle[$i]}" ] && myecho "[dvd-slideshow] Subtitle""= ${subtitle[$i]}"
		if [ "$first_image" == 1 ] ; then
			first_image=0
			hilight_image="${image[$i]}"
		fi

		# calculate actual frames rendered:
		previous_transition_increment="`previousTransitionIncrement`"
		previous_duration="${duration[$i-$previous_transition_increment]}" # already in thousandths.
		previous_slide="${image[$i-$previous_transition_increment]}"
		next_transition_increment="`nextTransitionIncrement`"
		next_duration="${duration[$i+$next_transition_increment]}"  # duration in thousandths of sec
		next_slide="${image[$i+$next_transition_increment]}"
		[ -z "$previous_slide" ] && previous_slide=0
		[ -z "$next_slide" ] && next_slide=0
#		echo "duration=${duration[$i]}  previous_inc=$previous_transition_increment previous_slide=$previous_slide previous_duration=$previous_duration"
		if [ "$previous_slide" == 'crossfade' ] || [ "$previous_slide" == 'wipe' ] ; then
			# subtract 1/2 time from rendered time:
			rendered_time=$(( ${duration[$i]} - $previous_duration / 2 )) 
			old_rendered_time=$(( ${duration[$i]} + $previous_duration ))
		elif [ "$previous_slide" == 'fadein' ] ; then
			rendered_time=$(( ${duration[$i]} - $previous_duration )) 
			old_rendered_time=$(( ${duration[$i]} + $previous_duration ))
		else  # no previous fade
			rendered_time=${duration[$i]}
			old_rendered_time=$rendered_time
		fi
#		echo "duration=${duration[$i]}  next_transition_increment=$next_transition_increment next_slide=$next_slide next_duration=$next_duration"
		if [ "$next_slide" == 'crossfade' ] || [ "$next_slide" == 'wipe' ] ; then
			# subtract time from rendered time:
			rendered_time=$(( $rendered_time - $next_duration / 2 )) 
			old_rendered_time=$(( $rendered_time + $next_duration )) 
		elif [ "$next_slide" == 'fadeout' ] ; then
			rendered_time=$(( $rendered_time - $next_duration )) 
			old_rendered_time=$(( $rendered_time + $next_duration )) 
		else  # no next fade
			rendered_time=$rendered_time	
			old_rendered_time=$old_rendered_time
		fi
		set_end_frame_time $rendered_time
		rendered_frames="$frames_to_render"

		if [ "$rendered_frames" -le 0 ] ; then
			echo "[dvd-slideshow] WARNING: Frames rendered are less than 1!"
			echo "[dvd-slideshow] 	Either you specified a duration = 0 "
			echo "[dvd-slideshow] 	or the fade time(s) are longer than the slide time."
			echo "[dvd-slideshow] 	!! This timing changed in dvd-slideshow 0.8.0."
			echo "[dvd-slideshow] 	!! so now the fades get applied on top of the slides"
			echo "[dvd-slideshow] 	!! and thus fades do not add time to the slideshow."
			echo "[dvd-slideshow] 	MODIFYING SLIDE TIME to $(hms $old_rendered_time)"
			set_end_frame_time $old_rendered_time
			rendered_frames="$frames_to_render"
		fi

		## now the slide may already exist if we had a fadein or crossfade before
		if [ ! -f "$tmpdir/slide_$i.ppm" ] || [ "$subtitle_type" == 'render' ] ; then 
			window=`echo "${effect1_params[$i]}" | awk -F';' '{print $1";"$2}'`
			parse_window "$window" "$file"
			mycrop  # takes the parameters from <parse_window> and returns: 
			[ $debug -ge 0 ] && myecho "[dvd-slideshow] mycrop $c_width"x"$c_height"+"$xc0"+"$yc0 composite" +"$xci"+$yci
			#[ c_width c_height xc0 yc0 xci yci ] = crop_parameters(image_width image_height frame_width frame_height x0 y0 x1 y1 xi yi)
			crop_parameters  # takes the parameters from <parse_window> and returns: 
			[ $debug -ge 0 ] && myecho "[dvd-slideshow] crop_parameters $c_width"x"$c_height"+"$xc0"+"$yc0 composite" +"$xci"+$yci
			## now, do the actual crop:
#			echo convert "${file}" -filter $filtermethod -resize "$sq_to_dvd_pixels" -crop "$c_width"x"$c_height+$xc0+$yc0" +repage -resize "$frame_width"x"$frame_height" 
#			echo composite -compose src-over -geometry "+$(( $xci + $frame_border ))+$(( $yci + $frame_border ))" -type TrueColorMatte -depth 8 - "$normal_bg" "$tmpdir/slide_$i.ppm"
#			convert "${file}" -filter $filtermethod -resize "$sq_to_dvd_pixels" "$outdir"/resized.jpg ; identify "$outdir"/resized.jpg
#			convert "$outdir"/resized.jpg -crop "$c_width"x"$c_height+$xc0+$yc0" +repage "$outdir"/cropped.jpg ; identify "$outdir"/cropped.jpg
#			convert "$outdir"/cropped.jpg -resize "$frame_width"x"$frame_height" -type TrueColorMatte -depth 8 "$outdir"/resize2.jpg ; identify "$outdir"/resize2.jpg
#			composite -compose src-over -geometry "+$(( $xci + $frame_border ))+$(( $yci + $frame_border ))" -type TrueColorMatte -depth 8 "$outdir"/resize2.jpg "$normal_bg" "$outdir"/composited.jpg
			convert "${file}" -filter $filtermethod -resize "$sq_to_dvd_pixels" -crop "$c_width"x"$c_height+$xc0+$yc0" +repage -resize "$frame_width"x"$frame_height" -type TrueColorMatte -depth 8 miff:- | composite -compose src-over -geometry "+$(( $xci + $frame_border ))+$(( $yci + $frame_border ))" -type TrueColorMatte -depth 8 - "$normal_bg" "$tmpdir/slide_$i.ppm"
			subtitle1[$i]="$( echo "${subtitle[$i]}" | awk -F';' '{print $1}' )"
			if [ -n "${subtitle1[$i]}" -a "$subtitle_type" == 'render' ] ; then
				subtitle "${subtitle1[$i]}" $i transparent # creates subtitle_$i.png
				composite -compose src-over -type TrueColorMatte -depth 8 "$tmpdir"/subtitle_"$i".png "$tmpdir"/slide_"$i".ppm "$tmpdir"/slide_"$i".ppm
			fi
		fi
		if [ -n "$logo" ] ; then  # optionally add logo layer
			add_logo "$logo" slide_$i.ppm "$logo_gravity"
		fi
		encode "$tmpdir/slide_$i.ppm" $rendered_frames
		image_number=$(( $image_number + 1 ))
		[ "$manual_chapter_markers" -eq 0 ] && write_chap=1
		find "$tmpdir" -name "fade*.ppm" -type f -print0 | xargs -0 rm -f  # remove old files
		find "$tmpdir" -name "kb_*" -type f -print0 | xargs -0 rm -f  # remove old files
		[ $debug -ge 1 ] &&  myecho "[dvd-slideshow] end_frame_number=$slide_end_frame end_time=$slide_end_hms rendered_frames=$rendered_frames"
                myecho "[dvd-slideshow]############################################################"
	elif [ "${effect1[$i]}" == 'kenburns' ] ; then  # KENBURNS
		## Kenburns effect from starting point to ending point
		# x0,y0 is the top left corner of the image
		# x1,y1 is the bottom right corner of the image
		# xs0,ys1 is the starting point for the top left corner, etc
		# xe1,ye1 is the ending point for the bottom right corner
		# textfile format is:  
		# file:duration:comment:kenburns:xs0,ys0;xs1,ys1;xe0,ye0;xe1,ye1;startangle,endangle
		myecho "[dvd-slideshow] $image_number/$imagefiles `truncate_filename $file` `hms ${duration[$i]}`"
		myecho "[dvd-slideshow] Kenburns ${effect1_params[$i]}"
		[ -n "${subtitle[$i]}" ] && myecho "[dvd-slideshow] Subtitle""= ${subtitle[$i]}"
		if [ "$first_image" == 1 ] ; then
			first_image=0
			hilight_image="${image[$i]}"
		fi

		window_start=`echo "${effect1_params[$i]}" | awk -F';' '{print $1";"$2}'`
		window_end=`echo "${effect1_params[$i]}" | awk -F';' '{print $3";"$4}'`

		previous_transition_increment="`previousTransitionIncrement`"
		previous_slide="${image[$i-$previous_transition_increment]}"
		if [ "$previous_transition_increment" -ne 0 ] ; then
			previous_duration="${duration[$i-$previous_transition_increment]}" # already in thousandths.
			previous_frames=`div1000 $(( $frames_per_ms * $previous_duration / 1000 ))` 
		fi
		next_transition_increment="`nextTransitionIncrement`"
		next_slide="${image[$i+$next_transition_increment]}"
		if [ "$next_transition_increment" -ne 0 ] ; then
			next_duration=${duration[$i+$next_transition_increment]}  # duration in thousandths of sec
			next_frames=$( duration2frames $next_duration )  # frames for next slide
		fi

		[ -z "$previous_slide" ] && previous_slide=0
		[ -z "$next_slide" ] && next_slide=0
#		echo "duration=${duration[$i]}  previous_inc=$previous_transition_increment previous_slide=$previous_slide previous_duration=$previous_duration"
		if [ "$previous_slide" == 'crossfade' ] || [ "$previous_slide" == 'wipe' ] ; then
			# subtract 1/2 time from rendered time:
			rendered_time=$(( ${duration[$i]} - $previous_duration / 2 )) 
			old_rendered_time=$(( ${duration[$i]} + $previous_duration ))
		elif [ "$previous_slide" == 'fadein' ] ; then
			rendered_time=$(( ${duration[$i]} - $previous_duration )) 
			old_rendered_time=$(( ${duration[$i]} + $previous_duration ))
		else  # no previous fade
			rendered_time=${duration[$i]}
			old_rendered_time=$rendered_time
		fi
#		echo "duration=${duration[$i]}  next_transition_increment=$next_transition_increment next_slide=$next_slide next_duration=$next_duration"
		if [ "$next_slide" == 'crossfade' ] || [ "$next_slide" == 'wipe' ] ; then
			# subtract time from rendered time:
			rendered_time=$(( $rendered_time - $next_duration / 2 )) 
			old_rendered_time=$(( $rendered_time + $next_duration )) 
			# also need to adjust total time/frames in this effect
		elif [ "$next_slide" == 'fadeout' ] ; then
			rendered_time=$(( $rendered_time - $next_duration )) 
			old_rendered_time=$(( $rendered_time + $next_duration )) 
		else  # no next fade
			rendered_time=$rendered_time	
			old_rendered_time=$old_rendered_time
		fi
		set_end_frame_time $rendered_time
		rendered_frames="$frames_to_render"
		if [ "$rendered_frames" -le 0 ] ; then
			echo "[dvd-slideshow] WARNING: Frames rendered are less than 1!"
			echo "[dvd-slideshow] 	Either you specified a duration = 0 "
			echo "[dvd-slideshow] 	or the fade time(s) are longer than the slide time."
			echo "[dvd-slideshow] 	!! This timing changed in dvd-slideshow 0.8.0."
			echo "[dvd-slideshow] 	!! so now the fades get applied on top of the slides"
			echo "[dvd-slideshow] 	!! and thus fades do not add time to the slideshow."
			echo "[dvd-slideshow] 	MODIFYING SLIDE TIME to $(hms $old_rendered_time)"
			set_end_frame_time $old_rendered_time
			rendered_frames="$frames_to_render"
		fi

		[ $debug -ge 1 ] &&  myecho "[dvd-slideshow] end_frame_number=$slide_end_frame end_time=$slide_end_hms"
		# kenburns syntax:
		# Kenburns $window_start $window_end $file $total_frames $startframe $lastframe bg [$char]
		if [ "$previous_transition_increment" -ne 0 ] && [ "$next_transition_increment" -ne 0 ] ; then
			kenburns "$window_start" "$window_end" "$file" "${frames_extended[$i]}" "$(( $previous_frames + 1 ))" "$(( $previous_frames + $frames_to_render ))" "$normal_bg"

		elif [ "$previous_transition_increment" -ne 0 ] ; then
			#kenburns "$window_start" "$window_end" "$file" "${frames_extended[$i]}" "$(( $previous_frames + 1 ))" "$frames" 
			kenburns "$window_start" "$window_end" "$file" "${frames_extended[$i]}" "$(( $previous_frames + 1 ))" "$(( $previous_frames + $frames_to_render ))" 
		elif [ "$next_transition_increment" -ne 0 ] ; then
			kenburns "$window_start" "$window_end" "$file" "${frames_extended[$i]}" 1 "$(( $frames_to_render ))"
		else
			kenburns "$window_start" "$window_end" "$file" "${frames_extended[$i]}" 1 "$frames" "#"
		fi
		encode_fade
		## just in case we want to fade out or crossfade, we need to save the last image:
		mv "$tmpdir/fade_$dj.ppm" "$tmpdir/slide_$i.ppm"
		find "$tmpdir" -name "fade*.ppm" -type f -print0 | xargs -0 rm -f  # remove old files
		find "$tmpdir" -name "fade*.png" -type f -print0 | xargs -0 rm -f # remove old files
		image_number=$(( $image_number + 1 ))
	elif [ "${effect1[$i]}" == 'scroll' ] ; then # SCROLL
		# textfile format is:  
		# file:duration:comment:scrollright
		myecho "[dvd-slideshow] $image_number/$imagefiles `truncate_filename $file` `hms ${duration[$i]}`"
		myecho "[dvd-slideshow] Scroll ${effect1_params[$i]}"
		[ -n "${subtitle[$i]}" ] && myecho "[dvd-slideshow] Subtitle""= ${subtitle[$i]}"
		if [ "$first_image" == 1 ] ; then
			first_image=0
			hilight_image="${image[$i]}"
		fi
		direction="${effect1_params[$i]}"

		previous_transition_increment="`previousTransitionIncrement`"
		previous_slide="${image[$i-$previous_transition_increment]}"
		if [ "$previous_transition_increment" -ne 0 ] ; then
			previous_duration="${duration[$i-$previous_transition_increment]}" # already in thousandths.
			previous_frames=`div1000 $(( $frames_per_ms * $previous_duration / 1000 ))` 
		fi
		next_transition_increment="`nextTransitionIncrement`"
		next_slide="${image[$i+$next_transition_increment]}"
		if [ "$next_transition_increment" -ne 0 ] ; then
			next_duration=${duration[$i+$next_transition_increment]}  # duration in thousandths of sec
			next_frames=$( duration2frames $next_duration )  # frames for next slide
		fi
		[ -z "$previous_slide" ] && previous_slide=0
		[ -z "$next_slide" ] && next_slide=0
#		echo "duration=${duration[$i]}  previous_inc=$previous_transition_increment previous_slide=$previous_slide previous_duration=$previous_duration"
		if [ "$previous_slide" == 'crossfade' ] || [ "$previous_slide" == 'wipe' ] ; then
			# subtract 1/2 time from rendered time:
			rendered_time=$(( ${duration[$i]} - $previous_duration / 2 )) 
			old_rendered_time=$(( ${duration[$i]} + $previous_duration ))
		elif [ "$previous_slide" == 'fadein' ] ; then
			rendered_time=$(( ${duration[$i]} - $previous_duration )) 
			old_rendered_time=$(( ${duration[$i]} + $previous_duration ))
		else  # no previous fade
			rendered_time=${duration[$i]}
			old_rendered_time=$rendered_time
		fi
#		echo "duration=${duration[$i]}  next_transition_increment=$next_transition_increment next_slide=$next_slide next_duration=$next_duration"
		if [ "$next_slide" == 'crossfade' ] || [ "$next_slide" == 'wipe' ] ; then
			# subtract time from rendered time:
			rendered_time=$(( $rendered_time - $next_duration / 2 )) 
			old_rendered_time=$(( $rendered_time + $next_duration )) 
		elif [ "$next_slide" == 'fadeout' ] ; then
			rendered_time=$(( $rendered_time - $next_duration )) 
			old_rendered_time=$(( $rendered_time + $next_duration )) 
		else  # no next fade
			rendered_time=$rendered_time	
			old_rendered_time=$old_rendered_time
		fi
		set_end_frame_time $rendered_time
		rendered_frames="$frames_to_render"
#echo "rendered_time=$rendered_time"
#echo "rendered_frames=$rendered_frames"
#echo "previous_frames=$previous_frames"
#echo "next_frames=$next_frames"

		# scroll syntax is: 
		# scroll $direction $file $bg $total_frames [$startframe] [$lastframe] [$char]
		#
		if [ "$previous_transition_increment" -ne 0 ] && [ "$next_transition_increment" -ne 0 ] ; then
			scroll "$direction" "$file" "$normal_bg" "${frames_extended[$i]}" "$(( $previous_frames + 1 ))" "$(( $previous_frames + $rendered_frames ))"
		elif [ "$previous_transition_increment" -ne 0 ] ; then
			scroll "$direction" "$file" "$normal_bg" "${frames_extended[$i]}" "$(( $previous_frames + 1 ))" "$frames" '#'
		elif [ "$next_transition_increment" -ne 0 ] ; then
			scroll "$direction" "$file" "$normal_bg" "${frames_extended[$i]}" 1 "$(( $rendered_frames ))" '#'
		else
			scroll "$direction" "$file" "$normal_bg" "$frames" 1 "$frames" "#"
		fi
		if [ "$rendered_frames" -le 0 ] ; then
			echo "[dvd-slideshow] ERROR: Frames rendered are less than 1!"
			echo "[dvd-slideshow] 	Either you specified a duration = 0 "
			echo "[dvd-slideshow] 	or the fade time(s) are longer than the slide time."
			cleanup; exit 0
		fi
#		[ $debug -ge 1 ] &&  myecho "[dvd-slideshow] end_frame_number=$slide_end_frame end_time=$slide_end_hms"
		encode_fade
#		finish_progressbar $fr $frames
		## just in case we want to fade out or crossfade, we need to save the last image:
		mv "$tmpdir/fade_$dj.ppm" "$tmpdir/slide_$i.ppm"
		find "$tmpdir" -name "fade*.ppm" -type f -print0 | xargs -0 rm -f  # remove old files
		find "$tmpdir" -name "fade*.png" -type f -print0 | xargs -0 rm -f # remove old files
		image_number=$(( $image_number + 1 ))
		interp=0
	elif [ "$file" == 'black' ] ; then  ###############################################
		## use plain black background with no picture
		## phase out "black" tag. Use background:::black instead
		myecho "[dvd-slideshow] ERROR: use of black is depreciated. Use the syntax:"
		myecho "[dvd-slideshow]        background:duration:subtitle:black   instead of:"
		myecho "[dvd-slideshow]        black:duration:subtitle            <depreciated>"
		cleanup; exit 1
	elif [ "$file" == 'testslide' ] ; then  # TESTSLIDE
		## Create a slide of size 720x480 with yellow lines
		convert -size 720x480 xc:gray -fill yellow -draw "line 0,0,719,0 text 110,0 \"0\" line 0,60,719,60 text 110,60 \"60\" line 0,120,719,120 text 110,120 \"120\" line 0,180,719,180 text 110,180 \"180\" line 0,240,719,240 text 110,240 \"240\" line 0,300,719,300 text 110,300 \"300\" line 0,360,719,360 text 110,360 \"360\" line 0,420,719,420 text 110,420 \"420\" line 0,479,719,479 text 110,479 \"479\" " -fill orange -draw "line 0,0,0,480 text 0,180 \"0\" line 90,0,90,480 text 90,180 \"90\" line 180,0,180,480 text 180,180 \"180\" line 270,0,270,480 text 270,180 \"270\" line 360,0,360,480 text 360,180 \"360\" line 450,0,450,480 text 450,180 \"450\" line 540,0,540,480 text 540,180 \"540\" line 630,0,630,480 text 630,180 \"630\" line 719,0,719,480 text 719,180 \"719\" " -type TrueColorMatte -depth 8 -filter $filtermethod -resize "$sq_to_dvd_pixels" -resize "$dvd_width"x"$dvd_height" -quality 100 "$tmpdir/slide_$i.ppm"
		set_end_frame_time ${duration[$i]}
		[ $debug -ge 1 ] &&  myecho "[dvd-slideshow] end_frame_number=$slide_end_frame end_time=$slide_end_hms"
		myecho "[dvd-slideshow]############################################################"
	elif [ "$file" == 'exit' ] ; then  # EXIT
		## stop here and finish .vob
		set_end_frame_time 0 
		[ $debug -ge 1 ] &&  myecho "[dvd-slideshow] end_frame_number=$slide_end_frame end_time=$slide_end_hms"
		break
	elif [ "$file" == 'background' ] ; then  # BACKGROUND
		bg="${effect1[$i]}"
		if [ -n "$bg" ] ; then
			background "$bg"   # calls the background image subroutine
		fi
		if [ "${duration[$i]}" != 0 ] ; then  
			myecho "[dvd-slideshow] $file `hms ${duration[$i]}`"
			## user wants to actually display background for a given time
			myecho "[dvd-slideshow] Displaying background $(truncate_filename "$bgfile")"
			cp "$tmpdir/slideshow_background.ppm" "$tmpdir/slide_$i.ppm"
			if [ "${subtitle[$i]}" == 'black' ] ; then
				myecho "[dvd-slideshow] WARNING: Subtitle=${subtitle[$i]}. Are you sure?"
			elif [ -n "${subtitle[$i]}" ] ; then
				myecho "[dvd-slideshow] Subtitle=${subtitle[$i]}"
			fi
			subtitle1[$i]="$( echo "${subtitle[$i]}" | awk -F';' '{print $1}' )"
#			myecho "[dvd-slideshow] Track ${audio_track[$i]} audiofile $audio_index $( truncate_filename "$file")"
			if [ -n "$logo" ] ; then  # optionally add logo layer
				add_logo "$logo" slide_$i.ppm "$logo_gravity"
			fi
#			echo "subtitle1=${subtitle1[$i]}"
			if [ -n "${subtitle1[$i]}" -a "$subtitle_type" == 'render' ] ; then
				subtitle "${subtitle1[$i]}" $i transparent # creates subtitle_$i.png
				composite -compose src-over -type TrueColorMatte -depth 8 "$tmpdir"/subtitle_"$i".png "$tmpdir"/slide_"$i".ppm "$tmpdir"/slide_"$i".ppm
			fi
			encode "$tmpdir/slide_$i.ppm" "$frames"
		fi
		set_end_frame_time ${duration[$i]}  
		[ $debug -ge 1 ] &&  myecho "[dvd-slideshow] end_frame_number=$slide_end_frame end_time=$slide_end_hms"
		myecho "[dvd-slideshow]############################################################"
#identify "$tmpdir/slide_$i.ppm"
	elif [ "`echo $file | tr -d \[:blank:\]`" == 'chapter' ] ; then   # CHAPTER
		## create a chapter marker at this time, but don't do anything else...
		manual_chapter_markers=1  # allow manual chapter markers
		write_chap=1
		previous_transition_increment="`previousTransitionIncrement`"
		previous_slide="${image[$i-$previous_transition_increment]}"
		if [ "$previous_transition_increment" -ne 0 ] ; then
			previous_duration="${duration[$i-$previous_transition_increment]}"
			if [ "$previous_slide" == 'crossfade' ] || [ "$previous_slide" == 'wipe' ] ; then
				# subtract time from audio time:
				#chapter_time=$(( $slide_end_time - $previous_duration / 2 )) 
				chapter_time=$slide_end_time	
			elif [ "$previous_slide" == 'fadein' ] ; then
				# set chapter marker at beginning of fadein:
				#chapter_time=$(( $slide_end_time - $previous_duration )) 
				chapter_time=$slide_end_time	
			else  # no previous fade
				chapter_time=$slide_end_time	
			fi
		else  # no previous transition. no need to adjust timing: 
			chapter_time=$slide_end_time	
		fi
		subtitle[$i]=''  # set subtitle to nothing so we don't get a subtitle
		myecho "[dvd-slideshow] Setting chapter marker at $( hms $chapter_time)"
#		myecho "[dvd-slideshow] Setting chapter marker at $slide_end_hms"
		set_end_frame_time 0
		myecho "[dvd-slideshow]############################################################"
	elif [ "`echo $file | tr -d \[:blank:\]`" == 'highlight' ] ; then   # HIGHLIGHT
		## use next image for this slideshow highlight image
		## the next image name will be embedded in the output .xml file
		first_image=1
		subtitle[$i]=''  # set subtitle to nothing so we don't get a subtitle
		myecho "[dvd-slideshow] Using next image for slideshow highlight"
		set_end_frame_time 0
		myecho "[dvd-slideshow]############################################################"
	elif [ "${audio_file[$i]}" -eq 1 ] ; then  # AUDIO FILE
		if [ "${audio_track[$i]}" -eq 1 ] ; then
			audio_1[$i_audio]="${file}"
			audio1_effect1[$i_audio]="${effect1[$i]}"
			audio1_effect1_params[$i_audio]="${effect1_params[$i]}"
			audio1_effect2[$i_audio]="${effect2[$i]}"
			audio1_effect2_params[$i_audio]="${effect2_params[$i]}"
			audio_index="$i_audio"
			myecho "[dvd-slideshow] Track ${audio_track[$i]} audiofile $audio_index $( truncate_filename "$file")"
			audio_index_padded=`addzeros "$i_audio"`
			i_audio=$(( $i_audio + 1 ))
		elif [ "${audio_track[$i]}" -eq 2 ] ; then
			audio_2[$j_audio]="${file}"
			audio2_effect1[$j_audio]="${effect1[$i]}"
			audio2_effect1_params[$j_audio]="${effect1_params[$i]}"
			audio2_effect2[$j_audio]="${effect2[$i]}"
			audio2_effect2_params[$j_audio]="${effect2_params[$i]}"
			audio_index="$j_audio"
			myecho "[dvd-slideshow] Track ${audio_track[$i]} audiofile $audio_index $( truncate_filename "$file")"
			audio_index_padded=`addzeros "$j_audio"`
			j_audio=$(( $j_audio + 1 ))
		else
			myecho "[dvd-slideshow] ERROR: Bad audio track number."
			myecho "[dvd-slideshow]        only use audio track 1 or 2"
			cleanup; exit 1
		fi
		track="${audio_track[$i]}"
		suffix=`echo "$file" | awk -F. '{print tolower($NF)}'`
		# let's check for the next slide and see if the duration is "audio"
		increment=`nextslideincrement`
		next_duration="${duration[$i+$increment]}"
#		[ "$next_duration" == 'audio' ] && audiosmp=0 || audiosmp=$smp
#		echo "$tmpdir/audio$track"_"$audio_index_padded.wav"
		if [ ! -f "$tmpdir/audio$track"_"$audio_index_padded.wav" ] ; then
			if [ "$suffix" == "mp3" ] ; then
				myecho "[dvd-slideshow] decoding mp3 audio file... be patient..."
				if [ "$audiosmp" -eq 1 ] ; then
					avconv -threads "$cores" -i "$file" -y -vn -ab "$audio_bitrate"k -f wav -ar $audio_sample_rate -ac 2 "$tmpdir/audio$track"_"$audio_index_padded.wav" >> "$avconv_out" 2>&1 &
				else
					avconv -threads "$cores" -i "$file" -y -vn -ab "$audio_bitrate"k -f wav -ar $audio_sample_rate -ac 2 "$tmpdir/audio$track"_"$audio_index_padded.wav" >> "$avconv_out" 2>&1
				fi
			elif [ "$suffix" == "m4a" ] || [ "$suffix" == "aac" ] ; then
				if [ "$audiosmp" -eq 1 ] ; then
				faad -o "$tmpdir/audio$track"_"$audio_index_padded.wav" "$file" &
				else
				faad -o "$tmpdir/audio$track"_"$audio_index_padded.wav" "$file" 
				fi
			elif [ "$suffix" == "ogg" ] ; then
				myecho "[dvd-slideshow] decoding ogg audio... be patient."
				if [ "$audiosmp" -eq 1 ] ; then
					oggdec --quiet -o "$tmpdir/audio$track"_"$audio_index_padded.wav" "${file}" &
				else
					oggdec --quiet -o "$tmpdir/audio$track"_"$audio_index_padded.wav" "${file}"
				fi
			elif [ "$suffix" == "wav" ] ; then
				myecho "[dvd-slideshow] processing wav audio... we will splice it later."
				cp "${file}" "$tmpdir/audio$track"_"$audio_index_padded.wav"
			elif [ "$file" == 'silence' ]; then
				myecho "[dvd-slideshow] creating silent audio track... we will splice it later."
				if [ "$audiosmp" -eq 1 ] ; then
					sox -t raw $sox_int $sox_word -c 2 -r $audio_sample_rate /dev/zero -t wav -c 2 -r $audio_sample_rate "$tmpdir/audio$track"_"$audio_index_padded.wav" trim 0 1 &
				else
					sox -t raw $sox_int $sox_word -c 2 -r $audio_sample_rate /dev/zero -t wav -c 2 -r $audio_sample_rate "$tmpdir/audio$track"_"$audio_index_padded.wav" trim 0 1
				fi
			else
				myecho "[dvd-slideshow] ERROR:  Unknown audio file format. Must be mp3, ogg, mp4/aac, wav, or silence"
			fi
		fi
		## now set the starting and ending point of this audio track:
#		myecho "audio_track=${audio_track[$i]} "
		# ignore time added by fades if there are any between the last audio file end
		# and the start of the next track!
		previous_transition_increment="`previousTransitionIncrement`"
		previous_slide="${image[$i-$previous_transition_increment]}"
		if [ "$previous_transition_increment" -ne 0 ] ; then
			previous_duration="${duration[$i-$previous_transition_increment]}" # already in thousandths.
			if [ "$previous_slide" == 'crossfade' ] || [ "$previous_slide" == 'wipe' ] ; then
				# subtract time from audio time:
				audio_time=$(( $slide_end_time - $previous_duration / 2 )) 
			elif [ "$previous_slide" == 'fadein' ] ; then
				audio_time=$(( $slide_end_time - $previous_duration )) 
			else  # no previous fade
				audio_time=$slide_end_time	
			fi
		else  # no previous transition. no need to adjust timing: 
			audio_time=$slide_end_time	
		fi
#		myecho "slide_end_time=$slide_end_time audio_time=$audio_time"
		if [ "${audio_track[$i]}" -eq 1 ] ; then
			audio1_start[$audio_index]="$slide_start_time"   # in ms
			## set ending point of the audio track:
			if [ "$audio_index" -gt 0 ] ; then # not first audio track
#				audio1_end[$(($audio_index-1))]="$slide_end_time"   # in ms from last slide
				audio1_end[$(($audio_index-1))]="$audio_time"   # in ms from last slide
				myecho "[dvd-slideshow] Set end time for audio track 1 file $audio_index to `hms $audio_time`"
			else # set audio end to zero for now...
				audio1_end[$audio_index]=0   # in ms from last slide
			fi
		elif [ "${audio_track[$i]}" -eq 2 ] ; then
			audio2_start[$audio_index]="$slide_start_time"   # in ms
			## set ending point of the audio track:
			if [ "$audio_index" -gt 0 ] ; then
#				audio2_end[$(($audio_index-1))]="$slide_end_time"   # in ms from last slide
				audio2_end[$(($audio_index-1))]="$audio_time"   # in ms from last slide
				myecho "[dvd-slideshow] Set end time for audio track 2 file $audio_index to `hms $slide_end_time`"
			else # set audio end to zero for now...
				audio2_end[$audio_index]=0   # in ms from last slide
			fi
		fi
		subtitle[$i]=''  # set subtitle to nothing so we don't get a subtitle
		set_end_frame_time 0
		if [ "$debug" -gt 0 ] || [ "$quiet" == 0 ] ; then
		myecho "[dvd-slideshow]############################################################"
		fi
	else  
		myecho "[dvd-slideshow] Unrecognized or malformed line in your input file:"
		myecho "[dvd-slideshow] $file. effect=${effect1[$i]} effect_params=${effect1_params[$i]}"
		myecho "Fix it and try again."
		cleanup; exit 1
	fi
	
	thumb_width=$(( ( $dvd_width - 100 ) / 6 ))
	thumb_height=$(( ( $dvd_height - 100 ) / 4 ))
	## setup the chapter markers at the start of each picture:
	if [ "$write_chap" -eq 1 ] ; then   # and chapter-select =1 
		if [ -z "$chapter_time" ] ; then
			chapter_marker="$slide_start_time"  # old method works with no manual markers
		else
			chapter_marker="$chapter_time" 
			chapter_time='' # reset it to nothing
		fi
		chaps[$this_chap]=`hms "$chapter_marker"`
		## now make a tiny thumbnail for the menu?:
		thumbs[$this_chap]="$tmpdir/slide_"$i"_thumb.ppm"
#		convert "$tmpdir/slide_$i.ppm" -depth 8 -resize "$thumb_width"x"$thumb_height" "$tmpdir"/slide_$i"_thumb.ppm"
		this_chap=$(($this_chap + 1))
		write_chap=0
	fi

	## now, create the xml file to pass to spumux
	if [ "$spumux_header" -eq 0 ]; then  # only do once on first pass:
		spumux_header=1
		echo '<subpictures format="'$ntsc_or_pal'">' > "$tmpdir/$slideshow_name".spumux
		echo '	<stream>' >> "$tmpdir/$slideshow_name".spumux
		continuous_subtitle_flag=0
		echo '<subpictures format="'$ntsc_or_pal'">' > "$tmpdir/$slideshow_name".spumux2
		echo '	<stream>' >> "$tmpdir/$slideshow_name".spumux2
	fi	

	## Subtitles ########################################################
	## add the subtitle track if it exists:  SUBTITLE
	if [ -n "${subtitle[$i]}" ] && [ "$subtitle_type" != 'render' ] ; then
		## move all the pixel-related stuff into a function, but keep timing stuff here...
#		echo "$i subtitle_rendered=${subtitle[$i]}"
		# look for semicolon, indicating multiple subtitle tracks:
		subtitle1[$i]="$( echo "${subtitle[$i]}" | awk -F';' '{print $1}' )"
		subtitle2[$i]="$( echo "${subtitle[$i]}" | awk -F';' '{print $2}' )"
		[ $debug -gt 1 ] && myecho "[dvd-slideshow] subtitle1=${subtitle1[$i]}"
		[ $debug -gt 1 ] && myecho "[dvd-slideshow] subtitle2=${subtitle2[$i]}"
		if [ -n "${subtitle2[$i]}" ] ; then
			has_subtitles2=1
			subtitle "${subtitle2[$i]}" $i  # just creates the .png file for overlay
			mv "$tmpdir"/subtitle_$i.png "$tmpdir"/subtitle2_$i.png
		fi
		if [ -n "${subtitle1[$i]}" ] ; then
			has_subtitles=1
			subtitle "${subtitle1[$i]}" $i  # just creates the .png file for overlay
		fi
	fi

	## let's assume the subtitle stays on the whole duration of the slide?
	subtitle_start=`hms "$slide_start_time"`
	subtitle_end=`hms "$slide_end_time"`
	[ $debug -gt 1 ] && myecho "[dvd-slideshow] subtitle_start=$subtitle_start subtitle_end=$subtitle_end"

        ### Fix by AW. Check to see if last subtitle was the same as this one!
	## if so, then display it continuously:
	if [ "$i" -eq 0 ] ; then
		# first line. check for subtitle?
	        if [ -n "${subtitle1[$i]}" ] ; then
			write_last_subtitle=1
			continuous_subtitle_start="$subtitle_start"
			continuous_subtitle_end="$subtitle_end"  # update end point every time
		fi
	        if [ -n "${subtitle2[$i]}" ] ; then
			write_last_subtitle2=1
			continuous_subtitle_start2="$subtitle_start"
			continuous_subtitle_end2="$subtitle_end"  # update end point every time
		fi
	elif [ "$i" -gt 0 ] ; then
		# subtitle track 1:
		if [ -n "${subtitle1[$i]}" -a -z "${subtitle1[$(($i-1))]}" ] ; then
			# Current subtitle is nonzero, and previous subtitle is empty:
			# Just update values, don't write out yet!
			write_last_subtitle=1
			continuous_subtitle_start="$subtitle_start"
		elif [ -z "${subtitle1[$i]}" -a -z "${subtitle1[$(($i-1))]}" ] ; then
			# no subtitles. don't do anything.
			write_last_subtitle=0
			continuous_subtitle_start="$subtitle_start"
		elif [ -z "${subtitle1[$i]}" -a -n "${subtitle1[$(($i-1))]}" ] ; then
			# Current subtitle is empty, and previous subtitle is nonzero:
			# write out subtitle
			write_last_subtitle=0
			echo '		<spu start="'$continuous_subtitle_start'" end="'$continuous_subtitle_end'" transparent="'$transparent_color'" image="'$tmpdir/subtitle_$(($i-1)).png'">' >> "$tmpdir/$slideshow_name".spumux
			echo '		</spu>' >> "$tmpdir/$slideshow_name".spumux
			echo '		' >> "$tmpdir/$slideshow_name".spumux
			continuous_subtitle_start="$subtitle_start"
	        elif [ "${subtitle1[$i]}" != "${subtitle1[$(($i-1))]}" ] ; then
			## subtitles different, but both not empty:
			# write out results
#			myecho "subtitles different i=${subtitle1[$i]} i-1=${subtitle1[$(($i-1))]}"
			write_last_subtitle=1
			echo '		<spu start="'$continuous_subtitle_start'" end="'$continuous_subtitle_end'" transparent="'$transparent_color'" image="'$tmpdir/subtitle_$(($i-1)).png'">' >> "$tmpdir/$slideshow_name".spumux
			echo '		</spu>' >> "$tmpdir/$slideshow_name".spumux
			echo '		' >> "$tmpdir/$slideshow_name".spumux
			# set new subtitle starting point:
			continuous_subtitle_start="$subtitle_start"
		else
			# subtitles are the same. Don't write it out yet!
			# save the continuous_subtitle_end variable until done...
			if [ -n "${subtitle1[$i]}" ] ; then
				write_last_subtitle=1
				# subtitles are the same AND the current one is not empty
			fi
		fi
		continuous_subtitle_end="$subtitle_end"  # update end point every time

		# subtitle track 2:
		if [ -n "${subtitle2[$i]}" -a -z "${subtitle2[$(($i-1))]}" ] ; then
			# Current subtitle is nonzero, and previous subtitle is empty:
			# Just update values, don't write out yet!
			write_last_subtitle2=1
			continuous_subtitle_start2="$subtitle_start"
		elif [ -z "${subtitle2[$i]}" -a -z "${subtitle2[$(($i-1))]}" ] ; then
			# no subtitles. don't do anything.
			write_last_subtitle2=0
			continuous_subtitle_start2="$subtitle_start"
		elif [ -z "${subtitle2[$i]}" -a -n "${subtitle2[$(($i-1))]}" ] ; then
			# Current subtitle is empty, and previous subtitle is nonzero:
			# write out subtitle
			write_last_subtitle2=0
			echo '		<spu start="'$continuous_subtitle_start2'" end="'$continuous_subtitle_end2'" transparent="'$transparent_color'" image="'$tmpdir/subtitle_$(($i-1)).png'">' >> "$tmpdir/$slideshow_name".spumux2
			echo '		</spu>' >> "$tmpdir/$slideshow_name".spumux2
			echo '		' >> "$tmpdir/$slideshow_name".spumux2
			continuous_subtitle_start2="$subtitle_start"
	        elif [ "${subtitle2[$i]}" != "${subtitle2[$(($i-1))]}" ] ; then
			## subtitles different, but both not empty:
			# write out results
#			myecho "subtitles different i=${subtitle2[$i]} i-1=${subtitle2[$(($i-1))]}"
			write_last_subtitle2=1
			echo '		<spu start="'$continuous_subtitle_start2'" end="'$continuous_subtitle_end2'" transparent="'$transparent_color'" image="'$tmpdir/subtitle_$(($i-1)).png'">' >> "$tmpdir/$slideshow_name".spumux2
			echo '		</spu>' >> "$tmpdir/$slideshow_name".spumux2
			echo '		' >> "$tmpdir/$slideshow_name".spumux2
			# set new subtitle starting point:
			continuous_subtitle_start2="$subtitle_start"
		else
			# subtitles are the same. Don't write it out yet!
			# save the continuous_subtitle_end2 variable until done...
			if [ -n "${subtitle2[$i]}" ] ; then
				write_last_subtitle2=1
				# subtitles are the same AND the current one is not empty
			fi
		fi
		continuous_subtitle_end2="$subtitle_end"  # update end point every time
	fi

	let i=$i+1
done

#######################################################################
####### End of loop over each line of input .txt file

if [ -f "$tmpdir/$slideshow_name".spumux ] && [ "$subtitle_type" != 'render' ] ; then
	if [ "$write_last_subtitle" -eq 1 ] ; then
		# write out last subtitle:
		echo '		<spu start="'$continuous_subtitle_start'" end="'$continuous_subtitle_end'" transparent="'$transparent_color'" image="'$tmpdir/subtitle_$(($i-1)).png'">' >> "$tmpdir/$slideshow_name".spumux
		echo '		</spu>' >> "$tmpdir/$slideshow_name".spumux
		echo '		' >> "$tmpdir/$slideshow_name".spumux
	fi
	## write the bottom of the subpictures file:
	echo '	</stream>' >> "$tmpdir"/"$slideshow_name".spumux
	echo '</subpictures>' >> "$tmpdir"/"$slideshow_name".spumux
	# write out palette.rgb file:
#	echo '000000' > "$outdir"/palette.rgb
#	mycolor=$( echo $subtitle_color | awk -F'#' '{print $2}' )
#	if [ "${#mycolor}" -ne 6 ] ; then
#		# not a hex triple. Use default white
#		echo "[dvd-slideshow] Using white subtitle color..."
#		echo "ffffff" >> "$outdir"/palette.rgb
#	else
#		echo "$mycolor" >> "$outdir"/palette.rgb
#	fi
fi
if [ -f "$tmpdir/$slideshow_name".spumux2 ] && [ "$subtitle_type" != 'render' ] ; then
	if [ "$write_last_subtitle2" -eq 1 ] ; then
		# write out last subtitle:
		echo '		<spu start="'$continuous_subtitle_start2'" end="'$continuous_subtitle_end2'" transparent="'$transparent_color'" image="'$tmpdir/subtitle2_$(($i-1)).png'">' >> "$tmpdir/$slideshow_name".spumux2
		echo '		</spu>' >> "$tmpdir/$slideshow_name".spumux2
		echo '		' >> "$tmpdir/$slideshow_name".spumux2
	fi
	## write the bottom of the subpictures file:
	echo '	</stream>' >> "$tmpdir"/"$slideshow_name".spumux2
	echo '</subpictures>' >> "$tmpdir"/"$slideshow_name".spumux2
fi

############################### Wait for mpeg2enc to finish

# just close the fifo and wait for the encoder to finish
logecho "[dvd-slideshow] mpeg2enc/avconv process=$yuvpid"
logecho "[dvd-slideshow] output from ps:"
logecho "`ps $yuvpid`"
# close pipe to mpeg2enc
exec 9>&-  
myecho '[dvd-slideshow] waiting for encoder to finish...'
if [ "$( jobs -p | grep -F -q $yuvpid )" ] ; then
	wait $yuvpid >> "$outdir/$logfile" 2>&1
fi
yuvpid=0

## calculate total slideshow time:
#end_time=$(( $total_slideshow_frames * 1000 / $frames_per_ms ))  ## in seconds
end_time="$slide_end_time"
end_hms="$slide_end_hms"

############################################################################
# AUDIO section...
##########################################################################
myecho "[dvd-slideshow]#####################################"

# check that video worked, otherwise audio will hang for time=0:
if [ "$slide_end_time" -eq 0 ] ; then
	myecho "[dvd-slideshow] ERROR: audio duration = 0. Exiting..."	
	exit
fi

## now do the audio for this slideshow ##########################
let i=0
total_audio_length=0
commandline_audio=0
if [ -n "${passed_audio[0]}" ] ; then  ## command-line passed audio
	myecho "[dvd-slideshow] Processing command-line audio..."
	for file in "${passed_audio[@]}"; do
		i_padded=`addzeros $i`
		myecho "[dvd-slideshow] Working on track 1 audio file $(($i+1))"
		myecho "[dvd-slideshow] $file"
		fade_in_time="2000" # default 2 second
		fade_out_time="2000"
		fade_in_hms=`hms "$fade_in_time"`
		fade_out_hms=`hms "$fade_out_time"`
		track=1
		song_length=`wavlength "$tmpdir/audio1_$i_padded.wav"`
		if [ "$song_length" -lt "$(( $fade_in_time + $fade_out_time ))" ] ; then
			fade_in_time=$(( ( $song_length - 1 ) / 2 ))
			fade_out_time="$fade_in_time"
		fi
		song_length_hms=`hms "$song_length"`
		myecho "[dvd-slideshow] fade_in_time=$fade_in_hms fade_out_time=$fade_out_hms"
		total_audio_length="$(( $total_audio_length + $song_length ))"
		myecho "[dvd-slideshow] total_audio_length=`hms $total_audio_length`"
		sox -v 0.95 "$tmpdir/audio$track"_"$i_padded.wav" $sox_word $sox_int -c 2 -r $audio_sample_rate "$tmpdir/audio1_$i_padded.raw" fade t "$fade_in_hms" "$song_length_hms" "$fade_out_hms"
		let i=$i+1
		myecho "[dvd-slideshow] ###############"
	done
	i_padded=`addzeros $i`
	## check to make sure the audio spans the video time:
	if [ "$total_audio_length" -lt "$end_time" ] ; then
		# video is longer than audio. need to add silence to end.
		thetime_hms=`hms $(( $end_time - $total_audio_length + 1000 ))` #plus 10 so sox actually crops.
		myecho "[dvd-slideshow] Buffering end of audio file with silence for $thetime_hms"
		sox -t raw $sox_int $sox_word -c 2 -r $audio_sample_rate /dev/zero $sox_word $sox_int -c 2 -r $audio_sample_rate "$tmpdir/audio1_$i_padded.raw" trim 0 "$thetime_hms"
	fi
	
	## cat all the audio files together: 
	cat "$tmpdir"/audio1_????.raw | sox -t raw $sox_word $sox_int -c 2 -r $audio_sample_rate - "$tmpdir/audio1.wav"
	## fade out at end of video:
	sox "$tmpdir/audio1.wav" "$tmpdir/audio_out.wav" fade t 0 "$end_hms" "$fade_out_hms"
	mv "$tmpdir/audio_out.wav" "$tmpdir/audio1.wav"
	## mpeg2 audio:
	## AC3 audio may be more compatible:
	if [ "$ac3" -eq 1 ] && [ "$output_format" != 'flv' ] ; then
		checkforprog avconv
		myecho "[dvd-slideshow] Creating ac3 audio for $file..."
		avconv -threads "$cores" -i "$tmpdir/audio1.wav" -y -vn -ab "$audio_bitrate"k -acodec ac3 -vol "100" -ar $audio_sample_rate -ac 6 "$tmpdir/audio1.ac3" >> "$avconv_out" 2>&1
		if [ $? -ne 0 ] ; then
			## avconv errored
			myecho "[dvd-slideshow] ERROR during avconv execution!"
			myecho "[dvd-slideshow] see $outdir/$logfile for details"
			cleanup; exit 1
		fi
	else
		## twolame is way faster! (3x in my test)
		it=`which twolame 2> /dev/null`
		if [ -n "$it" ] ; then
			twolame_version=`twolame -h | head -n 4 | grep version | awk '{ print $3 }'`
			myecho "[dvd-slideshow] using twolame $twolame_version..."
			if [ "$twolame_version" == '0.2m' ] ; then
				twolame -s $audio_sample_rate -b $audio_bitrate "$tmpdir/audio1.wav" "$tmpdir/audio1.mp2" >> "$outdir"/"$logfile" 2>&1
			else
				if [ "$vcd" -eq 1 ] || [ "$svcd" -eq 1 ] ; then
				twolame -s 44100 -b $audio_bitrate "$tmpdir/audio1.wav" "$tmpdir/audio1.mp2" >> "$outdir"/"$logfile" 2>&1
				else
				twolame -s 48000 -b $audio_bitrate "$tmpdir/audio1.wav" "$tmpdir/audio1.mp2" >> "$outdir"/"$logfile" 2>&1
				fi
			fi
		else
			myecho "[dvd-slideshow] using mp2enc for mpeg2 audio encoding"
			myecho "[dvd-slideshow] TIP:  install toolame for faster mp2 audio encoding!"
			myecho "[dvd-slideshow]	Debian/Ubuntu: sudo apt-get install toolame"
			mp2enc -v $verbosity -b $audio_bitrate -r $audio_sample_rate -s -o "$tmpdir/audio1.mp2" < "$tmpdir/audio1.wav"
		fi
	fi
	commandline_audio=1
fi  # end processing command-line passed audio

if [ -z "${audio_1[0]}" ] && [ -z "${audio_2[0]}" ] && [ "$commandline_audio" -eq 0 ] ; then
	## no audio file passed on command line or txtfile. use silence:
	audio_1[0]='silence'  # no duration needed
	myecho "[dvd-slideshow] No audio files passed. Using $end_hms silence."
	audio1_start=0 
	audio1_end="$end_time"
fi


## let's split this audio processing into two loops:  one just prepares the
## initial fadein/fadeout, and the next loop figures out the timing and cropping 

let i=0
skip_next_audio_file=0
if [ -n "${audio_1[0]}" ] ; then   ## audio track 1 files specified in .txt file
#	myecho "[dvd-slideshow] Processing track 1 audio from .txt file..."
	for file in "${audio_1[@]}"; do
		if [ "$skip_next_audio_file" -eq 1 ] ; then
#			myecho -n "i=$i myindex=$myindex  "
			if [ $i -eq $myindex ] ; then
				skip_next_audio_file=0
			fi	
			myecho "[dvd-slideshow] Skipping un-needed audio file $i"
			myecho "[dvd-slideshow] ###############"
			let i=$i+1
			continue
		fi
		i_padded=`addzeros $i`
		myecho "[dvd-slideshow] Working on track 1 audio file $(($i+1))"
		myecho "[dvd-slideshow] $file"
		
		if [ "${audio1_end[$i]:-0}" -eq 0 ] || [ -z "$audio1_end[$i]}" ] ; then
#		if [ -z "$audio1_end[$i]}" ] || [ $audio1_end[$i] ] ; then
			## must be last audio track. assume run til end
			audio1_end[$i]="$end_time"	
		fi

#		if [ ${audio1_start[$i]} -ge ${audio1_end[$i]} ] ; then
#			myecho "[dvd-slideshow] ERROR: Audio file endpoint is same or before start."
#			myecho "[dvd-slideshow] 	     This is sometimes caused by having two audio files"
#			myecho "[dvd-slideshow] 	     sequentially one after another with no slide between."
#			myecho "[dvd-slideshow] 	     Fix it and try again."
#			cleanup; exit 1
#		fi
	
		if [ "$file" == 'silence' ]; then   # create silence for the correct time:
			song_end_ms=$(( ${audio1_end[$i]} - ${audio1_start[$i]} ))
			[ "$song_end_ms" -lt 0 ] && song_end_ms=0
			song_end_hms=`hms $song_end_ms`
			song_start_hms="0"  # cannot modify starting point yet...
			myecho "[dvd-slideshow] Creating silence audio file for $song_end_hms"
			sox -t raw $sox_int $sox_word -c 1 -r $audio_sample_rate /dev/zero $sox_word $sox_int -c 2 -r $audio_sample_rate "$tmpdir"/audio1_$i_padded.raw trim "0" "$song_end_hms"
		else
			## file should only be wav format at this point since it was decoded before
			## all audio files are of the format "$tmpdir"/audio_1.wav
			# I found some "popping" in the audio for some tracks.
			# it turns out that this is caused by audio going
			# too low or too high and getting clipped.
			# reducing the volume a little should help.
			volume="0.95"
			waitforfile "$tmpdir/audio1_$i_padded.wav"
			volume_sox=`sox "$tmpdir"/"audio1_$i_padded.wav" $sox_nop stat -v 2>&1 | tr -d :[blank]:`
			myecho "[dvd-slideshow] Volume adjust=$volume  should be $volume_sox"
			waitforfile "$tmpdir/audio1_$i_padded".wav
			song_length_ms=`wavlength "$tmpdir/audio1_$i_padded.wav"`
			song_length_hms=`hms $song_length_ms`
			myecho "[dvd-slideshow] Original audio track length=$song_length_hms"

			if [ -z "${audio1_effect1_params[$i]}" ] ; then
				fade_in_time="0"
			else
				fade_in_time=`seconds2ms ${audio1_effect1_params[$i]}`
			fi
			if [ -z "${audio1_effect2_params[$i]}" ] ; then
				fade_out_time="0"
			else
				fade_out_time=`seconds2ms ${audio1_effect2_params[$i]}`
			fi
			fade_in_hms=`hms "$fade_in_time"`
			fade_out_hms=`hms "$fade_out_time"`
			myecho "[dvd-slideshow] Fade in time=$fade_in_hms Fade out time=$fade_out_hms"
			if [ "$song_length_ms" -le "$(( $fade_in_time + $fade_out_time ))" ] ; then
				myecho "[dvd-slideshow] WARNING: Audio length is shorter than the combined fadein and fadeout times"
				fade_in_time=$(( $song_length / 4 ))
				fade_out_time="$fade_in_time"
				myecho "[dvd-slideshow]          Setting fadein and fadeout time to `hms $fade_in_time`"
			fi
			song_end_ms=$(( ${audio1_end[$i]} - ${audio1_start[$i]} ))
			[ "$song_end_ms" -lt 0 ] && song_end_ms=0
			song_end_hms=`hms $song_end_ms`
			song_start_hms="0"  # cannot modify starting point yet...
#			myecho "[dvd-slideshow] audio1_start=${audio1_start[$i]} audio1_start+1=${audio1_start[$(($i+1))]}"
#			myecho "[dvd-slideshow] song_start_hms=$song_start_hms song_end_hms=$song_end_hms"
#			myecho "[dvd-slideshow] audio_start=`hms ${audio1_start[$i]}`. audio_end=`hms ${audio1_end[$i]}`."
			# check to see if we need to add multiple files together first:
			if [ -n "${audio1_start[$(($i+1))]}" ] && [ "${audio1_start[$i]}" -ge "${audio1_start[$(($i+1))]}" ] ; then
#				myecho " [dvd-slideshow] Multiple files found right after one another!"
				## User might add 10 audio files when only 2 are needed
				## to span the video... check for this:
				## 1. find next real audio start marker
				## 2. compare length of songs up to that point.
				myindex=$i
				while [ -n "${audio1_start[$(($myindex+1))]}" ] && [ "${audio1_start[$myindex]}" -ge "${audio1_start[$(($myindex+1))]}" ] ; do
					# grab last starting time:
					next_real_audio_start="${audio1_start[$(($myindex+2))]}"
					if [ -z "$next_real_audio_start" ] ; then
						## must be last audio track. assume run til end
						next_real_audio_start="$end_time"	
					fi
#					myecho " [dvd-slideshow] next audio start=$next_real_audio_start myindex=$myindex"
					myindex=$(( $myindex + 1 ))
				done
				# set first file audio endpoint to the least
				# of the full length of song or the start of the next file:
				# (whichever comes first)
				if [ $next_real_audio_start -lt $(( ${audio1_start[$i]} + $song_length_ms )) ] ; then
					# this song is too long and needs to be cropped
					# set endpoint to starting point of next song
					audio1_end[$i]=$next_real_audio_start 
#					# ignore next audio files until $next_real_audio_start
					skip_next_audio_file=1
#					myecho "[dvd-slideshow] Next audio file not needed"
#					myecho "[dvd-slideshow] Setting audio1_end[$i]=${audio1_end[$i]}"
				else
					# song not long enough... need to add next audio file
					# or buffer with silence at end.
					audio1_end[$i]=$(( ${audio1_start[$i]} + $song_length_ms )) 
					# set second file audio startpoint to end of fist song:
					audio1_start[$(($i+1))]="${audio1_end[$i]}" 
#					myecho "[dvd-slideshow] Concatenating next audio file also"
#					myecho " [dvd-slideshow] Setting audio1_start[$(($i+1))]=${audio1_end[$i]} audio1_end[$i]=${audio1_end[$i]}"
				fi
			fi  # end of concatinating multiple files...

			song_end_ms=$(( ${audio1_end[$i]} - ${audio1_start[$i]} ))
			[ "$song_end_ms" -lt 0 ] && song_end_ms=0
			song_end_hms=`hms $song_end_ms`
			song_start_hms="0"  # cannot modify starting point yet...
			[ "$debug" -ge 1 ] && myecho "[dvd-slideshow] song_start_hms=$song_start_hms song_end_hms=$song_end_hms"
			
			if [ "$song_length_ms" -lt "$song_end_ms" ] ; then
				myecho "[dvd-slideshow] Audio length < song_end   `hms $song_length_ms` < `hms $song_end_ms`"
				# video is longer than audio. need to add silence to end.
				# fade only to the end of song length now, because we may have to add silence:
				# We should probably eventually add the silence first, and then chop the song?
				if [ "$fade_in_time" -eq 0 ] && [ "$fade_out_time" -eq 0 ] ; then
					sox -v $volume "$tmpdir/audio1_$i_padded.wav" $sox_word $sox_int -c 2 -r $audio_sample_rate "$tmpdir/audio1_$i_padded.raw"
				else  # fade in or out
					sox -v $volume "$tmpdir/audio1_$i_padded.wav" $sox_word $sox_int -c 2 -r $audio_sample_rate "$tmpdir/audio1_$i_padded.raw" fade t "$fade_in_hms" "$song_length_hms" "$fade_out_hms"
				fi
				thetime_hms=`hms $(( $song_end_ms - $song_length_ms ))` 
				myecho "[dvd-slideshow] Adding $thetime_hms of silence to end of original audio file"
				sox -t raw $sox_int $sox_word -c 2 -r $audio_sample_rate /dev/zero $sox_word $sox_int -c 2 -r $audio_sample_rate "$tmpdir/silence.raw" trim 0 "$thetime_hms"
				cat "$tmpdir/audio1_$i_padded.raw" "$tmpdir/silence.raw" > "$tmpdir/audio.raw" 
				mv "$tmpdir/audio.raw" "$tmpdir/audio1_$i_padded.raw"
				rm "$tmpdir"/silence.raw
			else # desired song length is shorter than actual song length. need to cut it:
				if [ "$debug" -ge 2 ] ; then
					length=`wavlength "$tmpdir/audio1_$i_padded.wav"`
					myecho "[dvd-slideshow] Actual length of .raw file=`hms $length`"
					myecho "[dvd-slideshow] Fadein: $fade_in_hms"
					myecho "[dvd-slideshow] Song End: $song_end_hms"
					myecho "[dvd-slideshow] Fadeout: $fade_out_hms"
				fi
#				echo "song_length_ms=$song_length_ms song_end_ms=$song_end_ms fade_in_time=$fade_in_time fade_out_time=$fade_out_time"
				if [ "$song_length_ms" -ne "$song_end_ms"  ] && [ "$fade_in_time" -eq 0 ] && [ "$fade_out_time" -eq 0 ] ; then
#					echo "cropping"
					sox -v $volume "$tmpdir/audio1_$i_padded.wav" $sox_word $sox_int -c 2 -r $audio_sample_rate "$tmpdir/audio1_$i_padded.raw" trim 0 "$song_end_hms"
				elif [ "$fade_out_time" -ne 0 ] || [ "$fade_in_time" -ne 0 ] ; then
#					echo "fading"
					sox -v $volume "$tmpdir/audio1_$i_padded.wav" $sox_word $sox_int -c 2 -r $audio_sample_rate "$tmpdir/audio1_$i_padded.raw" fade t "$fade_in_hms" "$song_end_hms" "$fade_out_hms"
				else
#					echo "converting"
					sox -v $volume "$tmpdir/audio1_$i_padded.wav" $sox_word $sox_int -c 2 -r $audio_sample_rate "$tmpdir/audio1_$i_padded.raw"
				fi
			fi
			# now, audio should span to the end mark
		fi
		if [ $i -eq 0 ] && [ "${audio1_start[$i]}" -ne 0 ] ; then
			## buffer beginning with silence:
			thetime_hms=`hms "${audio1_start[$i]}"`
			myecho "[dvd-slideshow] Adding $thetime_hms to beginning of audio file"
			sox -t raw $sox_int $sox_word -c 2 -r $audio_sample_rate /dev/zero $sox_word $sox_int -c 2 -r $audio_sample_rate "$tmpdir/silence.raw" trim 0 "$thetime_hms"
			cat "$tmpdir"/silence.raw "$tmpdir/audio1_$i_padded.raw" > "$tmpdir/audio.raw" 
			mv "$tmpdir/audio.raw" "$tmpdir/audio1_$i_padded.raw"
			rm "$tmpdir"/silence.raw
		fi
		myecho "[dvd-slideshow] This audio plays in slideshow from `hms ${audio1_start[$i]}` to `hms ${audio1_end[$i]}`"
		if [ "$debug" -ge 1 ] ; then
			length=`rawlength "$tmpdir/audio1_$i_padded.raw"`
			myecho "[dvd-slideshow] Actual length of .raw file=`hms $length`"
		fi
		let i=$i+1
		myecho "[dvd-slideshow] ###############"
	done
		
	## AC3 audio may be more compatible:
	if [ "$ac3" -eq 1 ] && [ "$output_format" == 'mpeg2' ]; then
		myecho "[dvd-slideshow] Creating ac3 audio..."
		checkforprog avconv
		rm -f "$tmpdir/audio1.ac3"
		cat "$tmpdir"/audio1_????.raw | sox -t raw $sox_word $sox_int -c 2 -r $audio_sample_rate - -t wav - 2> /dev/null >"$tmpdir/audio1.wav"
		if [ $? -ne 0 ] ; then
			## sox errored
			myecho "[dvd-slideshow] ERROR during sox execution!"
			myecho "[dvd-slideshow] see $outdir/$logfile for details"
			cleanup; exit 1
		fi
		avconv -threads "$cores" -i "$tmpdir/audio1.wav" -vn -ab "$audio_bitrate"k -acodec ac3 -vol "100" -ar $audio_sample_rate -ac 6 "$tmpdir/audio1.ac3" >> "$avconv_out" 2>&1
#		avconv -threads "$cores" -i "$tmpdir/audio1.wav" -vn -ab "$audio_bitrate"k -acodec ac3 -ar $audio_sample_rate -ac 6 "$tmpdir/audio1.ac3" >> "$outdir/$logfile" 2>&1
		if [ $? -ne 0 ] ; then
			## avconv errored
			myecho "[dvd-slideshow] ERROR during avconv execution!"
			myecho "[dvd-slideshow] see $outdir/$logfile for details"
			cleanup; exit 1
		fi
	else
		myecho "[dvd-slideshow] Converting all track 1 audio files..."
		cat "$tmpdir"/audio1_????.raw | sox -t raw $sox_word $sox_int -c 2 -r $audio_sample_rate - "$tmpdir/audio1.wav"
		if [ "$debug" -ge 1 ] ; then
			length=`wavlength "$tmpdir/audio1.wav"`
			myecho "[dvd-slideshow] Actual length of .raw file=`hms $length`"
		fi
		
		if [ "$output_format" == 'mpg' ] || [ "$output_format" == "mpeg2" ] ; then 
			## twolame is way faster! (3x in my test)
			it=`which twolame 2> /dev/null`
			if [ -n "$it" ] ; then
				twolame_version=`twolame -h | head -n 4 | grep version | awk '{ print $3 }'`
				myecho "[dvd-slideshow] Creating mp2 audio using twolame $twolame_version..."
				if [ "$twolame_version" == '0.2m' ] ; then
					twolame -s $audio_sample_rate -b $audio_bitrate "$tmpdir/audio1.wav" "$tmpdir/audio1.mp2" >> "$outdir"/"$logfile" 2>&1
				else
					if [ "$vcd" -eq 1 ] || [ "$svcd" -eq 1 ] ; then
					twolame -s 44100 -b $audio_bitrate "$tmpdir/audio1.wav" "$tmpdir/audio1.mp2" >> "$outdir"/"$logfile" 2>&1
					else
					twolame -s 48000 -b $audio_bitrate "$tmpdir/audio1.wav" "$tmpdir/audio1.mp2" >> "$outdir"/"$logfile" 2>&1
					fi
				fi
			else
				myecho "[dvd-slideshow] Creating mp2 audio using mp2enc"
				myecho "[dvd-slideshow] TIP:  install toolame for faster mp2 audio encoding!"
				myecho "[dvd-slideshow]	Debian/Ubuntu: sudo apt-get install toolame"
				mp2enc -v $verbosity -b $audio_bitrate -r $audio_sample_rate -s -o "$tmpdir/audio1.mp2" < "$tmpdir/audio1.wav"
			fi
		fi  # end if we're using a mpeg2 video format
	fi
fi
		

#################################################################
## now do this all again for audio track number 2:
let i=0
skip_next_audio_file=0
if [ -n "${audio_2[0]}" ] ; then   ## audio track 2 files specified in .txt file
	myecho "[dvd-slideshow] #######################################"
	myecho "[dvd-slideshow] Processing track 2 audio from .txt file..."
	myecho "[dvd-slideshow] #######################################"
	for file in "${audio_2[@]}"; do
		if [ "$skip_next_audio_file" -eq 1 ] ; then
#			myecho -n "i=$i myindex=$myindex  "
			if [ $i -eq $myindex ] ; then
				skip_next_audio_file=0
			fi	
			myecho "[dvd-slideshow] Skipping un-needed audio file $i"
			myecho "[dvd-slideshow] ###############"
			let i=$i+1
			continue
		fi
		i_padded=`addzeros $i`
		myecho "[dvd-slideshow] Working on track 2 audio file $(($i+1))"
		myecho "[dvd-slideshow] $file"
		
		if [ "${audio2_end[$i]:-0}" -eq 0 ] || [ -z "$audio2_end[$i]}" ] ; then
			## must be last audio track. assume run til end
			audio2_end[$i]="$end_time"	
		fi
	
		if [ "$file" == 'silence' ]; then   # create silence for the correct time:
			song_end_ms=$(( ${audio2_end[$i]} - ${audio2_start[$i]} ))
			[ "$song_end_ms" -lt 0 ] && song_end_ms=0
			song_end_hms=`hms $song_end_ms`
			song_start_hms="0"  # cannot modify starting point yet...
			myecho "[dvd-slideshow] Creating silence audio file for $song_end_hms"
			sox -t raw $sox_int $sox_word -c 2 -r $audio_sample_rate /dev/zero $sox_word $sox_int -c 2 -r $audio_sample_rate "$tmpdir"/audio2_$i_padded.raw trim "0" "$song_end_hms"
		else # not silence
			## file should only be wav format at this point since it was decoded before
			## all audio files are of the format "$tmpdir"/audio_2.wav
			# I found some "popping" in the audio for some tracks.
			# it turns out that this is caused by audio going
			# too low or too high and getting clipped.
			# reducing the volume a little should help.
			volume=0.95
			sox "$tmpdir/audio2_$i_padded.wav" $sox_nop stat 2> "$tmpdir"/trash.txt 
			## need to fix this so it's accurate to 0.01 sec, not just 1 sec
			## this will get floor(time) now.
			song_length=`cat "$tmpdir"/trash.txt | grep 'Length (seconds):' | awk -F: '{print $2}' | awk -F. '{print $1}'`
			rm "$tmpdir"/trash.txt
			song_length_ms="$(( 1000 * $song_length))"
			song_length_hms=`hms $song_length_ms`
			myecho "[dvd-slideshow] Original audio track length=$song_length_hms"


			if [ -z "${audio2_effect1_params[$i]}" ] ; then
				fade_in_time="0"
			else
				fade_in_time=`seconds2ms ${audio2_effect1_params[$i]}`
			fi
			if [ -z "${audio2_effect2_params[$i]}" ] ; then
				fade_out_time="0"
			else
				fade_out_time=`seconds2ms ${audio2_effect2_params[$i]}`
			fi
			fade_in_hms=`hms "$fade_in_time"`
			fade_out_hms=`hms "$fade_out_time"`
			myecho "[dvd-slideshow] Fade in time=$fade_in_hms Fade out time=$fade_out_hms"

			if [ "$song_length_ms" -lt "$(( $fade_in_time + $fade_out_time ))" ] ; then
				myecho "[dvd-slideshow] WARNING: Song length is shorter than the combined fadein and fadeout times"
				fade_in_time=$(( ( $song_length - 1 ) / 2 ))
				fade_out_time="$fade_in_time"
				myecho "[dvd-slideshow]          Setting fadein and fadeout time to `hms $fade_in_time`"
			fi

			song_end_ms=$(( ${audio2_end[$i]} - ${audio2_start[$i]} ))
			[ "$song_end_ms" -lt 0 ] && song_end_ms=0
			song_end_hms=`hms $song_end_ms`
			song_start_hms="0"  # cannot modify starting point yet...
#			myecho "[dvd-slideshow] audio2_start=${audio2_start[$i]} audio2_start+1=${audio2_start[$(($i+1))]}"
#			myecho "[dvd-slideshow] song_start_hms=$song_start_hms song_end_hms=$song_end_hms"
#			myecho "[dvd-slideshow] audio_start=`hms ${audio2_start[$i]}`. audio_end=`hms ${audio2_end[$i]}`."
			# check to see if we need to add multiple files together first:
			if [ -n "${audio2_start[$(($i+1))]}" ] && [ "${audio2_start[$i]}" -ge "${audio2_start[$(($i+1))]}" ] ; then
#				myecho " [dvd-slideshow] Multiple files found right after one another!"
				## User might add 10 audio files when only 2 are needed
				## to span the video... check for this:
				## 1. find next real audio start marker
				## 2. compare length of songs up to that point.
				myindex=$i
				while [ -n "${audio2_start[$(($myindex+1))]}" ] && [ "${audio2_start[$myindex]}" -ge "${audio2_start[$(($myindex+1))]}" ] ; do
					# grab last starting time:
					next_real_audio_start="${audio2_start[$(($myindex+2))]}"
					if [ -z "$next_real_audio_start" ] ; then
						## must be last audio track. assume run til end
						next_real_audio_start="$end_time"	
					fi
#					myecho " [dvd-slideshow] next audio start=$next_real_audio_start myindex=$myindex"
					myindex=$(( $myindex + 1 ))
				done
				# set first file audio endpoint to the least
				# of the full length of song or the start of the next file:
				# (whichever comes first)
				if [ $next_real_audio_start -lt $(( ${audio2_start[$i]} + $song_length_ms )) ] ; then
					# this song is too long and needs to be cropped
					# set endpoint to starting point of next song
					audio2_end[$i]=$next_real_audio_start 
#					# ignore next audio files until $next_real_audio_start
					skip_next_audio_file=1
#					myecho "[dvd-slideshow] Next audio file not needed"
#					myecho "[dvd-slideshow] Setting audio2_end[$i]=${audio2_end[$i]}"
				else
					# song not long enough... need to add next audio file
					# or buffer with silence at end.
					audio2_end[$i]=$(( ${audio2_start[$i]} + $song_length_ms )) 
					# set second file audio startpoint to end of fist song:
					audio2_start[$(($i+1))]="${audio2_end[$i]}" 
#					myecho "[dvd-slideshow] Concatenating next audio file also"
#					myecho " [dvd-slideshow] Setting audio2_start[$(($i+1))]=${audio2_end[$i]} audio2_end[$i]=${audio2_end[$i]}"
				fi
			fi

			song_end_ms=$(( ${audio2_end[$i]} - ${audio2_start[$i]} ))
			[ "$song_end_ms" -lt 0 ] && song_end_ms=0
			song_end_hms=`hms $song_end_ms`
			song_start_hms="0"  # cannot modify starting point yet...
#			myecho "[dvd-slideshow] song_start_hms=$song_start_hms song_end_hms=$song_end_hms"

			if [ "$song_length_ms" -lt "$song_end_ms" ] ; then
				myecho "[dvd-slideshow] Audio length < song_end   `hms $song_length_ms` < `hms $song_end_ms`"
				# video is longer than audio. need to add silence to end.
				# fade only to the end of song length now, because we may have to add silence:
				# We should probably eventually add the silence first, and then chop the song?
				if [ "$fade_in_time" -eq 0 ] && [ "$fade_out_time" -eq 0 ] ; then
					sox -v $volume "$tmpdir/audio2_$i_padded.wav" $sox_word $sox_int -c 2 -r $audio_sample_rate "$tmpdir/audio2_$i_padded.raw"
				else # one of the fades is nonzero:
					sox -v $volume "$tmpdir/audio2_$i_padded.wav" $sox_word $sox_int -c 2 -r $audio_sample_rate "$tmpdir/audio2_$i_padded.raw" fade t "$fade_in_hms" "$song_length_hms" "$fade_out_hms"
				fi
				thetime_hms=`hms $(( $song_end_ms - $song_length_ms + 1000 ))` #plus 1s so sox actually crops.
				thetime2_hms=`hms $(( $song_end_ms - $song_length_ms ))` 
				myecho "[dvd-slideshow] Adding $thetime2_hms of silence to end of original audio file"
				sox -t raw $sox_int $sox_word -c 2 -r $audio_sample_rate /dev/zero $sox_word $sox_int -c 2 -r $audio_sample_rate "$tmpdir/silence.raw" trim 0 "$thetime_hms"
				cat "$tmpdir/audio2_$i_padded.raw" "$tmpdir/silence.raw" > "$tmpdir/audio.raw" 
				mv "$tmpdir/audio.raw" "$tmpdir/audio2_$i_padded.raw"
				# hopefully there won't be many times where the audio needs to be buffered 
				# at the end, so we'll add one extra step to make the coding easier:
				sox -t raw $sox_int $sox_word -c 2 -r $audio_sample_rate "$tmpdir/audio2_$i_padded.raw" "$tmpdir/audio2_$i_padded.wav"
				rm "$tmpdir"/silence.raw
			fi
			if [ "$debug" -ge 2 ] ; then
				length=`wavlength "$tmpdir/audio2_$i_padded.wav"`
				myecho "[dvd-slideshow] Actual length of .raw file=`hms $length`"
				myecho "[dvd-slideshow] Fadein: $fade_in_hms"
				myecho "[dvd-slideshow] Song End: $song_end_hms"
				myecho "[dvd-slideshow] Fadeout: $fade_out_hms"
			fi
			if [ "$song_length_ms" -ne "$song_end_ms"  ] && [ "$fade_in_time" -eq 0 ] && [ "$fade_out_time" -eq 0 ] ; then
#				echo "cropping"
				sox -v $volume "$tmpdir/audio2_$i_padded.wav" $sox_word $sox_int -c 2 -r $audio_sample_rate "$tmpdir/audio2_$i_padded.raw" trim 0 "$song_end_hms"
			elif [ "$fade_out_time" -ne 0 ] || [ "$fade_in_time" -ne 0 ] ; then
#				echo "fading"
				sox -v $volume "$tmpdir/audio2_$i_padded.wav" $sox_word $sox_int -c 2 -r $audio_sample_rate "$tmpdir/audio2_$i_padded.raw" fade t "$fade_in_hms" "$song_end_hms" "$fade_out_hms"
			else
#				echo "converting"
				sox -v $volume "$tmpdir/audio2_$i_padded.wav" $sox_word $sox_int -c 2 -r $audio_sample_rate "$tmpdir/audio2_$i_padded.raw"
			fi
		fi  # end of if silence or not
		if [ $i -eq 0 ] && [ "${audio2_start[$i]}" -ne 0 ] ; then
			## buffer beginning with silence:
			thetime_hms=`hms "${audio2_start[$i]}"`
			myecho "[dvd-slideshow] Adding $thetime_hms to beginning of audio file"
			sox -t raw $sox_int $sox_word -c 2 -r $audio_sample_rate /dev/zero $sox_word $sox_int -c 2 -r $audio_sample_rate "$tmpdir/silence.raw" trim 0 "$thetime_hms"
			cat "$tmpdir"/silence.raw "$tmpdir/audio2_$i_padded.raw" > "$tmpdir/audio.raw" 
			mv "$tmpdir/audio.raw" "$tmpdir/audio2_$i_padded.raw"
			rm "$tmpdir"/silence.raw
		fi
		myecho "[dvd-slideshow] This audio plays in slideshow from `hms ${audio2_start[$i]}` to `hms ${audio2_end[$i]}`"
		if [ "$debug" -ge 1 ] ; then
			length=`rawlength "$tmpdir/audio2_$i_padded.raw"`
			myecho "[dvd-slideshow] Actual length of .raw file=`hms $length`"
		fi
		let i=$i+1
		myecho "[dvd-slideshow] ###############"
	done
		
	myecho "[dvd-slideshow] Concatenating all track 2 audio files..."
	## cat all the audio files together: 
#	find "$tmpdir" -name audio2_????.raw -print0 | xargs -0 sox -t raw $sox_word -s -c 2 -r $audio_sample_rate - "$tmpdir/audio2.wav"
	cat "$tmpdir"/audio2_????.raw | sox -t raw $sox_word $sox_int -c 2 -r $audio_sample_rate - "$tmpdir/audio2.wav"
	if [ "$debug" -ge 1 ] ; then
		length=`wavlength "$tmpdir/audio2.wav"`
		myecho "[dvd-slideshow] Actual length of .raw file=`hms $length`"
	fi
	## AC3 audio may be more compatible:
	if [ "$ac3" -eq 1 ] && [ "$output_format" == 'mpeg2' ] ; then  # only if dvd output
		myecho "[dvd-slideshow] Creating ac3 audio..."
		checkforprog avconv
		rm -f "$tmpdir/audio2.ac3"
		avconv -threads "$cores" -i "$tmpdir"/audio2.wav -vn -ab "$audio_bitrate"k -acodec ac3 -vol "100" -ar $audio_sample_rate -ac 6 "$tmpdir/audio2.ac3" >> "$avconv_out" 2>&1
		if [ $? -ne 0 ] ; then
			## avconv errored
			myecho "[dvd-slideshow] ERROR during avconv execution!"
			myecho "[dvd-slideshow] see $outdir/$logfile for details"
			cleanup; exit 1
		fi
	else
		## twolame is way faster! (3x in my test)
		it=`which twolame 2> /dev/null`
		if [ -n "$it" ] ; then
			twolame_version=`twolame -h | head -n 4 | grep version | awk '{ print $3 }'`
			myecho "[dvd-slideshow] Creating mp2 audio using twolame $twolame_version..."
			if [ "$twolame_version" == '0.2m' ] ; then
				twolame -s $audio_sample_rate -b $audio_bitrate "$tmpdir/audio2.wav" "$tmpdir/audio2.mp2" >> "$outdir"/"$logfile" 2>&1
			else
				if [ "$vcd" -eq 1 ] || [ "$svcd" -eq 1 ] ; then
				twolame -s 44100 -b $audio_bitrate "$tmpdir/audio2.wav" "$tmpdir/audio2.mp2">> "$outdir"/"$logfile" 2>&1
				else
				twolame -s 48000 -b $audio_bitrate "$tmpdir/audio2.wav" "$tmpdir/audio2.mp2" >> "$outdir"/"$logfile" 2>&1
				fi
			fi
		else
			myecho "[dvd-slideshow] Creating mp2 audio using mp2enc"
			myecho "[dvd-slideshow] TIP:  install toolame for faster mp2 audio encoding!"
			myecho "[dvd-slideshow]	Debian/Ubuntu: sudo apt-get install toolame"
			mp2enc -v $verbosity -b $audio_bitrate -r $audio_sample_rate -s -o "$tmpdir/audio2.mp2" < "$tmpdir/audio2.wav"
		fi
	fi
fi


## check to make sure the output files exist before running mplex:
if [ ! -f "$tmpdir/video.$video_suffix" ] ; then
	myecho "[dvd-slideshow] ERROR: no output .$video_suffix file found!"
	myecho "[dvd-slideshow] This usually happens when avconv screws up something"
	myecho "[dvd-slideshow] or one image is messed up and the resulting video can't be created"
fi
	
myecho '[dvd-slideshow]############################################################'
myecho '[dvd-slideshow] Multiplexing audio and video...'
logecho '[dvd-slideshow] Some sequence marker warnings here are normal'

## now multiplex the audio and video:
## -M option is important:  it generates a "single" output file instead of "single-segement" ones
## if you don't use -M, the dvdauthor command will fail!
## total mplex bitrate = 128kBit audio + 1500 kBit video + a little overhead
verbosity=0
if [ "$output_format" == 'flv' ] ; then  # only one audio track for .flv, .swf, and .mp4, etc...
	if [ "$audio_1" == 'silence' ] ; then
		# no audio tracks for this flv file... do not add audio
		myecho "[dvd-slideshow] No audio for .flv file"
		mv "$tmpdir/video.flv" "$outdir"/"$slideshow_name".flv
	else
		myecho "[dvd-slideshow] Adding audio to .flv file"
		avconv -threads "$cores" -y -i "$tmpdir/audio1.wav" -i "$tmpdir/video.flv" -vcodec copy -f flv -ar 22050 -ab 48 -ac 1 "$tmpdir/video1.flv" >> "$avconv_out" 2>&1
		mv "$tmpdir/video1.flv" "$outdir"/"$slideshow_name".flv
	fi
#	myecho "[dvd-slideshow] Generating video thumbnail..."
#	avconv -threads "$cores" -y -i "$outdir"/"$slideshow_name".flv -f mjpeg -t 0.001 "$outdir"/"$slideshow_name".jpg >> "$avconv_out" 2>&1
	if [ -f "/usr/bin/flvtool2" ] ; then
		myecho "[dvd-slideshow] Running flvtool2 -U $slideshow_name".flv
		/usr/bin/flvtool2 -U "$outdir"/"$slideshow_name".flv
	fi
elif [ "$output_format" == 'swf' ] ; then
	myecho "[dvd-slideshow] Adding audio to .swf file"
	avconv -threads "$cores" -y -i "$tmpdir/audio1.wav" -i "$tmpdir"/video.swf -vcodec copy -f flv -ar 22050 -ab 48 -ac 1 "$tmpdir"/video1.swf >> "$avconv_out" 2>&1
	mv "$tmpdir"/video1.swf "$outdir"/"$slideshow_name".swf
#	myecho "[dvd-slideshow] Generating video thumbnail..."
#	avconv -threads "$cores" -y -i "$outdir"/"$slideshow_name".swf -f mjpeg -t 0.001 "$outdir"/"$slideshow_name".jpg >> "$avconv_out" 2>&1
elif [ "$output_format" == 'mp4' ] ; then   
	myecho "[dvd-slideshow] Adding audio to .mp4 file"
#	myecho avconv -threads "$cores" -y -i "$tmpdir/audio1.wav" -i "$tmpdir"/video.mp4 -vcodec copy -f mp4 -ar 22050 -ab 128k -ac 1 "$tmpdir"/video1.mp4 '>>' "$avconv_out" '2>&1'
	avconv -threads "$cores" -y -i "$tmpdir"/audio1.wav -i "$tmpdir"/video.mp4 -vcodec copy -f mp4 -ar 22050 -ab 128k -ac 1 "$tmpdir"/video1.mp4 >> "$avconv_out" 2>&1
	mv "$tmpdir"/video1.mp4 "$outdir"/"$slideshow_name".mp4
elif [ "$output_format" == 'mp4_ipod' ] ; then   
	myecho "[dvd-slideshow] Exporting ipod .mp4 file"
	avconv -threads "$cores" -y -i "$tmpdir/audio1.wav" -i "$tmpdir"/video.mp4 -vcodec copy -f mp4 -ar 22050 -ab 48 -ac 1 "$tmpdir"/video1.mp4 >> "$avconv_out" 2>&1
	mv "$tmpdir"/video1.mp4 "$outdir"/"$slideshow_name".mp4
elif [ "$output_format" == 'ogv' ] ; then   
	myecho "[dvd-slideshow] Adding audio to .ogv file"
	avconv -threads "$cores" -y -i "$tmpdir/audio1.wav" -i "$tmpdir"/video.ogv -vcodec copy -f ogg -acodec libvorbis -ac 1 "$tmpdir"/video1.ogv >> "$avconv_out" 2>&1
	mv "$tmpdir"/video1.ogv "$outdir"/"$slideshow_name".ogv
elif [ -n "${audio_2[0]}" ] && [ "$vcd" -eq 0 -a "$svcd" -eq 0 ] ; then
	## two audio tracks!
	echo "[dvd-slidehsow] two audio tracks found"
	if [ "$ac3" -eq 1 ] ; then
		mplex -V -v $verbosity $ignore_seq_end $video_buffer -f $mplex_type -o "$outdir"/"$slideshow_name".vob "$tmpdir/video.mpg" "$tmpdir"/audio1.ac3 "$tmpdir"/audio2.ac3 2>> "$outdir/$logfile"
	else
		mplex -V -v $verbosity $ignore_seq_end $video_buffer -f $mplex_type -o "$outdir"/"$slideshow_name".vob "$tmpdir/video.mpg" "$tmpdir"/audio1.mp2 "$tmpdir"/audio2.mp2 2>> "$outdir/$logfile"
	fi
else  # default mpeg2 video for dvd/vcd
	if [ "$ac3" -eq 1 ] ; then
		if [ ! -f "$tmpdir/audio1.ac3" ] ; then
			myecho "[dvd-slideshow] ERROR: no output .ac3 file found!"
			myecho "[dvd-slideshow] Must be some error with your input audio"
			myecho "[dvd-slideshow] or the ac3 encoder"
		fi
		mplex -V -v $verbosity $video_buffer $ignore_seq_end -f $mplex_type -o "$outdir"/"$slideshow_name".vob "$tmpdir/video.mpg" "$tmpdir"/audio1.ac3 2>> "$outdir/$logfile"
	else
		if [ ! -f "$tmpdir/audio1.mp2" ] ; then
			myecho "[dvd-slideshow] ERROR: no output .mp2 file found!"
			myecho "[dvd-slideshow] Must be some error with your input audio"
			myecho "[dvd-slideshow] or the mp2 audio encoder"
		fi
		mplex -V -v $verbosity $video_buffer $ignore_seq_end -f $mplex_type -r $mplex_bitrate -o "$outdir"/"$slideshow_name".vob "$tmpdir/video.mpg" "$tmpdir"/audio1.mp2  2>> "$outdir/$logfile"
	fi
	if [ $? -ne 0 ] ; then
		## mplex errored
		myecho "[dvd-slideshow] ERROR during mplex execution!"
		myecho "[dvd-slideshow] see $outdir/$logfile for details"
		cleanup; exit 1
	fi
fi

myecho "[dvd-slideshow]############################################################"

verbosity=0
## now run spumux only if the png was generated:
if [ "$vcd" -eq 1 ] || [ "$svcd" -eq 1 ] ; then
	myecho "[dvd-slideshow] VCD mode: not running spumux"
elif [ "$output_format" == "flv" ] || [ "$output_format" == "mp4" ] || [ "$output_format" == 'mp4_ipod' ] || [ "$output_format" == 'swf' ] || [ "$output_format" == 'ogv' ] ; then
	myecho "[dvd-slideshow] Non-DVD mode: not running spumux"
elif [ "$subtitle_type" != 'render' ] ; then   # dvd
myecho "[dvd-slideshow] Running spumux in render mode"
	if [ "$has_subtitles" -eq 1 ] ; then
		export VIDEO_FORMAT="$ntsc_or_pal"
		spumux -m dvd -v $verbosity -s 0 -P "$tmpdir"/"$slideshow_name".spumux < "$outdir"/"$slideshow_name".vob > "$outdir/tmp.vob"  2>> "$outdir/$logfile"
		if [ $? -ne 0 ] ; then
			## spumux errored
			myecho "[dvd-slideshow] ERROR during spumux execution!"
			myecho "[dvd-slideshow] see $outdir/$logfile for details"
			cleanup; exit 1
		fi
		mv "$outdir/tmp.vob" "$outdir"/"$slideshow_name".vob
	fi
	if [ "$has_subtitles2" -eq 1 ] ; then
		export VIDEO_FORMAT="$ntsc_or_pal"
		spumux -m dvd -v $verbosity -s 1 -P "$tmpdir"/"$slideshow_name".spumux2 < "$outdir"/"$slideshow_name".vob > "$outdir/tmp.vob"  2>> "$outdir/$logfile"
		if [ $? -ne 0 ] ; then
			## spumux errored
			myecho "[dvd-slideshow] ERROR during spumux execution!"
			myecho "[dvd-slideshow] see $outdir/$logfile for details"
			cleanup; exit 1
		fi
		mv "$outdir/tmp.vob" "$outdir"/"$slideshow_name".vob
	fi
fi


## build the chapters string for passing to dvdauthor:
myecho "[dvd-slideshow] total chapters=${#chaps[@]}"

total_chapters="${#chaps[@]}"
new_total_chapters="$total_chapters"
factor=1  ;  mod=1
while [ $new_total_chapters -gt 99 ] ;  ## 99 chapters max
do
	factor=$(( 2 * $factor ))
	new_total_chapters=$(( $new_total_chapters / 2 ))	
done
if [ "$new_total_chapters" -ne "${#chaps[@]}" ] ; then
	myecho "[dvd-slideshow] reduced total chapter markers to $new_total_chapters"
fi
a=0 ; b=0
for chap in "${chaps[@]}"; do
	if [ $a == 0 ] ; then  # no comma for first chapter
		## first chapter should always be at 0 time!
		chaps_string="0"
		chapter_thumbs[$b]="${thumbs[$a]}"
		b=$(( $b + 1 ))
	else
		# only do every $factor chapters
		if [ "$mod" -eq "$factor" ] ; then
			chaps_string="$chaps_string,$chap"
			chapter_thumbs[$b]="${thumbs[$a]}"
			b=$(( $b + 1 ))
			mod=1
		else
			mod=$(( $mod + 1 ))
		fi
	fi
	a=$(( $a + 1 ))
done

if [ "$write_chaps" -eq 1 ] ; then
	# write out chapters to file:
	echo "$chaps_string" > "$outdir"/"${slideshow_name}.chap"
fi

if [ "$debug" -ge 1 ] ; then
	myecho "[dvd-slideshow] chapter markers at $chaps_string"
fi
myecho "[dvd-slideshow]############################################################"

if [ "$vcd" -eq 1 ] || [ "$svcd" -eq 1 ] ; then
	mv "$outdir"/"$slideshow_name".vob "$outdir"/"$slideshow_name".mpg
	echo "$outdir"/"$slideshow_name".mpg > "$outdir"/"$slideshow_name".xml
elif [ "$output_format" == 'mpg' ] ; then
	mv "$outdir"/"$slideshow_name".vob "$outdir"/"$slideshow_name".mpg	
	echo "$outdir"/"$slideshow_name".mpg > "$outdir"/"$slideshow_name".xml
else
	echo '		<vob chapters="'$chaps_string'" file="'$outdir/$slideshow_name.vob'"  />' > "$outdir/$slideshow_name".xml
	echo '		<!-- pal="'$pal'" -->' >> "$outdir/$slideshow_name".xml
	[ -n "$hilight_image" ] && echo '		<!-- button="'$hilight_image'" -->' >> "$outdir/$slideshow_name".xml
	[ -n "$hilight_title" ] && echo '		<!-- title="'$hilight_title'" -->' >> "$outdir/$slideshow_name".xml
fi

cleanup
export VIDEO_FORMAT="$original_video_format"

## now, just cleanup the logfile a little bit:
sed -e '/ bytes of data written[[:cntrl:]]INFO/d' "$outdir"/"$logfile" > "$outdir"/tmp.txt
sed -e '/ [[:cntrl:]]size= /d' "$outdir"/"tmp.txt" > "$outdir"/"$logfile"
\rm "$outdir"/tmp.txt
#mv "$outdir"/tmp.txt "$outdir"/"$logfile"

cpu_end_time=`date +%s`
cpu_time="$(( $cpu_end_time - $cpu_start_time ))"
myecho "[dvd-slideshow] Total runtime was $cpu_time seconds"
myecho "[dvd-slideshow] More extensive logfile output is at:"
myecho "[dvd-slideshow] $outdir/$logfile"
myecho "[dvd-slideshow] Done!"
myecho ""
myecho "[dvd-slideshow] use one of the following comands to view your output:"
if [ "$output_format" == 'mpg' ] ; then
	myecho "[dvd-slideshow] totem \"$outdir/$slideshow_name.mpg\""
	myecho "[dvd-slideshow] vlc \"$outdir/$slideshow_name.mpg\""
	myecho "[dvd-slideshow] xine -g \"$outdir/$slideshow_name.mpg\""
	myecho "[dvd-slideshow] mplayer \"$outdir/$slideshow_name.mpg\""
elif [ "$output_format" == 'flv' ] ; then
	myecho "[dvd-slideshow] totem \"$outdir/$slideshow_name.flv\""
	myecho "[dvd-slideshow] vlc \"$outdir/$slideshow_name.flv\""
	myecho "[dvd-slideshow] xine -g \"$outdir/$slideshow_name.flv\""
	myecho "[dvd-slideshow] mplayer \"$outdir/$slideshow_name.flv\""
elif [ "$output_format" == 'swf' ] ; then
	myecho "[dvd-slideshow] totem \"$outdir/$slideshow_name.swf\""
	myecho "[dvd-slideshow] vlc \"$outdir/$slideshow_name.swf\""
	myecho "[dvd-slideshow] xine -g \"$outdir/$slideshow_name.swf\""
	myecho "[dvd-slideshow] mplayer \"$outdir/$slideshow_name.swf\""
elif [ "$output_format" == 'mp4' ] ; then
	myecho "[dvd-slideshow] totem \"$outdir/$slideshow_name.mp4\""
	myecho "[dvd-slideshow] vlc \"$outdir/$slideshow_name.mp4\""
	myecho "[dvd-slideshow] xine -g \"$outdir/$slideshow_name.mp4\""
	myecho "[dvd-slideshow] mplayer \"$outdir/$slideshow_name.mp4\""
elif [ "$output_format" == 'ogv' ] ; then
	myecho "[dvd-slideshow] totem \"$outdir/$slideshow_name.ogv\""
	myecho "[dvd-slideshow] vlc \"$outdir/$slideshow_name.ogv\""
	myecho "[dvd-slideshow] xine -g \"$outdir/$slideshow_name.ogv\""
	myecho "[dvd-slideshow] mplayer \"$outdir/$slideshow_name.ogv\""
else
	myecho "[dvd-slideshow] totem \"$outdir/$slideshow_name.vob\""
	myecho "[dvd-slideshow] vlc \"$outdir/$slideshow_name.vob\""
	myecho "[dvd-slideshow] xine -g -u 0 \"$outdir/$slideshow_name.vob\""
	myecho "[dvd-slideshow] mplayer -sid 0 \"$outdir/$slideshow_name.vob\""
fi
echo
exit 0