File: podget

package info (click to toggle)
podget 1.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 484 kB
  • sloc: sh: 3,206; python: 34; makefile: 24
file content (4108 lines) | stat: -rwxr-xr-x 212,577 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
#!/usr/bin/env bash

# ----------------------------------------------------------------------------------------------------------------------------------
# Filename:      podget                                                                                                          {{{
# Maintainer:    Dave Vehrs (dvehrs on Github.com)
# Copyright:     (c) 2005-2025 Dave Vehrs
#
#                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 3 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.
#
# Description:   Podget is a simple bash script to automate the downloading and
#                organizing of podcast content.
# Dependencies:  bash, coreutils, findutils, grep, gawk or mawk, libc-bin (for iconv), sed, and wget.
# Installation:  cp podget.sh /usr/local/bin
#                chmod 755 /usr/local/bin/podget.sh                                                                              }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# Debug and Info messages                                                                                                        {{{

# To enable debugging or informational messages, add option to command line:
#
# $ INFO= podget   : Enable only Podget INFO messages.
# $ DEBUG=1 podget : Enable Podget INFO and DEBUG messages.
# $ DEBUG=2 podget : Enable Podget INFO and DEBUG messages with Bash shell option for xtrace.
# $ DEBUG=3 podget : Enable Podget INFO and DEBUG messages with Bash shell options for xtrace, and verbose.
# $ DEBUG=4 podget : Enable Podget INFO and DEBUG messages with Bash shell options for xtrace, functrace and a debug trap.
#
# NOTE: The output of the Bash shell options for verbose and the debug trap (as we have it configured) are effectively so similar
# that enabling both at the same time can be redundant and confusing.

# Default DEBUG Disabled (Deletion of temporary files allowed), configured
# to allow its setting to be overridden from the command line.
DEBUG=${DEBUG:-0}

# Default DEBUG string leader. This will be used until the user's configuration file (generally podgetrc) is read then if they have
# a custom string leader defined it will be used.
DEBUG_LEADER="DEBUG --"

# Default INFO string leader.
# If you want to customize this string, add its declaration to your user configuration file (generally podgetrc) like the one
# for DEBUG_LEADER
INFO_LEADER="INFO  --"

# Function: __MSG_DEBUG                                                                                                          {{{
# Display additional informational messages to user.
# General rules for use:
#  - For one part messages, the message to user should be less than 72 characters long to fit on one 80 character line.
#  - For two part messages, the first part can be up to 17 characters long and the second part can be up to 55 characters long to fit.
#  - These are very general rules because printf will not overlap sections when they are longer than they should be.  So you can
#    have a longer first part when the second is shorter and still fit on an 80 character line.  However things will line up best if
#    you follow these guidelines.
# ARGUMENTS:
# ${1} == One part message.
# ${2} == Second part of two part message.
__MSG_DEBUG() {
    local PART1="${1}"
    local PART2="${2:-UNConfigured}"
    # This looks a bit unusual but allows us to have a local variable that inherits it's value from when it is called.  Technically
    # the second part is the global value for the variable of name "DEBUG_LEADER" being assigned to local variable of the same name.
    local DEBUG_LEADER="${DEBUG_LEADER}"
    local DEBUG="${DEBUG}"

    # Test if INFO is set (may be empty string).
    if [[ "${DEBUG}" -gt 0 ]]; then
        if [[ "${PART2}" == "UNConfigured" ]]; then
            printf '%s %s\n' "${DEBUG_LEADER}" "${PART1}"
        else
            printf '%s %-20s : %s\n' "${DEBUG_LEADER}" "${PART1}" "${PART2}"
        fi
    fi
}
#                                                                                                                                }}}

# Function: __MSG_INFO                                                                                                           {{{
# Display additional informational messages to user.  Each message should be less that 57 Characters so that the whole line averages
# less than 80 characters (this limit is especially important for two part messages.
# ARGUMENTS:
# ${1} == One part message.
# ${2} == Second part of two part message.
__MSG_INFO() {
    local PART1="${1}"
    local PART2="${2:-UNConfigured}"
    # This looks a bit unusual but allows us to have a local variable that inherits it's value from when it is called.  Technically
    # the second part is the global value for the variable of name "INFO_LEADER" being assigned to local variable of the same name.
    local INFO_LEADER="${INFO_LEADER}"

    # Test if INFO is set (may be empty string).
    if [[ -n "${INFO+set}" ]]; then
        if [[ "${PART2}" == "UNConfigured" ]]; then
            printf '%s %s\n' "${INFO_LEADER}" "${PART1}"
        else
            printf '%s %-20s : %s\n' "${INFO_LEADER}" "${PART1}" "${PART2}"
        fi
    fi
}
#                                                                                                                                }}}

# NOTE:  We could use a simple test for if DEBUG is set or not, even without a value assigned but unfortunately we previously
#        used the values of 0 for disabled and 1 for enabled for other tests.  To keep backwards compatibility, we are going to
#        keep 0 as the default disabled value.  Therefore once we confirm DEBUG is set, we then need to test for values to know
#        which modes to enable.

if [[ -n "${DEBUG+set}" ]]; then
    if (( DEBUG >= 1 )); then
        echo "${DEBUG_LEADER} Level ${DEBUG} debugging enabled."
        INFO=1
        if (( DEBUG >= 2 )); then
            set -o xtrace
            if (( DEBUG == 3 )); then
                set -o verbose
            elif (( DEBUG >= 4 )); then
                # Enable functrace so that DEBUG and RETURN traps are inherited by functions.
                set -o functrace
                # NOTE: Debug trap sends it's output to STDERR (2) so that it does not
                #       cause errors during command substitutions ( $(..) or `..` ).
                #       This can happen when functrace is enabled.
                trap 'echo "DEBUG LINE ${LINENO}: ${BASH_COMMAND}" >&2' DEBUG

            fi
        fi
    fi
fi

#
#                                                                                                                                }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# Global Variables                                                                                                               {{{

# Default VERBOSITY
#  0 == silent
#  1 == Warning messages only.
#  2 == Progress and Warning messages.
#  3 == Debug, Progress and Warning messages.
#  4 == All messages and wget set to maximum VERBOSITY.
#  NOTE: Verbosity is not a local option because it is needed before and after core function runs. This is the global default but it
#        can be changed from within podgetcore generally by command line options.
VERBOSITY=2

#                                                                                                                                }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# Early Functions                                                                                                                {{{
# Note: These are functions that may be called by bash traps or other things that are configured sooner than the section for other
#       functions.  This should be kept as lean as possible.

# Function: CleanupAndExit                                                                                                     {{{
# Closes session and removes lock file (if it exists)
# ARGUMENTS:
# ${1} == Exit Status to report.
CleanupAndExit() {
    local EXITSTATUS=${1}
    local VERBOSITY="${VERBOSITY}"

    if (( VERBOSITY >= 2 )) ; then
        #echo -en "\nClosing session"
        printf '\n%s' "Closing session"
    fi
    if [[ -n ${DIR_SESSION+set} && -f ${DIR_SESSION}/podget.$$ ]]; then
        if (( DEBUG == 0 )); then
            if (( VERBOSITY >= 2 )) ; then
                printf '%s' " and removing lock file"
            fi
            if (( VERBOSITY >= 4 )) ; then
                echo
                rm -fv "${DIR_SESSION}"/podget.$$
            else
                rm -f "${DIR_SESSION}"/podget.$$
            fi
        else
            __MSG_DEBUG "Not deleting ${DIR_SESSION}/podget.$$"
        fi
    fi
    if (( (VERBOSITY >= 2) && (VERBOSITY <= 3) )); then
        printf '%s\n' "."
    elif (( (VERBOSITY == 1) || (VERBOSITY > 3) )); then
        echo
    fi

    exit "${EXITSTATUS}"
}
#                                                                                                                                }}}

# Function: ExitOnError                                                                                                           {{{
# The commands of this function will trigger Shellcheck SC2317 (Command appears to be unreachable)
# because the function is called from a trap so we can ignore this message.
# ARGUMENTS:
# ${1} == Line number the error happened on
# ${2} == Exit status of the error
# ${3} == If the error occurred in a function, the name of the function.
# shellcheck disable=SC2317
ExitOnError() {
  # Name of script
  local JOB_NAME
  JOB_NAME=$(basename "$0")
  # The following three variables are configured with a default value in case
  # the function is called without options set.
  local LINENUM="${1:-"Unconfigured"}"                   # Line with error
  local EXITSTATUS="${2:-"Unconfigured"}"                # exit status of error
  local FUNCTION="${3:-"Unconfigured"}"                  # If error occurred in a function, its name will be listed.

  printf '\n%s\n  %-15s %s\n' "Error:" "Script:" "${JOB_NAME}"

  # Function line only appears if it has been set to value other than the
  # default.  Works on the assumption that "Unconfigured" is not likely to be
  # chosen as a function name.
  if [[ ${FUNCTION} != "Unconfigured" ]]; then
      printf '  %-15s %s\n' "Function:" "${FUNCTION}"
  fi

  printf '  %-15s %s\n  %-15s %s\n' "At line:" "${LINENUM}" "Exit Status:" "${EXITSTATUS}"

  printf '\n%s\n' "Context:"
  # Test is awk installed, if so use it.  If not, then use tools from coreutils.
  if hash awk 2>/dev/null; then
      # This line works and adds a ">>>" to designate the offending line but adds
      # awk as a script dependency.
      awk 'NR>L-4 && NR<L+4 { printf "%-5d%3s%s\n",NR,(NR==L?">>>":""),$0 }' L="${LINENUM}" "${0}"
  else
      # This line works and only depends on coreutils
      pr -tn "${0}" | tail -n+$((LINENUM - 3)) | head -n7
  fi

  CleanupAndExit 1
}
#                                                                                                                                }}}

#                                                                                                                                }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# Exit Codes                                                                                                                     {{{

# "Reserved" Exit codes
# 1     General Error
# 2     Misuse of shell built-ins
# 126   Command invoked cannot execute
# 127   Command not found
# 128+n Invalid argument to exit
#   130   Script terminated by Control-C (128+2)
#   143   Script terminated by TERM signal (128+15)

# "Our" Exit codes

# Display Help (set to '0' because it is an valid exit condition, not an error.)
ERR_DISPLAYHELP=0

# Library directory not defined.
ERR_LIBNOTDEF=50

# Library directory available space below limit
ERR_LIBLOWSPACE=51

# Libc6 not installed.  Cannot convert UTF16 feeds.
ERR_LIBC6NOTINSTALLED=60

# Another running session already exists.
ERR_RUNNINGSESSION=70

# OPML import error.
ERR_IMPORTOPML=80

# OPML export error.
ERR_EXPORTOPML=90

#                                                                                                                                }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# Traps                                                                                                                          {{{

# FUNCNAME is declared with a default value in case the trap is triggered while
# outside a function.
trap 'ExitOnError ${LINENO} ${?} ${FUNCNAME:-Unconfigured}' ERR

# trap to run CLEANUP function if program receives a TERM (kill) or INT (ctrl-c) signal
# - CLEANUP called in line for other normal exits.
trap 'CleanupAndExit 143' TERM
trap 'CleanupAndExit 130' INT

#                                                                                                                                }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# Set Shell Options                                                                                                              {{{

set -o errexit
set -o nounset
set -o pipefail

# Enable errtrace so that the ERR trap is inherited by functions
set -o errtrace

# Enabling inheritance of errexit by command substitution subshells, this was added in Bash 4.4
#   NOTE:  Test command is run within a subshell where pipefail is disabled.
if (set +o pipefail && shopt inherit_errexit 2>&1 | grep -q invalid) ; then
    echo "Bash added the 'inherit_errexit' shell option in version 4.4, please upgrade."
    exit 1
fi
shopt -s inherit_errexit

# Enable extended glob matches.
shopt -s extglob

# Note: Limits on errexit functionality.
#
#       Important to remember that there are occasions that a script will not immediately exit when a command exits with a
#       non-zero status.  These conditions mostly make sense but can have an unexpected effect when there is an error in a function
#       that is called from an if statement.  For Podget, this was found working with a simulated error within the ArrayContains
#       function so even though the function inherited the errexit setting, it was ignored for reasons laid out in the man page.
#       For this reason, we should keep in mind that functions that are to be used in the ways that may cause errexit to be ignored
#       should be kept as concise and pithy as possible to reduce the opportunity for errors.
#
#       For functions with a command that may exit with a non-zero status that cannot be avoided then it may be necessary to add
#       manual checking for exit status after the command runs to determine if the script should stop or not.
#
#       Example of handling such a command:
#           Command-To-Run
#           if [ $? -ne 0 ]; then echo "ERROR"; exit 1; fi
#
# From Bash Man page on the set option for errexit (-e):
#    -e      Exit  immediately if a pipeline (which may consist of a single simple command), a list, or a compound command
#            (see SHELL GRAMMAR above), exits with a non-zero status.  The shell does not exit if the command that fails is part of
#            the command list immediately following a while or  until keyword,  part of the test following the if or elif reserved
#            words, part of any command executed in a && or || list except the command following the final && or ||, any command
#            in a pipeline but the last, or if the command's return value is being inverted with !.  If a compound command other
#            than a subshell returns a non-zero status because a command failed while -e was being ignored, the shell does not exit.
#            A trap  on ERR,  if  set, is executed before the shell exits.  This option applies to the shell environment and each
#            subshell environment separately (see COMMAND EXECUTION ENVIRONMENT above), and may cause subshells to exit before
#            executing all the commands in the subshell.
#
#            If a compound command or shell function executes in a context where -e is being ignored, none of the commands executed
#            within  the  compound command or function body will be affected by the -e setting, even if -e is set and a command
#            returns a failure status.  If a compound command or shell function sets -e while executing in a context where -e is
#            ignored, that setting will not have any effect until the  compound  command or the command containing the function
#            call completes.
#                                                                                                                                }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# Text for command line help option                                                                                              {{{

: << HELP_STEXT
    -c --config <FILE>           Name of configuration file to use.
    --create-config <FILE>       Exit immediately after creating configuration file.
    -C --cleanup                 Skip downloading and only run cleanup loop.
    --cleanup_simulate           Skip downloading and simulate running
                                 cleanup loop.
                                 Display files to be deleted.
    --cleanup_days <COUNT>       Number of days to retain files.  Anything
                                 older will be removed.
    -d --dir_config <DIRECTORY>  Directory that configuration files are
                                 stored in.
    --dir_session <DIRECTORY>    Directory that session files are stored in.
    -f --force                   Force download of items from each feed even
                                 if they have already been downloaded.
    --import_opml <FILE or URL>  Import servers from OPML file or
                                 HTTP/FTP URL.
    --export_opml <FILE>         Export serverlist to OPML file.
    --import_pcast <FILE or URL> Import servers from iTunes PCAST file or
                                 HTTP/FTP URL.
    -l --library <DIRECTORY>     Directory to store downloaded files in.
    -n --no-playlist             Do not create M3U playlist of new items.
    -p --playlist-asx            In addition to the default M3U playlist,
                                 create an ASX Playlist.  M3U playlist must be
                                 created to convert to ASX.
    --playlist-per-podcast       Create playlist of new items for each podcast feed.
    -r --recent <COUNT>          Download only the <count> newest items from
                                 each feed.
    --serverlist <LIST>          Serverlist to use.
    -s --silent                  Run silently (for cron jobs).
    --verbosity <LEVEL>          Set verbosity level (0-4).
    -v                           Set verbosity to level 1.
    -vv                          Set verbosity to level 2.
    -vvv                         Set verbosity to level 3.
    -vvvv                        Set verbosity to level 4.
    -h --help                    Display help.
HELP_STEXT

#                                                                                                                                }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# Text for default configuration files                                                                                           {{{

: << TEXT_DEFAULT_CONFIG
# ----------------------------------------------------------------------------------------------------------------------------------
# Podget configuration file created by version @VERSION@
# [ NOTE:  Do not delete version line as it will be used by future versions to
#          to test if configuration files have been updated with any required changes.
# ----------------------------------------------------------------------------------------------------------------------------------
# File name and location configuration:

# Name of Server List configuration file
CONFIG_SERVERLIST=@SERVERLIST@

# Directory to store session files
# If this option is not configured then by default podget will place the session files in the directory defined by TMPDIR/podget or
# if it is not defined in the users shell then the session files will be placed in the directory /tmp/podget.
# If you prefer a different location, then configure this variable.
# DIR_SESSION=@HOME@/tmp/podget

# Directory where to store downloaded files
DIR_LIBRARY=@HOME@/POD

# Directory to store logs in
# By default, logs are stored in DIR_LIBRARY/.LOG
# If you prefer a different location, then configure this variable.
# DIR_LOG=@HOME@/POD/LOG

# Set logging file names
LOG_FAIL=errors
LOG_COMPLETE=done

# ----------------------------------------------------------------------------------------------------------------------------------
# Download Options:

# Wget base options
# Commonly used options:
#   -c                          Continue interupted downloads - While this flag is commonly used there are feeds that it can
#                                   cause "403 Forbidden" errors.
#   -nH                         No host directories (overrides .wgetrc defaults if necessary)
#   --proxy=off                 To disable proxy set by environmental variable http_proxy
#   --no-check-certificate      To disable HTTPS certificate checks.  Useful for sites that may be using self-signed cerficates
#                                   and not those from a trusted service authority.
#   --prefer-family=IPv4/IPv6   When DNS provides a choice of addresses to connect to a host, attempt to connect to the specified
#                                   address family first.  If all addresses of the given family fail then the other family will be
#                                   tried.  If set to 'none' then the addresses will be tried in the order provided by the server
#                                   regardless of which family they are in (this is effectively the default option).
#
#                                   If you wish to force the use of IPv4 addresses only then you can use the "-4" or "--inet4-only"
#                                   options.  Conversely, if you want to force the use of IPv6 addresses then you can set the "-6"
#                                   or "--inet6-only" options.
#   --content-disposition       [EXPERIMENTAL FEATURE] Wget will look for and use "Content-Disposition" headers received from the
#                                   server.  This can result in extra round-trips to the server for a "HEAD" request.  This option
#                                   is useful for servers that use the "Content-Disposition" header to hold the filename of the
#                                   downloaded file rather than appending it to the URL.  This has the potential to make  some of
#                                   Podget's FILENAME_FORMATFIX options unneeded.
#
#                                   WARNING:  Enabling this flag disables any download progress information from being passed on to
#                                   the user.  To debug errors that may occur during sessions with this flag enabled, it may be
#                                   necessary to enable DEBUG and then examine the temporary files that are not deleted in
#                                   DIR_SESSION.
#
#                                   NOTE: This can be enable globally for all feeds here or if you want to enable it for only a few
#                                   specific feeds, you can add "OPT_CONTENT_DISPOSITION" to their line in your serverlist.
#   --user-agent=<string>           By default Podget will identify itself as "Podget".  If that does not work or you want to
#                                   specify a custom user agent you can do so here.  If the agent is a single word then it does not
#                                   need to be quoted.  If it is a longer string with spaces then it will need to be quoted and have
#                                   it's quotes double escaped.
#                                   Examples:
#                                     --user-agent=Mozilla
#                                     --user-agent=Chrome
#                                     --user-agent=\\\"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36\\\"
#                                     --user-agent=\\\"Agent 007\\\"
#                                     --user-agent=\\\"Dread Pirate Roberts\\\"
#
# Wget options that include spaces need to be surrounded in quotes.
#
# WGET_BASEOPTS="-c -nH --user-agent=\\\"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36\\\""
# WGET_BASEOPTS="-c -nH --user-agent=Mozilla"
# WGET_BASEOPTS="-c --proxy=off --no-check-certificate"
# WGET_BASEOPTS="-nH --proxy=off --content-disposition"
# WGET_BASEOPTS="-c --prefer-family=IPv4"
# WGET_BASEOPTS="-c --prefer-family=IPv6"
WGET_BASEOPTS="-c -nH"

# Most Recent
# 0  == download all new items.
# 1+ == download only the <count> most recent
MOST_RECENT=0

# Force
# 0 == Only download new material.
# 1 == Force download all items even those you've downloaded before.
FORCE=0

# Autocleanup of old playlists and the files they list.
# 0 == disabled
# 1 == delete any old content
CLEANUP=0

# Number of days to keep files.   Cleanup will remove anything
# older than this.
CLEANUP_DAYS=7

# Stop downloading if available space on the partition drops below value (in KB)
# default:  614400 (600MB)
MIN_SPACE=614400

# ----------------------------------------------------------------------------------------------------------------------------------
# Playlist Options:

# Disable playlist creation [ No need to comment out other playlist variables ]
# 0 == create
# 1 == do not create
NO_PLAYLIST=0

# Build playlists (comment out or set to a blank string to accept default format: New-).
PLAYLIST_NAMEBASE=New-

# Date format for new playlist names
# +%F        = YYYY-MM-DD  like 2014-01-15  (DEFAULT)
# +%m-%d-%Y  = MM-DD-YYYY  like 01-15-2014
# For other options 'man date'
#
# Date options that include spaces need to be surrounded in quotes.
#
DATE_FORMAT=+%F

# ASX Playlists for Windows Media Player
# 0 == do not create
# 1 == create
ASX_PLAYLIST=0

# ----------------------------------------------------------------------------------------------------------------------------------
# Filename Suffix:

# Add suffix to the filename of every file downloaded to allow for subsequent scripts to detect the newly downloaded files and work
# on them.  Examples of this would be scripts to run id3v2 to force a standard genre for all MP3 files downloaded or to use mp3gain
# to normalize files to have the same volume.
#
# A period (.) will automatically be added between the filename and tag like so:
#       filename.mp3.newtag
#
# Tags will not be added to filenames as they are added to the playlists.  It will be necessary for any script that you run to
# process the files remove the tag for the playlists to work.
#
# If this variable is undefined or commented out, then by default no suffix will be added.

# FILENAME_SUFFIX="newtag"

# ----------------------------------------------------------------------------------------------------------------------------------
# Downloaded Filename Cleanup Options:
#
# These options are for the filenames downloaded from the feeds.  We will try to clean then up rather than interrupting the script
# execution.

# Filename Cleanup: For FAT32 filename compatability (Feature Request #1378956)
# Tested with the following characters: !@#$%^&*()_-+=||{[}]:;"'<,>.?/
#
# The \`, \" and \\ characters need to be escaped with a leading backslash.
#
# Bad Character definitions need to be surrounded in quotes.
#
# NOTE: FILENAME_BADCHARS is also used to test for characters that commonly cause errors in directory names.  This can cause
# FILENAME_BADCHARS to be reported as part of an error for configuration issues with DIR_SESSION, DIR_LOG, DIR_LIBRARY and podcast
# FEED_NAME and FEED_CATEGORY.
FILENAME_BADCHARS="\`~!#$^&=+{}*[]:;\"'<>?|\\"

# Filename Replace Character: Character to use to replace any/all
# bad characters found.
FILENAME_REPLACECHAR=_

# When you run podget at a VERBOSITY of 3 or 4, it may appear that the filename format fixes are done out of order.  That is because
# they are named as they are created and as new fixes have been developed, those with more detailed exclusionary conditions have had
# to be done before those with more generic conditions.  Looking for improvements to fix this issue.

# Filename Cleanup 2:  Some RSS Feeds (like the BBC World News Bulletin)
# download files with names like filename.mp3?1234567.  Enable this mode
# to fix the format to filename1234567.mp3.
# 0 == disabled
# 1 == enabled (default)
FILENAME_FORMATFIX=1

# Filename Cleanup 3: Filenames of feeds hosted by LBC Plus corrupted.
# Fixed per MoonUnit's feature request (#1660764)
#
# Takes an URL that looks like:  http://lbc.audioagain.com/shared/audio/stream.mp3?guid=2007-03/14<...snip>
#                            <snip...>a7766e8ad2748269fd347eaee2b2e3f8&amp;source=podcast.php&amp;channel_id=88
#
# Which normally creates a file named: a7766e8ad2748269fd347eaee2b2e3f8&amp;source=podcast.php&amp;channel_id=88
#
# This fix extracts the date of the episode and changes the filename to 2007-03-14.mp3
# 0 == disabled
# 1 == enabled (default)
FILENAME_FORMATFIX2=1

# Filename Cleanup 4: Filenames of feeds hosted by CatRadio.cat need fixing.
# Fixed per Oriol Rius's Bug Report (#1744705)
#
# Downloaded filenames look like: 1189153569775.mp3?programa=El+mat%ED+de+Catalunya+R%E0dio&amp;podcast=y
# This fix removes everything after the .mp3
#
# NOTE: Testing in 2017 reveals changes in CatRadio's URL format that hampers this fix.
#
# Downloaded filenames now look like:  1487257264030.mp3&programa=Bon+dia%2C+malparits%21&var10=Neix+%2BCatR%E0dio%2C+el+dial+digital+de+Catalunya+R%E0dio&var11=video&var15=1783&var20=Podcast&var29=Audio&var3=951439&var14=951439&v25=Catalunya+R%E0dio&var19=16/02/17&var12=Tall&var18=45194
#
#   Two changes cause issues:
#     1.  Change of '?' to '&' for designating options.
#     2.  Use of forward slashes in date (var19) mess up some of our other filename extraction.
#
# However the fix for these podcasts is now simpler.  If in our serverlist, we use either
# the OPT_FILENAME_LOCATION or OPT_CONTENT_DISPOSTION option for these feedlists then the
# filename will be correctly extracted.  This leaves us with a long number as the filename,
# however if we also enable the OPT_FILENAME_RENAME_MDATE option then the filename is prefixed
# with the last modification date of the file which helps list the files in an order that
# makes sense.
#
# 0 == disabled (default)
# 1 == enabled
FILENAME_FORMATFIX3=0

# Filename Cleanup 5:  When the filename is part of the URL and the actual filename stays the same for
# all items listed.
#
# Download URLs look like: http://feeds.theonion.com/~r/theonion/radionews/~5/213589629/podcast_redirect.mp3
# Where 213589629 is the unique filename.
#
# This filename change is disabled by default because it may cause unintended changes to the filename.
#
# 0 == disabled (default)
# 1 == enabled
FILENAME_FORMATFIX4=0

# Filename Cleanup 6: Remove "?referrer=rss" from the end of filenames as included in some feeds like
# those from Vimcasts.org.  Setup to work for MP3, M4V, OGG and OGV files.
#
# Feed URLs: http://vimcasts.org/feeds/ogg
#            http://vimcasts.org/feeds/quicktime
#
# In the feed, enclosure URLs look like: http://media.vimcasts.org/videos/1/show_invisibles.ogv?referrer=rss
#
# 0 == disabled
# 1 == enabled (default)
FILENAME_FORMATFIX5=1

# Filename Cleanup 7:  Removes the trailing part of the filename after the '?'.
# Fixed at the request of Joerg Schiermeier
#
# For dealing with enclosures like those formatted in the ZDF podcast.
# Feed URL: http://www.zdf.de/ZDFmediathek/podcast/1193018?view=podcast
# Example enclosure:
# http://podfiles.zdf.de/podcast/zdf_podcasts/101103_backstage_afo_p.mp4?2010-11-03+06-42
#
# 0 == disabled
# 1 == enabled (default)
FILENAME_FORMATFIX6=1

# Filename Cleanup 8:
# This fix is for feeds that assign the same filename to be downloaded for each
# enclosure and then embedded the actual filename of the object to be saved in
# the media_url= parameter.  This fix extracts that name and uses it for the
# saved file.
#
# 0 == disabled
# 1 == enabled (default)
FILENAME_FORMATFIX7=1

# Filename Cleanup 9:
# This fix is for feeds like Smodcast.  It removes the "?client_id=<string>"
# from the end of each enclosure url in the feed.
#
# NOTE:  To fully fix the filenames on feeds like Smodcast, this fix should
# be used in conjunction with FILENAME_FORMATFIX4.
#
# Example URL: http://api.soundcloud.com/tracks/62837276/stream.mp3?client_id=a427c512429c9c90e58de7955257879c
# Fixed filename: 62837276_stream.mp3
#
# 0 == disabled
# 1 == enabled (default)
FILENAME_FORMATFIX8=1

# Filename Cleanup 10:
#
# This is a fix for podcast feeds formatted like those for Audioboo.  Removes everything after the ?
# in the filename.  Attempted to make this fix generic enough to work with a variety of feeds of mp3, mp4,
# ogg and ogv files.
#
# Feed URL: http://audioboo.fm/users/39903/boos.rss
# Example URL: http://audioboo.fm/boos/1273271-mw-123-es-wird-fruhling.mp3?keyed=true&amp;source=rss
# Fixed Filename: 1273271-mw-123-es-wird-fruhling.mp3
#
# NOTE: On Aug 30 2018, this fix was updated to also fix feeds formated like those from viertausendhertz.de.
#
# Feed URL: http://viertausendhertz.de/feed/podcast/systemfehler
# Example URL: https://viertausendhertz.de/podcast-download/1538/sf04.mp3?v=1470947681&#038;source=feed
# Fixed Filename: sf04.mp3
#
# 0 == disabled
# 1 == enabled (default)
FILENAME_FORMATFIX9=1

# Filename Cleanup 11:
#
# This is an attempt to fix feeds hosted on Apple ITunes.  The enclosure URL from these feeds defines the
# the filename as a long string of numbers and letter.  It's not very descriptive.  However, after the
# filename and a '?', in the information passed down to the application as part of the URL, we can
# extract the episode name for each podcast.  It is that name that this fix will use for the filename,
# with a few character replacements to insure good filenames.
#
# 0 == disabled
# 1 == enabled (default)
FILENAME_FORMATFIX10=1

# ----------------------------------------------------------------------------------------------------------------------------------
# DEBUG
#
# Enabling debug will:
#   1. Stop podget from automatically deleting some temporary files in DIR_SESSION.
#   2. Enable additional messages to track progress.
#
# 0           == disabled (default)
# 1           == enabled
# ${DEBUG:-0} == Sets DEBUG to disabled if it is not already set.  This allows the user to enabled it
#                from the command line with "DEBUG=1 podget"
#
#DEBUG=${DEBUG:-0}

# ----------------------------------------------------------------------------------------------------------------------------------
TEXT_DEFAULT_CONFIG

: << TEXT_DEFAULT_SERVERLIST
# Default Server List for podget
#
# Default format with category and name:
#   <url> <category> <name>
#
# Alternate Formats:
#   1. With a category but no name.
#       <url> <category>
#   2. With a name but no category (2 ways).
#       <url> No_Category <name>
#       <url> . <name>
#   3. With neither a category or name.
#       <url>
#
# For additional formating documentation, please refer to 'man podget'.
#
#FEEDS:
# ----------------------------------------------------------------------------------------------------------------------------------
# Using TITLES from Feed:
http://thelinuxlink.net/tllts/tllts.rss LINUX The Linux Link OPT_FILENAME_RENAME_TITLETAG

TEXT_DEFAULT_SERVERLIST

: << TEXT_ASX_BEGINNING
<ASX version = "3.0">
        <PARAM NAME = "Encoding" VALUE = "UTF-8" />
        <PARAM NAME = "Custom Playlist Version" VALUE = "V1.0 WMP8 for CE" />
TEXT_ASX_BEGINNING

: << TEXT_ASX_END
</ASX>
TEXT_ASX_END

#                                                                                                                                }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# Functions                                                                                                                      {{{
#   NOTE: For consistency, function names should be in what is called Pascal Case.  This is a variation of Camel Case but the first
#         letter of the first word is also capitalized.

# Function: ArrayContains                                                                                                       {{{
# Test if Array contains element.
# Returns 0 if found, or 1 if not found.
# ARGUMENTS:
# ${1} == String to search for
# ${2} == Array to search within (also called ${@:2})
# NOTE: ArrayContains will not respect the errexit shell option because it is generally called from an if statement.  So best to
#       keep functions like this pithy.
ArrayContains() {
    local element
    for element in "${@:2}"; do [[ "${element}" =~ ^"${1}".* ]] && return 0; done
    return 1
}
#                                                                                                                                }}}

# Function: CompareStringInString                                                                                               {{{
# The commands of this function will trigger Shellcheck SC2317 (command appears to be unreachable)
# because I never actually use this function but keep it here for historical reasons.
# ARGUMENTS:
# ${1} == String to compare to
# ${2} == Substring to look for in first string
# shellcheck disable=SC2317
CompareStringInString() {
    echo "Enter Compare ..."
    echo "1 == ${1}"
    echo "2 == ${2}"
    case "${2}" in
        *"${1}" )
            echo "Found!"
            return 0
            ;;
    esac
    return 1
}
#                                                                                                                                }}}

# Function: DisplayShortHelp                                                                                                   {{{
# Displays general message with command line options.
# ARGUMENTS: <none>
DisplayShortHelp() {
	echo; echo "Usage $0 [options]"; echo
	sed --silent -e '/HELP_STEXT$/,/^HELP_STEXT/p' "$0" | sed -e '/HELP_STEXT/d'
}
#                                                                                                                                }}}

# Function: DirectoryCheck                                                                                                      {{{
# Simple function to verify that unsafe characters are not used in directory names.
# ARGUMENTS:
# ${1} == Name of Variable to be tested
DirectoryCheck() {
    # Variables have a default value of 'UNCONFigured' because this word and combination
    # of capitalization is unlikely to be used.  This allows us to catch improperly
    # formated calls to DirectoryCheck.
    #
    # Uses variable indirection,  The '!' introduces indirection which can be read
    # to say "Get the value of the variable named this".
    local TEST_STRING=${!1:-"UNCONFigured"}
    # The second use simply reports the name of the variable to be tested.
    local TEST_VARIABLE=${1:-"UNCONFigured"}
    local TEST_FAIL=0
    local OFFENDING_CHARS=""

    if [[ ${TEST_STRING} == "UNCONFigured" ]]; then
        echo "Improperly formated call to DirectoryCheck."
        return 1
    fi

    # Test if FILENAME_BADCHARS is configured, if it is then check filenames to
    # prevent the use of disallowed characters.
    if [[ -n ${FILENAME_BADCHARS+set} ]]; then
        for (( i=0; i<${#FILENAME_BADCHARS}; i++ )); do
            local TEST_CHAR=${FILENAME_BADCHARS:$i:1}

            # Grep looks for --fixed-strings so that certain characters are not
            # interpreted as regular expressions (like ^ $ or /)
            if grep --quiet --fixed-strings "${TEST_CHAR}" <<<"${TEST_STRING}"; then
                OFFENDING_CHARS="${OFFENDING_CHARS}${TEST_CHAR}"
                # This test must come first because it will set TEST_FAIL to 1 regardless
                # of how many offending characters are found.  Given that this test can be
                # reported multiple times, we do not want it to cause additional suggestions
                # to be given to the user below.
                TEST_FAIL=1
            fi
        done

        unset -v i
    fi

    # consult Shellcheck SC2076 for why I choose this construct rather than using regex (=~) checks
    if [[ ${TEST_STRING} = *"../"* ]]; then
        TEST_FAIL=$((TEST_FAIL+2))
    fi

    if [[ ${TEST_STRING} = *"*"* ]]; then
        TEST_FAIL=$((TEST_FAIL+4))
    fi

    # This test will create duplicate suggestions as the back-slash character also appears in
    # the default FILENAME_BADCHARS.
    if [[ ${TEST_STRING} = *"\\000"* ]]; then
        TEST_FAIL=$((TEST_FAIL+8))
    fi

    if (( TEST_FAIL != 0 )); then
        echo "DIRECTORY CHECK ERROR: ${TEST_VARIABLE} = ${TEST_STRING}"

        echo
        echo "Suggestion(s):"
        local COUNT=0
        while (( TEST_FAIL != 0 )); do
            if (( (8<=TEST_FAIL) && (TEST_FAIL<=150) )); then
                COUNT=$((COUNT+1))
                # Shellcheck does not like the backslash being escaped here as part of an echo statement (SC2028)
                # There is an open issue on github for it but some people think it is appropriate as "info".
                #   (https://github.com/koalaman/shellcheck/issues/2486)
                #
                # Attempting to use printf here as recommended by Shellcheck.  Seems unnecessary but that's how
                # the game is played.
                printf "  %s. '\\000' cannot be used in directory names as mkdir expects\n" "${COUNT}"
                # echo "  ${COUNT}. '\\000' cannot be used in directory names as mkdir expects"
                printf "     to get a null terminated string and '\\000' is considered 'end of string'.\n"
                # echo "     to get a null terminated string and '\\000' is considered 'end of string'."

                if (( TEST_FAIL >= 8 )); then
                    TEST_FAIL=$((TEST_FAIL-8))
                fi
            elif (( (4<=TEST_FAIL) && (TEST_FAIL<=7) )); then
                COUNT=$((COUNT+1))
                echo "  ${COUNT}. The asterisk should not be used in directories as they are commonly used"
                echo "     to designate a wild card for expansion in Bash variables."
                if (( TEST_FAIL >= 4 )); then
                    TEST_FAIL=$((TEST_FAIL-4))
                fi
            elif (( (2<=TEST_FAIL) && (TEST_FAIL<=3) )); then
                COUNT=$((COUNT+1))
                echo "  ${COUNT}. Directories should not contain two periods and a slash in conjunction."
                echo "     If you need to save certain files outside of the Podcast Library directory,"
                echo "     defined by this podgetrc, the proper solution is to create a second podgetrc"
                echo "     with the new library location defined and to run podget with the --config"
                echo "     command line option to designate the podgetrc file to use."
                if (( TEST_FAIL >= 2 )); then
                    TEST_FAIL=$((TEST_FAIL-2))
                fi
            elif ((1==TEST_FAIL)); then
                COUNT=$((COUNT+1))
                echo "  ${COUNT}. Attempts to use characters disallowed by FILENAME_BADCHARS."
                echo "     Either remove the offending characters from the configured directory"
                echo "     or FILENAME_BADCHARS."
                echo "       Configured characters not allowed:  ${FILENAME_BADCHARS}"
                echo "       Offending character(s):             ${OFFENDING_CHARS}"
                if (( TEST_FAIL >= 1 )); then
                    TEST_FAIL=$((TEST_FAIL-1))
                fi
            fi
        done
        if [[ ${TEST_VARIABLE} == "FEED_NAME" || ${TEST_VARIABLE} == "FEED_CATEGORY" ]]; then
            return 1
        else
            CleanupAndExit 1
        fi
    fi

}
#                                                                                                                                }}}

# Function: FilenameCheck                                                                                                       {{{
# This function tests the filenames used by podget locally for various configuration and log files.  While these checks have
# some similarity to those applied to downloaded files the major difference is that violations of these rules will interrupt
# the execution of podget and podget will attempt to fix the other filenames but many not always succeed.
# Arguments:
# {1} == Name of Variable to be tested
FilenameCheck() {
    # Variables have a default value of 'UNCONFigured' because this word and combination
    # of capitalization is unlikely to be used.  This allows us to catch improperly
    # formated calls to FilenameCheck.
    #
    # Uses variable indirection,  The '!' introduces indirection which can be read
    # to say "Get the value of the variable named this".
    local TEST_STRING=${!1:-"UNCONFigured"}
    # The second use simply reports the name of the variable to be tested.
    local TEST_VARIABLE=${1:-"UNCONFigured"}
    local TEST_FAIL=0
    local OFFENDING_CHARS=""

    if [[ ${TEST_STRING} == "UNCONFigured" ]]; then
        echo "Improperly formated call to FilenameCheck."
        return 1
    fi

    # Test if FILENAME_BADCHARS is configured, if it is then check filenames to
    # prevent the use of disallowed characters.
    if [[ -n ${FILENAME_BADCHARS+set} ]]; then
        for (( i=0; i<${#FILENAME_BADCHARS}; i++ )); do
            local TEST_CHAR=${FILENAME_BADCHARS:$i:1}

            # Grep looks for --fixed-strings so that certain characters are not
            # interpreted as regular expressions (like ^ $ or /)
            if grep --quiet --fixed-strings "${TEST_CHAR}" <<<"${TEST_STRING}"; then
                OFFENDING_CHARS="${OFFENDING_CHARS}${TEST_CHAR}"
                # This test must come first because it will set TEST_FAIL to 1 regardless
                # of how many offending characters are found.  Given that this test can be
                # reported multiple times, we do not want it to cause additional suggestions
                # to be given to the user below.
                TEST_FAIL=1
            fi
        done

        unset -v i
    fi

    if [[ -z ${TEST_STRING##*/*} ]]; then
        # First test remove PATH from TEST_FILENAME variable.
        local TEST_DIRECTORY="${TEST_STRING%/*}"
        local TEST_FILENAME="${TEST_STRING##*/}"

        if [[ -n "${TEST_DIRECTORY}" ]]; then
            TEST_FAIL=$((TEST_FAIL+2))
        fi

        # Remove directory from string to be tested for following tests.
        TEST_STRING=${TEST_FILENAME}
    fi

    # Configuration files should not be hidden by leading periods and trailing periods can cause issues on some file systems or
    # operating systems.  Test if filename begins or ends with a period (.)
    if [[ ${TEST_STRING:0:1} == "." || ${TEST_STRING:(-1):1} == "." ]]; then
        TEST_FAIL=$((TEST_FAIL+4))
    fi


    if (( TEST_FAIL != 0 )); then
        echo

        case "${TEST_VARIABLE}" in
            "CONFIG_CORE"       )
                echo "Configuration filename specified by -c or --create-config violates the following rules..."
                ;;
            "CMDL_SERVERLIST"   )
                echo "Serverlist filename specified by --serverlist violates the following rules..."
                ;;
            "CONFIG_SERVERLIST" )
                echo "Default Serverlist filename violates the following rules..."
                ;;
            "LOG_FAIL"          )
                echo "LOG_FAIL defined in ${CONFIG_CORE} violates the following rules..."
                ;;
            "LOG_COMPLETE"      )
                echo "LOG_COMPLETE defined in ${CONFIG_CORE} violates the following rules..."
                ;;
            *                   )
                echo "${TEST_VARIABLE} violates the following rules..."
                ;;
        esac

        echo
        echo "Suggestion(s):"
        COUNT=0
        while (( TEST_FAIL != 0 )); do
            case ${TEST_FAIL} in
                # Included as an example of how other errors could be added with
                # a binary progression for the values they add to TEST_FAIL.
                [4-7])
                    COUNT=$((COUNT+1))
                    echo "  ${COUNT}. Remove leading or trailing period from ${TEST_STRING}"
                    if (( TEST_FAIL > 1 )); then
                        TEST_FAIL=$((TEST_FAIL-4))
                    fi
                    ;;
                [2-3])
                    COUNT=$((COUNT+1))
                    echo "  ${COUNT}. Filenames should not include any directory configuration."
                    echo "     Remove the directory configuration."
                    case "${TEST_VARIABLE}" in
                        "CONFIG_CORE" | "CMDL_SERVERLIST" | "CONFIG_SERVERLIST" )
                            echo "     If you need to specify a directory other than the default,"
                            echo "     use the -d or --dir_config command line options."
                            ;;
                        "LOG_FAIL" | "LOG_COMPLETE" )
                            echo "     If you wish to specify another location to store the logs,"
                            echo "     then configure the DIR_LOG variable in your ${CONFIG_CORE}"
                            ;;
                    esac

                    if (( TEST_FAIL >= 2 )); then
                        TEST_FAIL=$((TEST_FAIL-2))
                    fi
                    ;;
                1)
                    COUNT=$((COUNT+1))
                    echo "  ${COUNT}. Attempts to use characters disallowed by FILENAME_BADCHARS."
                    echo "     Either remove the offending characters from the configured directory"
                    echo "     or FILENAME_BADCHARS."
                    echo "       Configured characters not allowed:  ${FILENAME_BADCHARS}"
                    echo "       Offending character(s):             ${OFFENDING_CHARS}"
                    if (( TEST_FAIL >= 1 )); then
                        TEST_FAIL=$((TEST_FAIL-1))
                    fi
                    ;;
            esac
        done

        CleanupAndExit 1
    fi
}
#                                                                                                                                }}}

# Function: FilenameFixFormat                                                                                                    {{{
# Cleans up filenames in several ways.  Each method can be enabled or disabled individually in podgetrc file.
# Arguments:
# ${1} == name of variable to hold return string
# ${2} == string to fix the format of
FilenameFixFormat() {
    # variable to hold returned value.
    local VAR_RETURN=${1}

    # Filename to be modified.
    # Set original value for filename format fixes and character substitutions.
    # Set according to what is passed as the second argument to function.
    local MODIFIED_FILENAME=${2}

    # ORIGINAL and MODIFIED start out the same.
    local ORIGINAL_FILENAME="${MODIFIED_FILENAME}"


    if [[ -n ${FILENAME_FORMATFIX+set}  || -n ${FILENAME_FORMATFIX2+set} || -n ${FILENAME_FORMATFIX3+set} ||
          -n ${FILENAME_FORMATFIX4+set} || -n ${FILENAME_FORMATFIX5+set} || -n ${FILENAME_FORMATFIX6+set} ||
          -n ${FILENAME_FORMATFIX7+set} || -n ${FILENAME_FORMATFIX8+set} || -n ${FILENAME_FORMATFIX9+set} ||
          -n ${FILENAME_FORMATFIX10+set} ]]; then
       __MSG_INFO "ORIGINAL FILENAME" "${ORIGINAL_FILENAME}"
    fi

    # Note:  Filename format fixes that have more specific conditions come first.  More generic last.  This is
    # because a fix with too liberal a condition can prevent a more specific fix from running.  Fixes are named in
    # the order they were created, so it may appear that they are out of order.  By changing the order that they are
    # executed in, it is possible to have more enabled by default.
    #
    # TODO: Create exclusionary conditions for the fixes that are out of order to restore sanity to this list.
    #
    # FILENAME_FORMATFIX has been moved to the end of the order.
    #
    # FILENAME_FORMATFIX4 is not part of this function and is called immediately after this function ends.

    # Filename format fix for podcasts hosted on http://lbc.audioagain.com.
    if [[ -n ${FILENAME_FORMATFIX2+set} ]] && (( FILENAME_FORMATFIX2 > 0 )); then
        if [[ "${MODIFIED_FILENAME}" =~ [0-9a-zA-Z]+[\&]amp\;source=podcast.php[\&]amp\;channel_id=[0-9]+$ ]]; then
            MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed 's/.*stream.mp3[?]guid=\([0-9]\+\)-\([0-9]\+\)\/\([0-9]\+\)\/.*/\1-\2-\3.mp3/')
            __MSG_INFO "FILENAME FORMAT(2) FIXED: ${MODIFIED_FILENAME}"
        fi
    fi


    # Filename format fix for podcasts hosted on http://www.catradio.cat
    if [[ -n ${FILENAME_FORMATFIX3+set} ]] && (( FILENAME_FORMATFIX3 > 0 )); then
        if [[ "${MODIFIED_FILENAME}" =~ [0-9]+\.mp3[?][\&]programa=[0-9a-Z+-=%\&\;]+$ ]]; then
            # shellcheck disable=SC2001
            MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed 's/\(.*\)\.mp3\(.*\)/\1\.mp3/g')
            __MSG_INFO "FILENAME FORMAT(3) FIXED: ${MODIFIED_FILENAME}"
        fi
    fi

    # Remove "?referrer=rss" from filename as included with some feeds like Vimcasts.org
    if [[ -n ${FILENAME_FORMATFIX5+set} ]] &&  (( FILENAME_FORMATFIX5 > 0 )); then
        if [[ "${MODIFIED_FILENAME}" =~ [0-9a-zA-Z_]+\.[agmopv34]+[?]referrer=rss$ ]]; then
            MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed -r 's/([-A-Za-z0-9_]+.[agmopv34]+)[?]referrer=rss/\1/g')
            __MSG_INFO "FILENAME FORMAT(5) FIXED: ${MODIFIED_FILENAME}"
        fi
    fi

    # ZDF podcast filename fix
    if [[ -n ${FILENAME_FORMATFIX6+set} ]] && (( FILENAME_FORMATFIX6 > 0 )); then
        if [[ "${MODIFIED_FILENAME}" =~ [-_0-9a-zA-Z]+\.[agmopv34]+[?][-_+0-9]+$ ]]; then
            MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed -ru 's/([-_A-Za-z0-9]+.[agmopv34]+)[?][-+0-9]*/\1/g')
            __MSG_INFO "FILENAME FORMAT(6) FIXED: ${MODIFIED_FILENAME}"
        fi
    fi

    # media_url cleanup
    # This fix was inspired by the Radio France podcast feed.  Each enclosure URL in the feed had the same filename
    # specified to be downloaded, and the actual filename of the MP3 file was appended in the media_url variable.
    # This fix extracts that filename and uses it for the downloaded file.
    #
    # Filename consists of: numbers, letters, dashes, underscore, plus, percent, equals, question mark, ampersand, and period
    # with extended regex and buffers limited
    # wget -O - http://radiofrance-podcast.net/podcast09/rss_12036.xml | grep enclosure | sed -ru 's/.*(media_url=.*[.][gmopv34]+)"\ .*/\1/' | sed -ru 's/.*%2F([-0-9A-Za-z_.]+[.][gmopv34]+)/\1/'
    if [[ -n ${FILENAME_FORMATFIX7+set} ]] && (( FILENAME_FORMATFIX7 > 0 )); then
        if [[ "${MODIFIED_FILENAME}" =~ [+_%\&=?.0-9a-zA-Z]*media_url=http ]]; then
            MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed -ru 's/.*(media_url=http.*[.][agmopv34]+)"\ .*/\1/' | sed -ru 's/.*%2F([-0-9A-Za-z_.]+[.][agmopv34]+)/\1/')
            __MSG_INFO "FILENAME FORMAT(7) FIXED: ${MODIFIED_FILENAME}"
        fi
    fi

    # SMODCAST cleanup
    # Remove "?client_id=<string>" from filename.
    #
    # Note: This is only the first part of the cleanup needed for the SMODCAST feeds.  These removes the trailing portion of the
    # enclosure URL but every filename is left as "stream.mp3".  The distinguishing part of each URL is held one segment before the
    # filename and so FILENAME_FORMATFIX4 must also be enabled.  This can potentially affect other feeds and so it may be desirable
    # to separate these feeds to their own configuration and serverlist files.  They can then be loaded by using the -c and
    # --serverlist flags on the command line.
    if [[ -n ${FILENAME_FORMATFIX8+set} ]] && (( FILENAME_FORMATFIX8 > 0 )); then
        if [[ "${MODIFIED_FILENAME}" =~ stream\.mp3[?]client_id=[0-9a-zA-Z]\\+ ]]; then
            MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed -ru 's/(stream[.]mp3)[?]client_id=[0-9A-Za-z]+/\1/')
            __MSG_INFO "FILENAME FORMAT(8) FIXED: ${MODIFIED_FILENAME}"
        fi
    fi

    # Audioboo Filename Cleanup.
    # Enclosure URLs have "?keyed=true&amp;source=rss" appended to them.  This fix removes that string.
    # It should work for Audioboo podcasts and others with similar formating.
    if [[ -n ${FILENAME_FORMATFIX9+set} ]] && (( FILENAME_FORMATFIX9 > 0 )); then
        if [[ "${MODIFIED_FILENAME}" =~ [-_0-9a-zA-Z]+[.][agmopv34]+[?][_%\&\;=0-9a-zA-Z]+ ]]; then
            MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed -ru 's/([-_A-Za-z0-9]+[.][agmopv34]+)[?][-_%&#;=A-Za-z0-9]+/\1/g')
            __MSG_INFO "FILENAME FORMAT(9) FIXED: ${MODIFIED_FILENAME}"
        fi
    fi

    # MP3 on Apple ITunes
    # Filenames are generally long strings of numbers and letters, with the actual episode name being defined after the '?'
    # This extracts the episode name and uses it for the filename.
    if [[ -n ${FILENAME_FORMATFIX10+set} ]] && (( FILENAME_FORMATFIX10 > 0 )); then
        if [[ "${MODIFIED_FILENAME}" =~ [-0-9A-Za-z_]+[.][MmPp3]+[?][-0-9A-Za-z%=]+%26episodeName%3D[-0-9A-Za-z%.*]+%26episodeKind%3D ]]; then
            MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed -ru 's/.*%26episodeName%3D([-._%A-Za-z0-9*]+)%26episodeKind[-%&;=A-Za-z0-9]+/\1.mp3/g' | sed -ru 's/%2B/_/g;s/%25[0-9ACF]{2}//g;s/[*]//g')
            __MSG_INFO "FILENAME FORMAT(10) FIXED: ${MODIFIED_FILENAME}"
        fi
    fi

    # Fix improperly formated filenames (fixes filename.mp3?123456 to filename123456.mp3)
    if [[ -n ${FILENAME_FORMATFIX+set} ]] && (( FILENAME_FORMATFIX > 0 )); then
        if [[ "${MODIFIED_FILENAME}" =~ .*\.mp3[?].*$ ]]; then
            # shellcheck disable=SC2001
            MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed 's/\.mp3\(.*\)/\1.mp3/')
            __MSG_INFO "FILENAME FORMAT FIXED: ${MODIFIED_FILENAME}"
        fi
    fi

    # Test if BADCHARS set by variable
    if [[ -n ${FILENAME_BADCHARS+set} ]] ; then
        # Test for BADCHARS in MODIFIED_FILENAME
        if [[ ${MODIFIED_FILENAME} =~ ["${FILENAME_BADCHARS}"] ]]; then
             # Two step process.  First modify any BADCHARS into the REPLACECHAR and then squeeze each repetition of the REPLACECHAR
             # down to a single time.
             MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | tr "${FILENAME_BADCHARS}" "${FILENAME_REPLACECHAR}" | tr -s "${FILENAME_REPLACECHAR}")
            __MSG_INFO "FILENAME FORMAT FIXED: ${MODIFIED_FILENAME}"
        fi
    fi

    if [[ "${ORIGINAL_FILENAME}" != "${MODIFIED_FILENAME}" ]]; then
        __MSG_INFO "MODIFIED FILENAME" "${MODIFIED_FILENAME}"
    fi

    # Pass the modified filename back to the calling variable.
#    eval "${VAR_RETURN}=${MODIFIED_FILENAME@Q}"
    printf -v "${VAR_RETURN}" '%s' "${MODIFIED_FILENAME}"

    # close without error
    return 0
}
#                                                                                                                                }}}

# Function: FilterOptions                                                                                                       {{{
# This takes each feed from a serverlist and selectively enables options specific to it.  Used for Feed Categories and Names.
# Arguments:
# ${1} == name of variable to filter on (either FEED_CATEGORY or FEED_NAME)
FilterOptions() {
    local FILTER_ITEM="${1}"

    # NOTE: The regex expressions in the following checks were updated so that
    #       they played nice on FreeBSD 12.1 with Bash 5.0.17.
    #
    #       Previously the regexes included:  (.*[[:space:]]|)
    #
    #       This would either look for the pattern after other parts or
    #       immediately at the beginning of the string.  It was the second part
    #       that caused issues, the part after the or but before the closing
    #       parenthesis. The blank part worked on Linux but not on FreeBSD.
    #
    #       To fix it, we changed to this:  (.+[[:space:]]|[[:space:]]?)

    # Extract Password from FILTER_ITEM if found.
    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)(PASS:)([^[:space:]]+).*$ ]]; then
        URL_PASSWORD="${BASH_REMATCH[3]}"
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/PASS:+([^[:space:]])}"
    fi

    # Extract USERNAME from FILTER_ITEM if found.
    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)(USER:)([^[:space:]]+).*$ ]]; then
        URL_USERNAME="${BASH_REMATCH[3]}"
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/USER:+([^[:space:]])}"
    fi

    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_CONTENT_DISPOSITION.*$ ]]; then
        WGET_OPTION_DISPOSITION=1
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_CONTENT_DISPOSITION}"
    fi

    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_DISPOSITION_FAIL.*$ ]]; then
        WGET_OPTION_DISPOSITION_FAIL=1
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_DISPOSITION_FAIL}"
    fi

    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_NO_CERT_CHECK.*$ ]]; then
        WGET_OPTION_NO_CHECK_CERIFICATE=1
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_NO_CERT_CHECK}"
    fi

    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_PREFER_IP[vV]4.*$ ]]; then
        WGET_OPTION_PREFER_IP_TYPE=4
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM//OPT_PREFER_IP[vV]4}"
    fi

    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_PREFER_IP[vV]6.*$ ]]; then
        WGET_OPTION_PREFER_IP_TYPE=6
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM//OPT_PREFER_IP[vV]6}"
    fi

    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_FEED_ORDER_ASCENDING.*$ ]]; then
        FEED_SORT_ORDER="ASCENDING"
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_FEED_ORDER_ASCENDING}"
    fi

    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_FEED_PLAYLIST_NEWFIRST.*$ ]]; then
        FEED_FULL_PLAYLIST=1
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_FEED_PLAYLIST_NEWFIRST}"
    fi

    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_FEED_PLAYLIST_OLDFIRST.*$ ]]; then
        FEED_FULL_PLAYLIST=2
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_FEED_PLAYLIST_OLDFIRST}"
    fi

    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_WGET_DEFUSERAGENT.*$ ]]; then
        WGET_OPTION_DEFAULT_USERAGENT=1
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_WGET_DEFUSERAGENT}"
    fi

    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_RSS_MEDIACONTENT.*$ ]]; then
        WGET_OPTION_RSS_MEDIACONTENT=1
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_RSS_MEDIACONTENT}"
    fi

    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_FILENAME_LOCATION.*$ ]]; then
        WGET_OPTION_FILENAME_LOCATION=1
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_FILENAME_LOCATION}"
    fi

    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_FILENAME_RENAME_MDATE.*$ ]]; then
        POST_WGET_RENAME_MDATE=1
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_FILENAME_RENAME_MDATE}"
    fi

    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_FILENAME_RENAME_TITLETAG.*$ ]]; then
        POST_WGET_RENAME_TITLETAG=1
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_FILENAME_RENAME_TITLETAG}"
    fi

    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_FILENAME_RENAME_REVTITLETAG.*$ ]]; then
        POST_WGET_RENAME_REVTITLETAG=1
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_FILENAME_RENAME_REVTITLETAG}"
    fi

    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)ATOM_FILTER_SIMPLE.*$ ]]; then
        ATOM_FILTER_SIMPLE=1
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/ATOM_FILTER_SIMPLE}"
    fi

    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)(ATOM_FILTER_TYPE=\"?)([^\" ]+).*$ ]]; then
        ATOM_FILTER_TYPE="${BASH_REMATCH[3]}"
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/ATOM_FILTER_TYPE=+([^[:space:]])}"
    fi

    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)(ATOM_FILTER_LANG=\"?)([^\" ]+).*$ ]]; then
        ATOM_FILTER_LANG="${BASH_REMATCH[3]}"
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/ATOM_FILTER_LANG=+([^[:space:]])}"
    fi

    # Remove repeated spaces
    printf -v "${FILTER_ITEM}" '%s' "$(tr -s ' ' <<< "${!FILTER_ITEM}")"

    # Remove any residual leading whitespace from ${!FILTER_ITEM}
    printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM#"${!FILTER_ITEM%%[![:space:]]*}"}"

    # Remove any residual trailing whitespace from ${!FILTER_ITEM}
    printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM%"${!FILTER_ITEM##*[![:space:]]}"}"

    # No_Category, or blank item handling.
    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)No_Category.*$ || -z "${!FILTER_ITEM-empty}" ]]; then
        # Set to single period which is a bashism for current directory.
        printf -v "${FILTER_ITEM}" '%s' '.'
    fi

    if [[ "${!FILTER_ITEM}" =~ ^.*%(YY|MM|DD)%.*$ ]]; then
        printf -v "${FILTER_ITEM}" '%s' "$(sed -e "s#%YY%#$(date +%Y)#" -e "s#%MM%#$(date +%m)#" -e "s#%DD%#$(date +%d)#" <<< "${!FILTER_ITEM}")"
    fi

}
#                                                                                                                                }}}

# Function: PlaylistConvertToASX                                                                                                 {{{
# This function converts a M3U playlist to ASX format.
# ARGUMENTS:
# ${1} == Directory that libraries are stored in
# ${2} == M3U Playlist name to convert
PlaylistConvertToASX() {
    local DIR_LIBRARY=${1}
    local M3U_PLAYLISTNAME=${2}
    ASX_LOCATION="\\SD Card\\POD\\"
    ASX_PLAYLISTNAME=$(basename "${DIR_LIBRARY}"/"${M3U_PLAYLISTNAME}" .m3u).asx
    sed --silent -e '/TEXT_ASX_BEGINNING$/,/^TEXT_ASX_BEGINNING/p' "$0" |
      sed -e '/TEXT_ASX_BEGINNING/d' > "${DIR_LIBRARY}"/"${ASX_PLAYLISTNAME}"

    while read -r line ; do
      local FIXED_ENTRY="${line//\//\\}"
      {
          echo '    <ENTRY>'
          echo "        <ref href = \"${ASX_LOCATION}${FIXED_ENTRY}\" />"
          echo "        <ref href = \".\\${FIXED_ENTRY}\" />"
          echo '    </ENTRY>'
      } >> "${DIR_LIBRARY}"/"${ASX_PLAYLISTNAME}"
    done < "${DIR_LIBRARY}"/"${M3U_PLAYLISTNAME}"

    sed --silent -e '/TEXT_ASX_END$/,/^TEXT_ASX_END/p' "$0" |
      sed -e '/TEXT_ASX_END/d' >> "${DIR_LIBRARY}"/"${ASX_PLAYLISTNAME}"

     # Removing unix2dos dependency. Converting to sed statement with in-place editing of the file in question.
     # ctrl-v ctrl-m for windows line end.
     sed -i 's/$/
/' "${DIR_LIBRARY}"/"${ASX_PLAYLISTNAME}"
}
#                                                                                                                                }}}

# Function: PlaylistSort                                                                                                        {{{
# ARGUMENTS:
# ${1} == Library directory that files are stored in.
# ${2} == M3U Playlist to sort.
PlaylistSort() {
    local -r DIR_LIBRARY=${1}
    local -r M3U_PLAYLISTNAME=${2}
    local REALPLAYLISTNAME="${DIR_LIBRARY}/$M3U_PLAYLISTNAME"

    # Sort Playlist
    unset -v TEMPPLAYLISTNAME
    local TEMPPLAYLISTNAME
    if hash mktemp >&2; then
        TEMPPLAYLISTNAME=$(mktemp 2>/dev/null)
    elif hash tempfile >&2; then
        # NOTE: The shellcheck warning for tempfile being depreciated is
        # disabled here because we are only using it for systems that do not
        # already have mktemp.  So realistically, it should almost never be called.
        # shellcheck disable=SC2186
        TEMPPLAYLISTNAME=$(tempfile 2>/dev/null)
    else
        echo "Error: Neither mktemp or tempfile found.  Unable to sort playlist."
        unset -v REALPLAYLISTNAME TEMPPLAYLISTNAME
        return
    fi

    # Convert Sort --output= option to -o for compatibility with NetBSD
    cp -p "$REALPLAYLISTNAME" "$TEMPPLAYLISTNAME" && sort -o "$REALPLAYLISTNAME" "$TEMPPLAYLISTNAME" && rm "$TEMPPLAYLISTNAME"
    # cp -p "$REALPLAYLISTNAME" "$TEMPPLAYLISTNAME" && sort --output="$REALPLAYLISTNAME" "$TEMPPLAYLISTNAME" && rm "$TEMPPLAYLISTNAME"

    unset -v REALPLAYLISTNAME TEMPPLAYLISTNAME
}
#                                                                                                                                }}}

# Function: PodgetBuildFeedPlaylist                                                                                              {{{
# Build M3U playlist for a single feed if it is configured to get them in the serverlist file.
# ARGUMENTS: <none>
PodgetBuildFeedPlaylist() {
    # If you're curious about why we doing what we do here, please refer to note on variable scope at end of file.
    local -r DIR_CONFIG="${DIR_CONFIG}"
    local -r CONFIG_SERVERLIST="${CONFIG_SERVERLIST}"
    local -r VERBOSITY="${VERBOSITY}"

    # Test if any feeds are configured to require individual playlists.  If none are configured to require them, skip this
    # section.
    # NOTE: filename globbing for the grep command is somewhat clunky because expansion does not happen within quotes.  Might be
    #       nice to find a more elegant way to state this.
    if grep --files-with-match --quiet --no-messages "OPT_FEED_PLAYLIST_\\(NEW\\|OLD\\)FIRST" "${DIR_CONFIG}/${CONFIG_SERVERLIST}"{.utf16,}; then
        __MSG_DEBUG "============================================================"
        __MSG_INFO "Build OPT_FEED_PLAYLISTs"
        # Set header to not be displayed unless active feed configured to require one.
        local FEED_PLAYLIST_HEADER=0

        local FILETYPE
        for FILETYPE in utf8 utf16 ; do
            if (( DEBUG >= 1 )) ; then echo; fi
            case ${FILETYPE} in
                'utf8')
                    __MSG_DEBUG "UTF-8 Loop running." ;;
                'utf16')
                    __MSG_DEBUG "UTF-16 Loop running." ;;
            esac
            local CURRENT_SERVERLIST
            case ${FILETYPE} in
                'utf8')
                    CURRENT_SERVERLIST="${DIR_CONFIG}"/"${CONFIG_SERVERLIST}" ;;
                'utf16')
                    CURRENT_SERVERLIST="${DIR_CONFIG}/${CONFIG_SERVERLIST}.utf16" ;;
                *)
                    echo "Unknown Filetype: ${FILETYPE}"
            esac

            if [[ ! -f ${CURRENT_SERVERLIST} ]]; then
                __MSG_DEBUG "No config file found, exiting loop."
                continue
            fi

            ### TODO: Need to find a way to shrink this.
            local FEED_URL
            local FEED_CATEGORY
            local FEED_NAME
            while read -r FEED_URL FEED_CATEGORY FEED_NAME ; do
                local FEED_FULL_PLAYLIST=0

                if   [[ "${FEED_URL:0:1}" == "#" ||  -z "${FEED_URL-empty}" ]] ; then
                    __MSG_DEBUG "Discarding (comment or blank line)."
                    __MSG_DEBUG "Clear Loop vars"
                    unset -v FEED_URL
                    unset -v FEED_CATEGORY
                    unset -v FEED_NAME
                    unset -v FEED_FULL_PLAYLIST
                    continue
                fi

                # ---------------------
                # Read Podcast configuration - loop to run same filters on FEED_CATEGORY and FEED_NAME

                unset -v FILTER_TARGET
                local FILTER_TARGET
                for FILTER_TARGET in FEED_CATEGORY FEED_NAME; do
                    FilterOptions "${FILTER_TARGET}"
                done

                # Unset options that are not required in this while loop
                unset -v URL_PASSWORD
                unset -v URL_USERNAME
                unset -v WGET_OPTION_DEFAULT_USERAGENT
                unset -v WGET_OPTION_DISPOSITION
                unset -v WGET_OPTION_DISPOSITION_FAIL
                unset -v WGET_OPTION_NO_CHECK_CERIFICATE
                unset -v WGET_OPTION_PREFER_IP_TYPE
                unset -v WGET_OPTION_FILENAME_LOCATION
                unset -v WGET_OPTION_RSS_MEDIACONTENT
                unset -v FEED_SORT_ORDER
                unset -v POST_WGET_RENAME_MDATE
                unset -v ATOM_FILTER_SIMPLE
                unset -v ATOM_FILTER_TYPE
                unset -v ATOM_FILTER_LANG

                if (( FEED_FULL_PLAYLIST >= 1 )) ; then
                    if (( FEED_PLAYLIST_HEADER == 0 )); then
                        if (( VERBOSITY == 1 )) ; then
                            printf '\n%s\n' "Build OPT_FEED_PLAYLISTs"
                        fi
                        if (( VERBOSITY >= 2 )) ; then
                            printf '\n%s\n%s\n' "-------------------------------------------------" "Build OPT_FEED_PLAYLISTs"
                        fi
                        # Increment header variable so it only displays once.
                        # NOTE: If we attempt to post-increment our variable, it will cause an error because of the way that '(('
                        # evaluates the expression.  When the result is zero, it exits with '1' triggering errexit, however if
                        # we pre-increment then the error does not happen.
                        # More examples: https://en.wikipedia.org/wiki/Increment_and_decrement_operators
                        (( ++FEED_PLAYLIST_HEADER ))
                    fi
                    if [ "${FEED_NAME}" == "." ]; then
                        if (( VERBOSITY >= 1 )); then
                            printf '%-30s %-50s\n' "" "No FEED_NAME, unable to create playlist for:"
                            printf '%-30s %-50s\n' "" "  ${FEED_URL}"
                        else
                            echo "No FEED_NAME, unable to create playlist for:"
                            echo "    ${FEED_URL}"
                        fi
                        continue
                    fi

                    # Date Substitutions
                    FEED_CATEGORY=$(echo "${FEED_CATEGORY}" | sed -e "s#%YY%#$(date +%Y)#" -e "s#%MM%#$(date +%m)#" -e "s#%DD%#$(date +%d)#" )

                    if (( VERBOSITY >= 2 )) ; then
                        printf '\n%s\n' "-------------------------------------------------"
                    fi
                    if (( VERBOSITY >= 1 )) ; then
                        if [ "${FEED_CATEGORY}" == "." ]; then
                            printf '%-30s %-50s\n' "Category: NONE" "Name: ${FEED_NAME}"
                        else
                            printf '%-30s %-50s\n' "Category: ${FEED_CATEGORY}" "Name: ${FEED_NAME}"
                        fi
                    fi

                    # Replace spaces with underscores and then pipe through tr to limit repetitions.
                    local FULL_PLAYLIST_NAME
                    FULL_PLAYLIST_NAME=$(echo "PLAYLIST_${FEED_NAME//[[:space:]]/_}.m3u" | tr -s _)
                    # Remove old full playlist.
                    if [ -f "${DIR_LIBRARY}/${FULL_PLAYLIST_NAME}" ]; then
                        if (( VERBOSITY >= 2 )) ; then
                            echo "Remove old playlist: ${FULL_PLAYLIST_NAME}"
                            rm "${DIR_LIBRARY}/${FULL_PLAYLIST_NAME}"
                        else
                            __MSG_INFO "Remove old playlist" "${DIR_LIBRARY}/${FULL_PLAYLIST_NAME}"
                            rm -f "${DIR_LIBRARY}/${FULL_PLAYLIST_NAME}"
                        fi
                    fi
                    if [[ -d "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}" ]]; then
                        # Build new full playlist.
                        if (( VERBOSITY >= 2 )); then
                            echo "Build new ${DIR_LIBRARY}/${FULL_PLAYLIST_NAME}"
                        else
                            __MSG_INFO "Build new playlist" "${DIR_LIBRARY}/${FULL_PLAYLIST_NAME}"
                        fi
                        local FEED_ITEMS
                        if (( FEED_FULL_PLAYLIST == 1 )); then
                            # Get list in order of newest to oldest
                            FEED_ITEMS=$(ls -1t "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/")
                        else
                            # Get list in order of oldest to newest
                            FEED_ITEMS=$(ls -1tr "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/")
                        fi
                        if [ -n "${FEED_ITEMS}" ]; then
                            local ITEM
                            while read -r ITEM; do
                                __MSG_DEBUG "FEED Full Playist add ${ITEM}"
                                # Added Sed statement to remove "./" (current directory) from each item added as necessary
                                echo "${FEED_CATEGORY}/${FEED_NAME}/${ITEM}" | sed -e 's|[.]/||g' >> "${DIR_LIBRARY}/${FULL_PLAYLIST_NAME}"
                            done <<< "${FEED_ITEMS}"
                            unset -v FEED_ITEMS
                            unset -v ITEM
                        else
                            if (( VERBOSITY >= 1 )); then
                                printf '%-30s %-50s\n' "" "No files, no playlist"
                            fi
                        fi
                    else
                        if (( VERBOSITY >= 1 )); then
                            printf '%-30s %-50s\n' "" "No directory, no playlist"
                        fi
                    fi

                fi

                unset -v FEED_URL
                unset -v FEED_CATEGORY
                unset -v FEED_NAME
                unset -v FEED_FULL_PLAYLIST
            done < "${CURRENT_SERVERLIST}"
        done
    fi
}
#                                                                                                                                }}}

# Function: PodgetCleanup                                                                                                        {{{
# Cleanup loop for PodgetCore function.  This loop removes any downloaded files older than CLEANUP_DAYS
# ARGUMENTS: <none>
PodgetCleanup() {
    # If you're curious about why we doing what we do here, please refer to note on variable scope at end of file.
    local -r VERBOSITY="${VERBOSITY}"
    local -r CLEANUP_SIMULATE="${CLEANUP_SIMULATE}"
    local -r DIR_LIBRARY="${DIR_LIBRARY}"
    local -r PLAYLIST_NAMEBASE="${PLAYLIST_NAMEBASE}"
    if (( VERBOSITY >= 2 )) ; then
        if (( CLEANUP_SIMULATE > 0 )); then
            echo "Simulating cleanup, the following files will be removed when you run cleanup."
        else
            printf '\n%s\n%s\n' "-------------------------------------------------" "Cleanup old tracks."
        fi
    else
        __MSG_DEBUG "============================================================"
        __MSG_INFO "Cleanup Old Tracks"
    fi
    FILELIST=$(find "${DIR_LIBRARY}"/ -maxdepth 1 -type f -name "*.m3u")
    # Convert CLEANUP_DAYS to CLEANUP_SECONDS (86400 == seconds in a day)
    local CLEANUP_SECONDS=$((CLEANUP_DAYS*86400))
    # Convert CLEANUP_SECONDS to date in seconds from unix epoch before midnight last night.
    # This works with uniform whole days and isn't subject to when the cleanup is run.
    local DATE_CLEAN2=$(($(date +%s --date 0:00)-CLEANUP_SECONDS))
    local FILE
    while IFS= read -r FILE; do
        # Catch for when FILELIST is blank
        if [[ -z "${FILE}" ]]; then
            continue
        fi
        if [[ "${FILE##/*/}" =~ ^${PLAYLIST_NAMEBASE}* ]]; then
            # Compare global playlist file modification date with DATE_CLEAN2.  If file modification date is newer than
            # DATE_CLEAN2 then we skip it.
            if [ "$(stat --format %Y "${FILE}")" -gt "${DATE_CLEAN2}" ]; then
                continue
            fi
        fi
        if (( VERBOSITY >= 2 )) ; then
            echo "Deleting tracks from ${FILE}:"
        else
            __MSG_INFO "Deleting Tracks" "From ${FILE}"
        fi
        local LINE
        while read -r LINE ; do
            if [[ -f "${DIR_LIBRARY}/${LINE}" ]]; then
                # Compare each file from the playlist with file modification date.  If file modification date is older than
                # DATE_CLEAN2 then we remove that file
                if [ "$(stat --format %Y "${DIR_LIBRARY}/${LINE}")" -lt "${DATE_CLEAN2}" ]; then
                    if (( CLEANUP_SIMULATE > 0 )); then
                        echo "File to remove:  ${DIR_LIBRARY}/${LINE}"
                    else
                        __MSG_INFO "Remove File" "${DIR_LIBRARY}/${LINE}"
                        rm -f "${DIR_LIBRARY}/${LINE}"
                    fi
                fi
            else
                if (( CLEANUP_SIMULATE > 0 )) ; then
                    __MSG_INFO "File not found" "${DIR_LIBRARY}/${LINE}"
                fi
            fi
        done < "${FILE}"
        if (( CLEANUP_SIMULATE > 0 )); then
            echo "Playlist to remove: ${FILE}"
        else
            __MSG_INFO "Remove Playlist" "${FILE}"
            rm -f "${FILE}"
        fi
    done <<<"${FILELIST}"
}
#                                                                                                                                }}}

# Function: PodgetExportOPML                                                                                                     {{{
# Displays general message with command line options.
# ARGUMENTS: <none>
PodgetExportOPML() {
    # If you're curious about why we doing what we do here, please refer to note on variable scope at end of file.
    local -r EXPORT_OPML="${1}"
    local -r VERBOSITY="${VERBOSITY}"
    local -r DIR_CONFIG="${DIR_CONFIG}"
    local -r CONFIG_SERVERLIST="${CONFIG_SERVERLIST}"
    local -r ERR_EXPORTOPML="${ERR_EXPORTOPML}"

    if [[ ${EXPORT_OPML} == "NONE" ]]; then
        echo
        echo "No file configured to export to."
        CleanupAndExit 1
    fi

    if (( VERBOSITY >= 2 )) ; then
        printf '\n%s\n' "Export serverlist to OPML file: ${EXPORT_OPML}"
    fi

    if [[ ! -e ${EXPORT_OPML} ]]; then
        printf '%s\n\t%s\n\t%s\n\t%s\n' '<?xml version="1.0" encoding="utf-8" ?>' '<opml version="1.0">' '<head/>' '<body>' > "${EXPORT_OPML}"

        local FEED_URL
        local FEED_CATEGORY
        local FEED_NAME
        local FEED_FULL_PLAYLIST
        while read -r FEED_URL FEED_CATEGORY FEED_NAME ; do
            if   [[ "${FEED_URL:0:1}" == "#" ||  -z "${FEED_URL-empty}" ]] ; then
                __MSG_DEBUG "Discarding (comment or blank line)."
                __MSG_DEBUG "Clear Loop vars"
                unset -v FEED_URL
                unset -v FEED_CATEGORY
                unset -v FEED_NAME
                unset -v FEED_FULL_PLAYLIST
                continue
            fi

            # ---------------------
            # Read Podcast configuration - loop to run same filters on FEED_CATEGORY and FEED_NAME

            unset -v FILTER_TARGET
            local FILTER_TARGET
            for FILTER_TARGET in FEED_CATEGORY FEED_NAME; do
                FilterOptions "${FILTER_TARGET}"
            done

            # Unset options that are not required in this while loop
            unset -v URL_PASSWORD
            unset -v URL_USERNAME
            unset -v WGET_OPTION_DEFAULT_USERAGENT
            unset -v WGET_OPTION_DISPOSITION
            unset -v WGET_OPTION_DISPOSITION_FAIL
            unset -v WGET_OPTION_NO_CHECK_CERIFICATE
            unset -v WGET_OPTION_PREFER_IP_TYPE
            unset -v WGET_OPTION_FILENAME_LOCATION
            unset -v WGET_OPTION_RSS_MEDIACONTENT
            unset -v FEED_SORT_ORDER
            unset -v POST_WGET_RENAME_MDATE
            unset -v ATOM_FILTER_SIMPLE
            unset -v ATOM_FILTER_TYPE
            unset -v ATOM_FILTER_LANG

            if (( VERBOSITY >= 3 )) ; then
                     echo "  Writing out feed ${FEED_NAME} in category ${FEED_CATEGORY} with url ${FEED_URL}"
            fi
            printf '\t<outline text="%s"><outline text="%s" type="rss" xmlUrl="%s" /></outline>' \
                "${FEED_CATEGORY}" "${FEED_NAME}" "${FEED_URL}" >> "${EXPORT_OPML}"
        done < "${DIR_CONFIG}"/"${CONFIG_SERVERLIST}"

        printf '\t%s\n\t%s\n' '</body>' '</opml>' >> "${EXPORT_OPML}"
    else
        echo "OPML Export Error: ${EXPORT_OPML}" >> "${DIR_LOG}"/"${LOG_FAIL}"
        CleanupAndExit ${ERR_EXPORTOPML}
    fi
}
#                                                                                                                                }}}

# Function: PodgetImportOPML                                                                                                     {{{
#
# ARGUMENTS:
# ${1} == OPML to import
PodgetImportOPML() {
    # If you're curious about why we doing what we do here, please refer to note on variable scope at end of file.
    local -r IMPORT_OPML="${1}"

    if [[ ${IMPORT_OPML} == "NONE" ]]; then
        echo
        echo "unset FILE or URL to import from."
        CleanupAndExit 1
    fi

    if (( VERBOSITY >= 2 )) ; then
        printf '\n%s\n' "Import servers from OPML file: ${IMPORT_OPML}"
    fi

    local new_category
    new_category="OPML_Import_$(date ${DATE_FORMAT})"

    local opml_list

    if [[ ${IMPORT_OPML} == http:* ]] || [[ ${IMPORT_OPML} == ftp:* ]] ; then
        if (( VERBOSITY >= 2 )) ; then
            echo "Getting opml list."
        fi
        opml_list=$(wget "${WGET_OPTIONS[@]}" -O - "${IMPORT_OPML}")
    else
        opml_list=$(cat "${IMPORT_OPML}")
    fi

    local new_list
    new_list=$(echo "${opml_list}" | sed -e 's/\(\/>\)/\1\n/g' | sed -e :a -n -e 's/<outline\([^>]\+\)\/>/\1/Ip;/<outline/{N;s/\n\s*/ /;ba;}')

    if [[ -n "$new_list" ]]; then

        local OLD_IFS=$IFS
        IFS=$'\n'

        local data
        for data in ${new_list} ; do
            if (( VERBOSITY >= 1 )) ; then
                printf '\n%s\n' "---------------"
            fi

            local new_label
            new_label=$(echo "${data}" | sed -n -e 's/.*text="\([^"]\+\)".*/\1/Ip' | sed -e 's/^\s*[0-9]\+\.\s\+//' -e "s/[:;'\".,!/?<>\\|]//g")
            local new_url
            new_url=$(echo "${data}" | sed -n -e 's/.*[xml]*url="\([^"]\+\)".*/\1/Ip' | sed -e 's/ /%20/g')

            if (( VERBOSITY >= 3 )) ; then
                echo "LABEL:  ${new_label}"
                echo "URL:    ${new_url}"
            fi

            # Add '|| true' to catch when grep returns a non-zero status for URLs it does not find.  This replaces the need to
            # disable errexit and the ERR trap.
            local test
            test=$(grep "${new_url}" "${DIR_CONFIG}"/"${CONFIG_SERVERLIST}") || true

            if [[ -z "$test" ]]; then
                echo "${new_url} ${new_category} ${new_label}" >> "${DIR_CONFIG}"/"${CONFIG_SERVERLIST}"
            elif (( VERBOSITY >= 2 )) ; then
                echo "Feed ${new_label} is already in the serverlist"
            fi
        done

        IFS=$OLD_IFS
    else
        if (( VERBOSITY >= 2 )) ; then
            echo "  OPML Import Error ${IMPORT_OPML}" 1>&2
        fi
        echo "OPML Import Error: ${IMPORT_OPML}" >> "${DIR_LOG}"/"${LOG_FAIL}"
        CleanupAndExit ${ERR_IMPORTOPML}
    fi
}
#                                                                                                                                }}}

# Function: PodgetImportPCAST                                                                                                    {{{
#
# ARGUMENTS:
# ${1} == PCAST to import (file or URL)
PodgetImportPCAST() {
    # If you're curious about why we doing what we do here, please refer to note on variable scope at end of file.
    local IMPORT_PCAST="${IMPORT_PCAST}"
    local VERBOSITY="${VERBOSITY}"
    local DIR_CONFIG="${DIR_CONFIG}"
    local CONFIG_SERVERLIST="${CONFIG_SERVERLIST}"

    if [[ ${IMPORT_PCAST} == "NONE" ]]; then
        echo
        echo "unset FILE or URL to import from."
        CleanupAndExit 1
    fi

    if (( VERBOSITY >= 2 )) ; then
        printf '\n%s\n' "Import server from PCAST file: ${IMPORT_PCAST}"
    fi

    local pcast_data
    if [[ ${IMPORT_PCAST} == http:* ]] || [[ ${IMPORT_PCAST} == ftp:* ]] ; then
        if (( VERBOSITY >= 2 )) ; then
            echo "Getting pcast file."
        fi
        pcast_data=$(wget "${WGET_OPTIONS[@]}" -O - "${IMPORT_PCAST}")
    else
        pcast_data=$(cat "${IMPORT_PCAST}")
    fi

    local new_link new_category new_title
    new_link=$(echo "${pcast_data}" | sed -n -e 's/.*\(href\|url\)="\([^"]\+\)".*/\2/Ip' | sed -e 's/ /%20/g')
    new_category=$(echo "${pcast_data}" | sed -n -e 's/.*<category>\([^<]\+\)<.*/\1/Ip' | sed -e 's/ /_/g;s/\&quot;/\&/g;s/\&amp;/\&/g')
    new_title=$(echo "${pcast_data}" | sed -n -e 's/.*<title>\([^<]\+\)<.*/\1/Ip')

    if (( VERBOSITY >= 2 )) ; then
        echo "LINK: ${new_link}"
        echo "CATEGORY: ${new_category}"
        echo "TITLE: ${new_title}"
    fi

    # Added '|| true' to catch when grep exits with a non-zero status because the link was not found.  This eliminates the need to
    # disable errexit and the ERR trap.
    local test
    test=$(grep "${new_link}" "${DIR_CONFIG}"/"${CONFIG_SERVERLIST}") || true

    if [[ -z "$test" ]]; then
        echo "${new_link} ${new_category} ${new_title}" >> "${DIR_CONFIG}"/"${CONFIG_SERVERLIST}"
    elif (( VERBOSITY >= 2 )) ; then
        echo "Feed ${new_title} is already in the serverlist"
    fi
}
#                                                                                                                                }}}

# Function: PodgetServerLoop                                                                                                     {{{
# Displays general message with command line options.
# ARGUMENTS: <none>
PodgetServerLoop() {
    # Set local variables (and get values from global variables as necessary).
    # If you're curious about why we doing what we do here, please refer to note on variable scope at end of file.
    local -r VERBOSITY="${VERBOSITY}"
    local -r LOG_FAIL="${LOG_FAIL}"
    local -r LOG_COMPLETE="${LOG_COMPLETE}"
    local -r CONFIG_SERVERLIST="${CONFIG_SERVERLIST}"
    local -r NO_PLAYLIST="${NO_PLAYLIST}"
    if [[ -n ${PLAYLIST_PERPODCAST+set} ]]; then
        local -r PLAYLIST_PERPODCAST="${PLAYLIST_PERPODCAST}"
    fi
    local -r DIR_LOG="${DIR_LOG}"
    local SESSION_PLAYLIST_NAME
    local -r DIR_CONFIG="${DIR_CONFIG}"
    local CURRENT_SERVERLIST
    local COUNTER
    local FEED_CATEGORY
    local FEED_NAME
    local FEED_URL

    __MSG_DEBUG "Main loop"
    __MSG_DEBUG "SERVER LIST FILE" "$CONFIG_SERVERLIST"
    __MSG_DEBUG "WGET COMMON OPTIONS" "${WGET_COMMON_OPTIONS}"
    if (( NO_PLAYLIST == 0 )); then
        __MSG_DEBUG "Playlist Creation Enabled."
    else
        __MSG_DEBUG "Playlist Creation Disabled."
    fi
    if [[ -n ${PLAYLIST_PERPODCAST+set} ]]; then
        __MSG_DEBUG "PLAYLIST_PERPODCAST: ${PLAYLIST_PERPODCAST} (Enabled)"
    fi

    mkdir -p "${DIR_LOG}"
    FilenameCheck LOG_FAIL
    FilenameCheck LOG_COMPLETE
    touch "${DIR_LOG}"/"${LOG_FAIL}" "${DIR_LOG}"/"${LOG_COMPLETE}"

    if (( NO_PLAYLIST == 0 )) && [[ -z ${PLAYLIST_PERPODCAST+set} ]]; then
        SESSION_PLAYLIST_NAME="${PLAYLIST_NAMEBASE:=NEW-}$(date $DATE_FORMAT).m3u"

        COUNTER=2
        while [[ -e ${DIR_LIBRARY}/${SESSION_PLAYLIST_NAME} ]] ; do
            SESSION_PLAYLIST_NAME="${PLAYLIST_NAMEBASE:=NEW-}$(date $DATE_FORMAT).r$COUNTER.m3u"
            COUNTER=$((COUNTER+1))
        done

        __MSG_INFO "Session Playlist Name" "${SESSION_PLAYLIST_NAME}"
    fi

    # UTF-8/16 handling
    local FILETYPE
    for FILETYPE in utf8 utf16 ; do
        case ${FILETYPE} in
            'utf8')
                __MSG_INFO "UTF-8 Loop running." ;;
            'utf16')
                __MSG_INFO "UTF-16 Loop running." ;;
        esac
        case ${FILETYPE} in
            'utf8')
                CURRENT_SERVERLIST="${DIR_CONFIG}"/"${CONFIG_SERVERLIST}" ;;
            'utf16')
                # Test if iconv is installed.  If it is not, display error.
                if ! hash iconv >/dev/null 2>&1; then
                    echo "Can't find iconv binary, is libc-bin installed?" 1>&2
                    echo "Exiting UTF16 loop, unable to convert file to UTF8" 1>&2
                    CleanupAndExit $ERR_LIBC6NOTINSTALLED
                fi
                CURRENT_SERVERLIST="${DIR_CONFIG}/${CONFIG_SERVERLIST}.utf16" ;;
            *)
                echo "Unknown Filetype: ${FILETYPE}"
        esac
        if [[ ! -f ${CURRENT_SERVERLIST} ]]; then
            __MSG_INFO "No config file found, exiting loop."
            continue
        fi

        while read -r FEED_URL FEED_CATEGORY FEED_NAME ; do
            local URL_USERNAME
            local URL_PASSWORD
            local FEED_FULL_PLAYLIST
            local WGET_COMMON_OPTIONS="${WGET_COMMON_OPTIONS}"

            if (( DEBUG >= 1 )) ; then echo; fi
            __MSG_DEBUG "============================================================"
            __MSG_DEBUG "Server Loop:"
            __MSG_DEBUG "Serverlist Line --> ${FEED_URL:-} ${FEED_CATEGORY:-} ${FEED_NAME:-}"

            if   [[ "${FEED_URL:0:1}" == "#" || -z "${FEED_URL-empty}" ]] ; then
                __MSG_DEBUG "Discarding (comment or blank line)."
                __MSG_DEBUG "Clear Server Loop vars"
                unset -v FEED_URL
                unset -v FEED_CATEGORY
                unset -v FEED_NAME
                unset -v FEED_FULL_PLAYLIST
                unset -v URL_USERNAME
                unset -v URL_PASSWORD
                continue
            fi

            if (( DEBUG >= 1 )) ; then echo; fi
            __MSG_DEBUG "Reset options to allow loop specific options"
            __MSG_DEBUG " WGET_COMMON_OPTIONS: ${WGET_COMMON_OPTIONS}"

            unset -v WGET_SUBCHAR
            local WGET_SUBCHAR
            WGET_NOTCOUNT=0

            # In Vim to enter digraphs that are not commonly on the US keyboards,
            # we use ctrl-K followed by a two character lookup code.
            #   Examples:
            #     !2 - double vertical line  ‖
            #     =2 - double low line       ‗
            #     oo - bullet                •
            #     Db - diamond bullet        â—†
            #     '% - Greek Theta           Ï´
            #     Pd - British Pound symbol  £
            #     Eu - Euro Symbol           €
            #     Ye - Yen symbol            ¥
            #     Pt - Peseta symbol         â‚§
            #     W= - Won symbol            â‚©
            #     Ct - Cent symbol           ¢
            #     Co - Copyright symbol      ©
            #     Rg - Registered Trademark  ®
            #     +- - Plus Minus            ±
            #     Om - Ohm symbol            Ω
            #     AO - Angstrom symbol       â„«
            #     DG - Degree Sign           °
            #     AE - Latin Capital AE      Æ
            #     ae - Latin Small ae        æ
            #     Ca - Caret                 ‸
            #     1R - Roman Numeral One     â… 
            #     2R - Roman Numeral Two     â…¡
            #     3R - Roman Numeral Three   â…¢
            #     4R - Roman Numeral Four    â…£
            #     5R - Roman Numeral Five    â…¤
            #
            #     These are not good to use because they frequently overlap with following
            #     characters if not followed by a space.
            #     oC - Degree Celsius        ℃
            #     oF - Degree Fahrenheit     ℉
            #
            #     Digraphs may not be included in the locale that you have configured.  On my test systems,
            #     I found that I had one that did not display the correct characters for the digraphs
            #     but rather replaced them all with an underscore character.  The function worked but
            #     it did not display the characters correctly.
            #
            #     On the systems where it did display correctly, I found that I had the following
            #     configuration in my /etc/default/locale:
            #            #  File generated by update-locale
            #            LANG="en_US.UTF-8"
            #
            #     On the one system that did not display correctly, the configuration I had
            #     in /etc/default/locale was:
            #            #  File generated by update-locale
            #            LANG="en_US"
            #
            #      This can be updated by modifying the file or by running:
            #             update-locale LANG="en_US.UTF-8"
            #
            #      This may or may not require a reboot to take effect but I took the easy way out and
            #      rebooted so I would be sure it displayed as I hoped in the future.
            #
            #      NOTE ON CHARACTERS TO CONSIDER NOT INCLUDING:
            #        It is probably a good idea to not include any character that has special meaning
            #        in Bash and needs to be escaped.  That is why this string primarily starts with
            #        digraphs and then includes a few characters that are commonly found on most
            #        keyboards.  I initially wanted to include the $ symbol with the other monetary
            #        symbols.  However I had to escape it or it could cause an "unbound variable"
            #        error on some systems.
            #
            #      NOTE ON CHARACTERS TO CONSIDER INCLUDING:
            #        We are using this character to parse the WGET_BASEOPTS string and put it's parts
            #        into the WGET_OPTIONS array.  To make things as easy as possible, we want to use
            #        characters that are unlikely to be used in any of the WGET options.  This can be a
            #        bit tricky for some options like passwords or user-agent that can take almost
            #        anything.  For that reason, I have included a large selection of digraphs and a
            #        few characters that do not require escaping because it is very unlikely that
            #        someone used them all for one of those options and we will be able to safely
            #        find one to use.
            WGET_TEST_STRING="_;‖‗•◆ϴ£€¥₧₩¢ⅠⅡⅢⅣⅤΩÅ©®±°Ææ‸:|<>?~!@#%^"
            local INTERVAL
            for (( INTERVAL=0; INTERVAL<${#WGET_TEST_STRING}; INTERVAL++ )); do
                WGET_TEST_CHAR=${WGET_TEST_STRING:$INTERVAL:1}

                # grep looks for --fixed-strings so that certain characters are not
                # interpreted as regular expressions.
                #
                # we're looking for a character that is not found in the string so it is
                # ! grep
                if ! grep --quiet --fixed-strings "${WGET_TEST_CHAR}" <<<"${WGET_COMMON_OPTIONS}"; then
                    WGET_SUBCHAR="${WGET_TEST_CHAR}"
                    break
                else
                    WGET_NOTCOUNT=$((WGET_NOTCOUNT+1))
                fi
            done

            # Done with loop variable, remove it.
            unset -v INTERVAL

            if [[ -n "${WGET_SUBCHAR+defined}" ]] && [[ "${#WGET_SUBCHAR}" -gt 0 ]]; then
                __MSG_DEBUG "WGET Success finding parsing character (${WGET_SUBCHAR})"
                __MSG_DEBUG "  Test string length: ${#WGET_TEST_STRING}"
                __MSG_DEBUG "  Characters tested before usable found: ${WGET_NOTCOUNT}"
            else
                echo
                echo "Unable to find character to use as delimiter for WGET_BASEOPTS string."
                echo "Every character in our test set was also used somewhere in WGET_BASEOPTS."
                echo   "Test Set:   ${WGET_TEST_STRING}"
                echo   "WGET_BASEOPTS: ${WGET_BASEOPTS}"
                CleanupAndExit 1
            fi

            WGET_COMMON_OPTIONS="${WGET_COMMON_OPTIONS// -/${WGET_SUBCHAR}-}"

            # clear array and reimport
            unset -v WGET_OPTIONS

            # Import options from WGET_COMMON_OPTIONS string into WGET_OPTIONS array
            IFS="${WGET_SUBCHAR}" read -r -a WGET_OPTIONS <<<"${WGET_COMMON_OPTIONS}"

            WGET_COMMON_OPTIONS="${WGET_COMMON_OPTIONS//${WGET_SUBCHAR}-/ -}"
            unset -v WGET_NOTCOUNT
            unset -v WGET_SUBCHAR
            unset -v WGET_TEST_CHAR
            unset -v WGET_TEST_STRING

            __MSG_DEBUG "Reset FEED_FULL_PLAYLIST=0"
            local FEED_FULL_PLAYLIST=0

            __MSG_DEBUG "Reset FEED_SORT_ORDER=DESCENDING"
            local FEED_SORT_ORDER="DESCENDING"

            __MSG_DEBUG "Reset WGET_OPTION_DEFAULT_USERAGENT"
            local WGET_OPTION_DEFAULT_USERAGENT=0

            __MSG_DEBUG "Reset WGET_OPTION_FILENAME_LOCATION"
            local WGET_OPTION_FILENAME_LOCATION=0

            local WGET_OPTION_DISPOSITION
            if ArrayContains "--content-disposition" "${WGET_OPTIONS[@]}" ; then
                # removing actual --content-disposition option from WGET because it is not used directly
                # but rather to set mode.  Used for COMMON_OPTIONS to allow ease of use.
                for index in "${!WGET_OPTIONS[@]}"; do
                    if [[ ${WGET_OPTIONS[${index}]} == "--content-disposition" ]]; then
                        unset -v 'WGET_OPTIONS['"${index}"']'
                        WGET_OPTION_DISPOSITION=1
                        __MSG_DEBUG "Reset WGET_OPTION_DISPOSITION to global setting(${WGET_OPTION_DISPOSITION})"
                    fi
                done
            else
                WGET_OPTION_DISPOSITION=0
                __MSG_DEBUG "Reset WGET_OPTION_DISPOSITION to global setting(${WGET_OPTION_DISPOSITION})"
            fi

            if ArrayContains "--user-agent=" "${WGET_OPTIONS[@]}" ; then
                __MSG_DEBUG "Custom Wget User Agent Enabled."
            else
                WGET_OPTIONS+=("--user-agent=Podget")
                __MSG_DEBUG "Default Wget User Agent for Podget Enabled."
            fi

            __MSG_DEBUG "Reset WGET_OPTION_DISPOSITION_FAIL"
            local WGET_OPTION_DISPOSITION_FAIL=0

            __MSG_DEBUG "Reset WGET_OPTION_NO_CHECK_CERIFICATE"
            local WGET_OPTION_NO_CHECK_CERIFICATE=0

            __MSG_DEBUG "Reset WGET_OPTION_PREFER_IP_TYPE"
            local WGET_OPTION_PREFER_IP_TYPE=0

            __MSG_DEBUG "Reset WGET_OPTION_RSS_MEDIACONTENT"
            local WGET_OPTION_RSS_MEDIACONTENT=0

            __MSG_DEBUG "Reset POST_WGET_RENAME_MDATE"
            local POST_WGET_RENAME_MDATE=0

            __MSG_DEBUG "Reset POST_WGET_RENAME_TITLETAG"
            local POST_WGET_RENAME_TITLETAG=0

            __MSG_DEBUG "Reset POST_WGET_RENAME_REVTITLETAG"
            local POST_WGET_RENAME_REVTITLETAG=0

            __MSG_DEBUG "Reset ATOM_FILTER_SIMPLE"
            local ATOM_FILTER_SIMPLE=0

            __MSG_DEBUG "Reset ATOM_FILTER_TYPE"
            unset -v ATOM_FILTER_TYPE
            local ATOM_FILTER_TYPE

            __MSG_DEBUG "Reset ATOM_FILTER_LANG"
            unset -v ATOM_FILTER_LANG
            local ATOM_FILTER_LANG

            # End resets
            # -----------------------------------------------------------------
            # Read new configuration

            # Pass FEED_CATEGORY and FEED_NAME through the option filters.  This allows handling of options with blank feed
            # categories and names.
            unset -v FILTER_TARGET
            local FILTER_TARGET
            for FILTER_TARGET in FEED_CATEGORY FEED_NAME; do
                FilterOptions "${FILTER_TARGET}"
            done

            # Remove variable since it is no longer used.
            unset -v FILTER_TARGET

            # Unset options that are not required in this while loop

            # End setting of FEED_CATEGORY, FEED_NAME, and OPT_items
            # -----------------------------------------------------------------

            # Add Username and Password to wget options if found.
            # Options --user and --password are used for both FTP and HTTP sessions.  Using --ftp-user and --http-user would require
            # being able to selectively use the correct one based on the URL.  Same for --ftp-password and --http-password.
            if [[ -n ${URL_USERNAME+set} ]]; then
                WGET_OPTIONS+=("--user=${URL_USERNAME}")
            fi

            if [[ -n ${URL_PASSWORD+set} ]]; then
                WGET_OPTIONS+=("--password=${URL_PASSWORD}")
            fi

            # Reset to default WGET user-agent
            if (( WGET_OPTION_DEFAULT_USERAGENT==1 )); then
                for index in "${!WGET_OPTIONS[@]}"; do
                    if [[ ${WGET_OPTIONS[${index}]} =~ ^"--user-agent=".* ]]; then
                        __MSG_DEBUG "Reset to Default Wget User Agent"
                        unset -v 'WGET_OPTIONS['"${index}"']'
                    fi
                done
            fi

            # Add --no-check-certificate to WGET_OPTIONS
            if (( WGET_OPTION_NO_CHECK_CERIFICATE==1 )); then
                for index in "${!WGET_OPTIONS[@]}"; do
                    # if --no-check-certificate has been set before, remove it.
                    if [[ ${WGET_OPTIONS[${index}]} == "--no-check-certificate" ]]; then
                        unset -v 'WGET_OPTIONS['"${index}"']'
                    fi
                done
                WGET_OPTIONS+=("--no-check-certificate")
            fi

            # Set preferred IP type for WGET_OPTIONS
            if (( WGET_OPTION_PREFER_IP_TYPE>0 )); then
                for index in "${!WGET_OPTIONS[@]}"; do
                    # if --prefer-family has been set before, remove it.
                    if [[ ${WGET_OPTIONS[${index}]} =~ --prefer-family=IPv[46] ]]; then
                        unset -v 'WGET_OPTIONS['"${index}"']'
                    fi
                done
                case "${WGET_OPTION_PREFER_IP_TYPE}" in
                    4 )
                        WGET_OPTIONS+=("--prefer-family=IPv4")
                        ;;
                    6 )
                        WGET_OPTIONS+=("--prefer-family=IPv6")
                        ;;
                esac
            fi

            if (( VERBOSITY >= 2 )) ; then
                printf '\n%s\n' "-------------------------------------------------"
            fi
            if (( VERBOSITY >= 1 )) ; then
                local DISPLAY_CATEGORY
                local DISPLAY_NAME

                if [ "${FEED_CATEGORY}" == "." ]; then
                    DISPLAY_CATEGORY="None"
                else
                    DISPLAY_CATEGORY="${FEED_CATEGORY}"
                fi

                if [ "${FEED_NAME}" == "." ]; then
                    DISPLAY_NAME="None"
                else
                    DISPLAY_NAME="${FEED_NAME}"
                fi

                printf '%-30s %-50s\n' "Category: ${DISPLAY_CATEGORY}" "Name: ${DISPLAY_NAME}"
            fi

            __MSG_DEBUG "Loop WGET_OPTIONS" "${WGET_OPTIONS[*]}"

            # DirectoryCheck for FEED_NAME and FEED_CATEGORY here prior to using them.
            local ITEM
            for ITEM in FEED_CATEGORY FEED_NAME; do
                # FEED_NAME can be blank, if it is then we skip the DirectoryCheck
                if [[ ${ITEM} == "FEED_NAME" && -z "${!ITEM}" ]]; then
                    # we use continue rather than break here in case the variables are in a different order.
                    continue
                fi

                # Moved DirectoryCheck inside an IF statement so that a non-zero exit status would not trigger either the errexit
                # or the ERR trap conditions.
                if ! DirectoryCheck "${ITEM}"; then
                    echo
                    echo "Skipping this feed until corrected, proceeding to next feed listed in ${CURRENT_SERVERLIST}"
                    echo
                    # This needs to be 'continue 2' because we are not continuing the immediate for loop but rather the
                    # loop wrapping it.
                    continue 2
                fi
            done
            unset -v ITEM

            if (( FEED_FULL_PLAYLIST >= 1 )) ; then
                PLAYLIST_NAME=$(echo "PLAYLIST_${FEED_NAME//[[:space:]]/_}.m3u" | tr -s _)
            elif (( NO_PLAYLIST == 0 )) && [[ -n ${PLAYLIST_PERPODCAST+set} ]]; then
                # If configured to create individual playlists for each podcast, set playlist name here.
                # White-Space in feed name will be converted to underscores and then tr will limit their repetitions.
                PLAYLIST_NAME="${PLAYLIST_NAMEBASE:=NEW-}$(date $DATE_FORMAT)-$(echo "${FEED_NAME//[[:space:]]/_}" | tr -s '_').m3u"

                COUNTER=2
                while [[ -e "${DIR_LIBRARY}/${PLAYLIST_NAME}" ]] ; do
                    PLAYLIST_NAME="${PLAYLIST_NAMEBASE:=NEW-}$(date $DATE_FORMAT)-$(echo "${FEED_NAME//[[:space:]]/_}" | tr -s '_').r$COUNTER.m3u"
                    COUNTER=$((COUNTER+1))
                done
            elif (( NO_PLAYLIST == 0 )) && [[ -z ${PLAYLIST_PERPODCAST+set} ]]; then
                PLAYLIST_NAME="${SESSION_PLAYLIST_NAME}"
            fi

            if [[ -n ${URL_USERNAME+set} ]]; then
                __MSG_INFO "Podcast Username" "${URL_USERNAME}"
            fi
            if [[ -n ${URL_PASSWORD+set} ]]; then
                # Password is stored in the serverlist file in plain text so displaying it here is a small risk but can be
                # useful for debugging connection issues.
                __MSG_DEBUG "Podcast Password" "${URL_PASSWORD}"
            fi
            __MSG_DEBUG "WGET Options" "${WGET_OPTIONS[*]}"

            # We use double brackets here instead of double parentheses for numeric comparisons because it allows us
            # to string the three options together.   And inside double brackets, the && (and) takes precedence over the
            # || (or).  So it can be confusing to read but works.
            #
            # That is why '[[ A && B || C && D ]]' will result in both A and B needing to be true OR both C and D.
            if [[ "${NO_PLAYLIST}" -eq 0  &&  -n ${PLAYLIST_PERPODCAST+set} || "${FEED_FULL_PLAYLIST}" -gt 0 ]]; then
                __MSG_INFO "Playlist Name" "${PLAYLIST_NAME} (for single Podcast)"
            fi

            if (( VERBOSITY >= 2 )) ; then
                echo
                echo "Downloading feed index from ${FEED_URL}"
            fi

            case ${FILETYPE} in
                'utf8')
                    INDEXFILE=$(wget "${WGET_OPTIONS[@]}" -O - "${FEED_URL}") && EXITSTATUS=0 || EXITSTATUS=1
                    ;;
                'utf16')
                    # Slight gymnastics to report the exit status of WGET and not ICONV.
                    INDEXFILE=$(wget "${WGET_OPTIONS[@]}" -O - "${FEED_URL}" | iconv -f UTF-16 -t UTF-8; exit "${PIPESTATUS[0]}") && EXITSTATUS=0 || EXITSTATUS=1
                    ;;
            esac

            if (( EXITSTATUS != 0 )); then
                if (( VERBOSITY >= 1 )); then
                    printf '%-30s %-50s\n' "" "Error Downloading Feed."
                else
                    echo "ERROR Downloading Feed:  ${FEED_NAME}"
                fi
                # if downloaded failed, add URL to LOG_FAIL
                echo "${FEED_URL}" >> "${DIR_LOG}"/"${LOG_FAIL}"
                continue
            fi

            INDEXFILE=$(echo "${INDEXFILE}" | tr '\n\r' ' ' | sed -e 's/<\([^/]\)/\n<\1/g')

            # We will look for either '<rss ' or '<feed ' opening tags within first 9 lines of the INDEXFILE
            local TESTLINES
            TESTLINES=$(sed -n 1,9p <<< "${INDEXFILE}")

            # While most these messages are acceptably controlled for display via __MSG_DEBUG, we add an extra check
            # here because the loop in the center would take extra unnecessary time.
            if (( DEBUG >= 1 )) ; then
                __MSG_DEBUG "------ Check for RSS or Atom feed --------"
                local LINE
                while IFS= read -r LINE; do
                    __MSG_DEBUG "${LINE}"
                done< <(printf "%s\n" "${TESTLINES}")
                unset -v LINE
                __MSG_DEBUG "------ ( first 9 lines of feed --------"
                __MSG_DEBUG "------   looking for '<rss '   --------"
                __MSG_DEBUG "------   or '<feed ' )         --------"
                echo
            fi

            local INDEXFILE_TMP
            local INDEXFILE_TMP2

            if grep -q '<rss ' <<< "${TESTLINES}" ;then
                __MSG_DEBUG "RSS Feed Found"
                if (( DEBUG > 1 )) ; then echo; fi
                # if file is RSS then we look for '<enclosure '
                #    To debug a sed command and see how it flows use --debug option.
                #    NOTES for sed command:
                #       1.  -n       suppress automatic printing of pattern space
                #       2.  -e :a    set label named 'a'
                #       3.  -e '/<podcast:liveitem.*<\/podcast:liveitem>/Id'
                #                    Look for podcast:liveitem tags.  If found, delete.
                #                    Flags:
                #                      I    Ignore case while searching
                #                      d    Delete pattern space
                #       4.  -e '/<podcast:liveitem.*/I{N;s/\ *\n/\ /;T;ba}'
                #                    This command reads the next line into patter space when the podcast:liveitem opening and
                #                    closing tags do not occur on same line.  Reads line in, removes the newline character and
                #                    returns to label 'a'.
                #       5.  -e 's/.*<enclosure.*url\s*=\s*"\([^"]\+\)".*/\1/Ip'
                #                    Look for enclosure and url in pattern space.  If found, print the
                #                    url value.  This version looks for when the HTML feed uses double quotes around
                #                    the url value.
                #                    Flags:
                #                      I    Ignore case while searching
                #                      p    Print only substituted line
                #       6.  -e 't'   if last s/// did successful substitution then branch to end of script
                #                    because no label was provided.
                #       7.  -e "s/.*<enclosure.*url\\s*=\\s*'\\([^']\\+\\)'.*/\\1/Ip"
                #                    This command is here to catch when the HTML feed is using single quotes rather than double
                #                    quotes.
                #       8.  -e 't'   if last s/// did successful substitution then branch to end of script
                #                    because no label was provided.
                #       9.  -e 's/.*<title>\(.*\)<[/]title>.*$/TITLE \1/Ip'
                #                    Looking for <title> tag and grabbing contents.
                #       10. -e 't'   if last s/// did successful substitution then branch to end of script
                #                    because no label was provided.
                #       11. -e '/\(<enclosure\|<title>\).*/I{N;s/\ *\n/\ /;T;ba}'
                #                    this final command is to read the next line of the file into the pattern space.
                #                    We use this for feeds where the url= portion does not appear on the same line as
                #                    the enclosure start tag or when the closing title tag is not on the same line as
                #                    the opening one.  After merging, we go back to label 'a'. Might need to add
                #                    an 'I' flag to make it case insensitive for the 'enclosure' bit.
                #
                # INDEXFILE before adding TITLE bits
                # INDEXFILE=$(echo "${INDEXFILE}" | \
                #             sed -n -e :a -e 's/.*<enclosure.*url\s*=\s*"\([^"]\+\)".*/\1/Ip' -e 't' \
                #                          -e "s/.*<enclosure.*url\\s*=\\s*'\\([^']\\+\\)'.*/\\1/Ip" \
                #                          -e '/<enclosure\s*/{N;s/ *\n/ /;ba;}')
                #
                # INDEXFILE_TMP before adding bits to delete podcast:liveitem stuff
                # INDEXFILE_TMP=$(echo "${INDEXFILE}" | \
                #             sed -n -e :a -e 's/.*<enclosure.*url\s*=\s*"\([^"]\+\)".*/URL \1/Ip' -e t \
                #                          -e "s/.*<enclosure.*url\\s*'=\\s*\\([^i]\\+\\)'.*/URL \\1/Ip" -e t \
                #                          -e 's/.*<title>\(.*\)<[/]title>.*$/TITLE \1/Ip' -e t \
                #                          -e '/\(<enclosure\|<title>\).*/I{N;s/\ *\n/\ /;T;ba}')
                if (( WGET_OPTION_RSS_MEDIACONTENT < 1 )); then
                    INDEXFILE_TMP=$(echo "${INDEXFILE}" | \
                                sed -n -e :a -e '/<podcast:liveitem.*<\/podcast:liveitem>/Id' \
                                             -e '/<podcast:liveitem.*/I{N;s/\ *\n/\ /;T;ba}' \
                                             -e 's/.*<enclosure.*url\s*=\s*"\([^"]\+\)".*/URL \1/Ip' -e t \
                                             -e "s/.*<enclosure.*url\\s*=\\s*'\\([^']\\+\\)'.*/URL \\1/Ip" -e t \
                                             -e 's/.*<title>\(.*\)<[/]title>.*$/TITLE \1/Ip' -e t \
                                             -e '/\(<enclosure\|<title>\).*/I{N;s/\ *\n/\ /;T;ba}')
                else
                    # This section adds a couple of tests to look for <media:content ...> tags from the RSS Media Specification.
                    # This is used in the feeds created by FreshRSS aggregator so it's use is not expected to be common but we may
                    # find a few users that require it.  These tests were added after test 8 above and before test 9.
                    #       8.1.  -e 's/.*<media:content.*type="\(video\|audio\).*url\s*=\s*"\([^"]\+\)".*/URL \2/Ip'
                    #                    Look in pattern space for media:content tags that are preceded by TYPE video or audio then
                    #                    extract the URL.
                    #                    Flags:
                    #                      I    Ignore case while searching
                    #                      p    Print only substituted line
                    #       8.2.  -e 't'   if last s/// did successful substitution then branch to end of script
                    #                    because no label was provided.
                    #       8.3.  -e "s/.*<media:content.*type='\\(video\\|audio\\).*url\\s*=\\s*'\\([^']\\+\\)'.*/URL \\2/Ip"
                    #                    This command is the sane as 8.1 but to catch when the HTML feed is using single quotes
                    #                    rather than double quotes.
                    #       8.4.  -e 't'   if last s/// did successful substitution then branch to end of script
                    #                    because no label was provided.
                    #       8.5.  -e 's/.*<media:content.*url\s*=\s*"\([^"]\+\)".*type="\(video\|audio\).*/URL \1/Ip'
                    #                    This is like 8.1 but TYPE option follows the URL rather than precedes it.
                    #       8.6.  -e 't'   if last s/// did successful substitution then branch to end of script
                    #                    because no label was provided.
                    #       8.7.  -e "s/.*<media:content.*url\\s*=\\s*'\\([^']\\+\\)'.*type=\\(video\\|audio\\).*/URL \\1/Ip"
                    #                    This is like 8.3 but TYPE option follows the URL rather than precedes it.
                    #       8.8.  -e 't'   if last s/// did successful substitution then branch to end of script
                    #                    because no label was provided.
                    # Then the final pattern was updated to also look for incomplete media:content tags.
                    #       11. -e '/\(<enclosure\|<title>\|<media:content\).*/I{N;s/\ *\n/\ /;T;ba}'
                    #                    this final command is to read the next line of the file into the pattern space.
                    #                    We use this for feeds where the url= portion does not appear on the same line as
                    #                    the enclosure start tag or when the closing title tag is not on the same line as
                    #                    the opening one.  After merging, we go back to label 'a'. Might need to add
                    #                    an 'I' flag to make it case insensitive for the 'enclosure' bit.
                    #
                    INDEXFILE_TMP=$(echo "${INDEXFILE}" | \
                                sed -n -e :a -e '/<podcast:liveitem.*<\/podcast:liveitem>/Id' \
                                             -e '/<podcast:liveitem.*/I{N;s/\ *\n/\ /;T;ba}' \
                                             -e 's/.*<enclosure.*url\s*=\s*"\([^"]\+\)".*/URL \1/Ip' -e t \
                                             -e "s/.*<enclosure.*url\\s*=\\s*'\\([^']\\+\\)'.*/URL \\1/Ip" -e t \
                                             -e 's/.*<media:content.*type="\(video\|audio\).*url\s*=\s*"\([^"]\+\)".*/URL \2/Ip' -e t \
                                             -e "s/.*<media:content.*type='\\(video\\|audio\\).*url\\s*=\\s*'\\([^']\\+\\)'.*/URL \\2/Ip" -e t \
                                             -e 's/.*<media:content.*url\s*=\s*"\([^"]\+\)".*type="\(video\|audio\).*/URL \1/Ip' -e t \
                                             -e "s/.*<media:content.*url\\s*=\\s*'\\([^']\\+\\)'.*type=\\(video\\|audio\\).*/URL \\1/Ip" -e t \
                                             -e 's/.*<title>\(.*\)<[/]title>.*$/TITLE \1/Ip' -e t \
                                             -e '/\(<enclosure\|<title>\|<media:content\).*/I{N;s/\ *\n/\ /;T;ba}')
                fi
                 # If TITLE tag appears after the ENCLOSURE tag in the file, reverse the order of list for parsing.
                 if (( POST_WGET_RENAME_REVTITLETAG > 0 )); then
                     INDEXFILE_TMP=$(echo "${INDEXFILE_TMP}" | sed -n '1!G;h;$p')
                 fi
                 # Merge TITLE AND URL lines onto single line divided by '<Url-Title>'
                 INDEXFILE_TMP2=""
                 while read -r TAG DATA; do
                     case ${TAG} in
                         "TITLE" )
                             ITEM_TITLE="${DATA}"
                             ;;
                         "URL" )
                             # with cleanup for URL (used to be called FINAL below ATOM section)
                             ITEM_URL=$(echo "${DATA}" | sed -e 's/\s/%20/g' -e "s/'/%27/g" -e 's/\&apos;/%27/g' -e 's/\&amp;/\&/g')
                             # Enabled handling of unset ITEM_TITLE items by including a dash at the end of the variable name to
                             # signify that the default is a blank value (or we could specify a value we wanted after the dash).
                             INDEXFILE_TMP2+="${ITEM_URL}<Url-Title>${ITEM_TITLE-}${NEWLINE}"
                             unset -v ITEM_TITLE ITEM_URL
                             ;;
                     esac
                 done <<<"${INDEXFILE_TMP}"
                 if (( POST_WGET_RENAME_REVTITLETAG > 0 )); then
                     # Return INDEX to its default order
                     INDEXFILE=$(echo "${INDEXFILE_TMP2}" | sed -n '1!G;h;$p')
                 else
                     # INDEX already in correct order.
                     INDEXFILE="${INDEXFILE_TMP2}"
                 fi
            elif grep -q '<feed ' <<< "${TESTLINES}"; then
                __MSG_DEBUG "Atom Feed Found"
                if (( DEBUG > 1 )) ; then echo; fi
                # if file is Atom then we look for '<link\s.*rel="enclosure" '
                # NOTE: there may be a tag between link and rel, therefore we need to add '\s.*'

                # Characters unlikely to appear in an XML document.  Combination of "invalid" characters and those
                # that have worked well for my testing.
                TEST_STRING="^{}_~"

                # Find suitable TEST_CHAR to use for sed statements below.
                for (( i=0; i<${#TEST_STRING}; i++ )); do
                    TEST_CHAR=${TEST_STRING:$i:1}

                    # grep looks for --fixed-strings so that certain characters are not
                    # interpreted as regular expressions (like ^ $ or /)
                    #
                    # We're looking for a character NOT found in the INDEXFILE so its ! grep
                    if ! grep --quiet --fixed-strings "${TEST_CHAR}" <<<"${INDEXFILE}"; then
                        # When a character is not found in the string that we can use, break out of the loop.
                        break
                    fi
                done

                unset -v i

                # Get full enclosure lines to filter on
                INDEXFILE=$(echo "${INDEXFILE}" | sed -n -e "\\${TEST_CHAR}<link\\s.*rel=\"enclosure\".*/>${TEST_CHAR}Ip")

# NOTE: I have this section disabled because it has a high potential for confusing
#       users.  At this stage, there is potential that they will see many enclosures
#       in the feed and not understand why the filtering they have selected results
#       in fewer or none found.  However it is useful during testing so it is
#       available.
#                if (( DEBUG > 1 )); then
#                    __MSG_DEBUG "------ Indexfile Contents --------"
#                    while IFS= read -r LINE; do
#                        __MSG_DEBUG "${LINE}"
#                    done< <(printf "%s\n" "${INDEXFILE}")
#                    __MSG_DEBUG "----------------------------------"
#                    __MSG_DEBUG "----------------------------------"
#                    echo
#                fi

                # SIMPLE FILTERING: filter down to just audio & video types.
                if (( ATOM_FILTER_SIMPLE > 0 )); then
                    INDEXFILE=$(echo "${INDEXFILE}" | sed -n -e "\\${TEST_CHAR}type=\"\\(audio\\|video\\)${TEST_CHAR}p")
                fi

                if [[ -n ${ATOM_FILTER_TYPE+set} ]]; then
                    INDEXFILE=$(echo "${INDEXFILE}" | sed -n -r -e "\\${TEST_CHAR}.*type=\"${ATOM_FILTER_TYPE}\".*${TEST_CHAR}p")
                fi

                TYPECOUNT=$(echo "${INDEXFILE}" | sed -n -e "s${TEST_CHAR}.*type=\"\\([^\"]\\+\\)\".*${TEST_CHAR}\\1${TEST_CHAR}Ip" | sort | uniq -c | awk '{printf "%7s | %s\n",$1,$2}')

                if (( VERBOSITY >= 2 )) ; then
                    # Check if any filtering is already enabled.  If it is, assume that is all the user wants so no need to inform
                    # them that more is possible.
                    if (( ATOM_FILTER_SIMPLE == 0 )) && [[ -z ${ATOM_FILTER_TYPE+set} ]]; then
                        if (( $(echo "${TYPECOUNT}" | wc -l) > 1 )); then
                            echo
                            echo "This feed supports multiple types.  Consider using ATOM_FILTER_SIMPLE or"
                            echo "ATOM_FILTER_TYPE to narrow your selection."
                            echo
                            echo "  COUNT | TYPE"
                            echo "  ------+-------------"
                            echo "${TYPECOUNT}"
                            echo
                        fi
                    fi
                fi

                if [[ -n "${ATOM_FILTER_LANG+set}" ]]; then
                    INDEXFILE=$(echo "${INDEXFILE}" | sed -n -r -e "\\${TEST_CHAR}.*xml:lang=\"${ATOM_FILTER_LANG}\".*${TEST_CHAR}p")
                fi

                LANGCOUNT=$(echo "${INDEXFILE}" | sed -n -e "s${TEST_CHAR}.*xml:lang=\"\\([^\"]\\+\\)\".*${TEST_CHAR}\\1${TEST_CHAR}Ip" | sort | uniq -c | awk '{printf "%7s | %s\n",$1,$2}')

                if (( VERBOSITY >= 2 )) ; then
                    # Check if any filtering is already enabled.  If it is, assume that is all the user wants so no need to inform
                    if [[ -z "${ATOM_FILTER_LANG+set}" ]]; then
                        if (( $(echo "${LANGCOUNT}" | wc -l) > 1 )); then
                            echo
                            echo "This feed supports multiple languages.  Consider using ATOM_FILTER_LANG"
                            echo "to narrow your selection."
                            echo
                            echo "  COUNT | LANGUAGE"
                            echo "  ------+-------------"
                            echo "${LANGCOUNT}"
                            echo
                        fi
                    fi
                fi

                # Get the URLs from each enclosure after filtering.
                INDEXFILE=$(echo "${INDEXFILE}" | sed -n -e "s${TEST_CHAR}.*href=\"\\([^\"]\\+\\)\".*${TEST_CHAR}\\1${TEST_CHAR}Ip")
                # final INDEXFILE cleanup options
                INDEXFILE=$(echo "${INDEXFILE}" | \
                            sed -e 's/\s/%20/g' -e "s/'/%27/g" -e 's/\&apos;/%27/g' -e 's/\&amp;/\&/g' | \
                            sed -e ':a;N;$!ba;s/\n/ /g')
                # Convert to new one item per line format. Once we figure out the best way to extract
                # titles from we can convert or move this section as necessary.
                INDEXFILE_TMP2=""
                for ITEM_URL in ${INDEXFILE}; do
                     INDEXFILE_TMP2+="${ITEM_URL}<Url-Title>${NEWLINE}"
                done
                # Set back to INDEXFILE
                INDEXFILE="${INDEXFILE_TMP2}"
            else
                echo "Feed is neither RSS, or Atom.  Skipping to next feed."
                # if Feed is neither RSS or Atom, add URL to LOG_FAIL
                echo "${FEED_URL}" >> "${DIR_LOG}"/"${LOG_FAIL}"
                continue
            fi

            if [[ -n ${INDEXFILE} ]]; then

                # Remove any error log entries for the FEED_URL if it failed before
                RemoveURL "${FEED_URL}" "${DIR_LOG}"/"${LOG_FAIL}"

                if (( MOST_RECENT > 0 )) ; then
                    local FULLINDEXFILE="${INDEXFILE}"
                    local SURPLUSINDEX
                    if [[ "${FEED_SORT_ORDER}" == "ASCENDING" ]]; then
                        __MSG_DEBUG "FEED SORT ORDER: ASCENDING"
                        # Adding one to MOST_RECENT because we tend to have one blank line
                        # at the end of our INDEXFILE
                        #   -- This was needed when using tail.  Does not appear necessary when using sed.
                        # MOST_RECENT=$((MOST_RECENT+1))
                        # OpenBSD Tail does not support options with two dashes (so no --lines), we have
                        # to use the single dash option here or force OpenBSD to use GNU Tail.  Given this
                        # is a single use error, it is easier to use BSD compatible syntax even if it can be
                        # more challenging to debug.
                        # INDEXFILE=$(echo "${INDEXFILE}" | tail --lines="${MOST_RECENT}")
                        # INDEXFILE=$(echo "${INDEXFILE}" | tail -n "${MOST_RECENT}")
                        # This can also be done with sed but MOST_RECENT needs to be incremented by 2 not 1
                        # MOST_RECENT=$((MOST_RECENT+2))
                        # INDEXFILE=$(echo "${INDEXFILE}" | sed -n -e ':a' -e '$p;N;'"${MOST_RECENT}"',$D;ba')
                        local LINE_COUNT
                        local LINE_BREAK
                        LINE_COUNT=$(echo "${FULLINDEXFILE}" | sed -n '$=;')
                        LINE_BREAK=$((LINE_COUNT - MOST_RECENT))
                        INDEXFILE=$(echo "${FULLINDEXFILE}" | sed -n "${LINE_BREAK},\$ p")
                        # SURPLUSINDEX holds all the items that are not in INDEXFILE for marking as already downloaded below.
                        SURPLUSINDEX=$(echo "${FULLINDEXFILE}" | sed -n "${LINE_BREAK},\$ !p")
                        unset -v LINE_COUNT
                        unset -v LINE_BREAK
                    else
                        __MSG_DEBUG "FEED SORT ORDER: DESCENDING"
                        # Attempting to use head here results in exit condition 141, but using the sed construct
                        # below works.  Not sure why given that tail works above.
                        # INDEXFILE=$(echo "${INDEXFILE}" | head --lines="${MOST_RECENT}")
                        INDEXFILE=$(echo "${INDEXFILE}" | sed -n "1,${MOST_RECENT}p")
                        # SURPLUSINDEX holds all the items that are not in INDEXFILE for marking as already downloaded below.
                        SURPLUSINDEX=$(echo "${FULLINDEXFILE}" | sed -n "1,${MOST_RECENT}!p")

                    fi
                fi

                if (( DEBUG >= 1 )) ; then
                    local URLCOUNT
                    if (( MOST_RECENT > 0 )) ; then
                        __MSG_DEBUG "Full Index List:"
                        URLCOUNT=0
                        while read -r DATA; do
                            __MSG_DEBUG "${URLCOUNT}. ${DATA}"
                            URLCOUNT=$((URLCOUNT+1))
                        done <<<"${FULLINDEXFILE}"
                        __MSG_DEBUG "Modified Index List:"
                        URLCOUNT=0
                        while read -r DATA; do
                            __MSG_DEBUG "${URLCOUNT}. ${DATA}"
                            URLCOUNT=$((URLCOUNT+1))
                        done <<<"${INDEXFILE}"
                    else
                        __MSG_DEBUG "Index List:"
                        URLCOUNT=0
                        while read -r DATA; do
                            __MSG_DEBUG "${URLCOUNT}. ${DATA}"
                            URLCOUNT=$((URLCOUNT+1))
                        done <<<"${INDEXFILE}"
                    fi
                    unset -v URLCOUNT
                fi

                # End of this while loop is at approximately line 2980
                local DATA
                while read -r DATA; do
                    # Check for blank line, if found just proceed to next line.
                    if [[ -z "${DATA}" ]]; then
                        continue
                    fi

                    # Divide URL and TITLE from DATA
                    local URL="${DATA%<Url-Title>*}"
                    local TITLE="${DATA#*<Url-Title>}"

                    # Safety check:  if ${DATA} does not contain '<Url-Title>'
                    if [[ "${URL}" == "${TITLE}" ]]; then
                        TITLE=""
                    fi

                    if ! grep -F "${URL}" "${DIR_LOG}"/"${LOG_COMPLETE}" >/dev/null || (( FORCE != 0 )) ; then

                        if (( VERBOSITY >= 2 )) ; then
                            echo
                        fi

                        # Without the 'sed' statements.
                        local URL_FILENAME="${URL##*/}"
                        local URL_BASE="${URL%/*}"

                        # replace any whitespace in the filename with underscores.
                        URL_FILENAME=$(echo "${URL_FILENAME}" | tr '[:blank:]' '_' | tr -s '_')

                        # Test for available space on library partition
                        local AVAIL_SPACE
                        AVAIL_SPACE=$(df -kP "${DIR_LIBRARY}" | tail -n 1 | awk '{print $4}')
                        if (( AVAIL_SPACE < MIN_SPACE )); then
                            printf '\n%s\n%s\n' "Available space on Library partition has dropped below allowed." "Stopping Session." 1>&2
                            CleanupAndExit ${ERR_LIBLOWSPACE}
                        fi
                        unset -v AVAIL_SPACE

                        # Filename format fixes and character substitutions.
                        # Return value stored in variable ${MOD_FILENAME}, called here as a string to be used as the name of the
                        # variable.
                        local MOD_FILENAME
                        FilenameFixFormat MOD_FILENAME "${URL_FILENAME}"

                        # Fix where filename part of URI is constant
                        # This fix is known to cause issues with in filenames when it is not needed.  Disabled by default.
                        if [[ -n ${FILENAME_FORMATFIX4+set} ]] && (( FILENAME_FORMATFIX4 > 0 )); then
                            if [[ -z ${MOD_FILENAME} ]] ; then
                                MOD_FILENAME="${URL_FILENAME}"
                            fi
                            local MOD_PREFIX="${URL_BASE%%/}"
                            local MOD_PREFIX="${MOD_PREFIX##*/}"
                            MOD_FILENAME="${MOD_PREFIX##*/}_${MOD_FILENAME}"
                            __MSG_DEBUG "FILENAME FORMAT(4) FIXED: ${MOD_FILENAME}"
                        fi


                        if (( POST_WGET_RENAME_TITLETAG == 1 ))||(( POST_WGET_RENAME_REVTITLETAG == 1 )); then
                            # Title format fixes and character substitutions.
                            # Return value stored in variable ${MOD_TITLE}, called here as a string to be used as the name of the
                            # variable.
                            if [[ -n "${TITLE}" ]]; then
                                local MOD_TITLE
                                TitleFixFormat MOD_TITLE "${TITLE}"
                                if [[ -n "${MOD_TITLE}" ]]; then
                                    TITLE="${MOD_TITLE}"
                                fi
                            fi
                        fi

                        # If directories do not exist, then create them.
                        if [[ ! -d "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}" ]]; then
                            mkdir -p "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}"
                        fi

                        # If FORCE then remove existing files before download.
                        if (( FORCE != 0 )); then
                            if [[ -n ${MOD_FILENAME} ]]; then
                                if [[ -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${MOD_FILENAME}" ]]; then
                                    if (( VERBOSITY == 0 )) ; then
                                        rm -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${MOD_FILENAME}"
                                    else
                                        rm -fv "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${MOD_FILENAME}"
                                    fi
                                fi
                            else
                                if [[ -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${URL_FILENAME}" ]]; then
                                    if (( VERBOSITY == 0 )) ; then
                                        rm -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${URL_FILENAME}"
                                    else
                                        rm -fv "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${URL_FILENAME}"
                                    fi
                                fi
                            fi
                        fi

                        if (( VERBOSITY >= 2 )) ; then
                            if [[ -n ${MOD_FILENAME} ]]; then
                                echo -e "Downloading ${MOD_FILENAME} from ${URL_BASE}"
                            else
                                echo -e "Downloading ${URL_FILENAME} from ${URL_BASE}"
                            fi
                        fi

                        # Added '&& WGET_EXITSTATUS=0 || WGET_EXITSTATUS=1' to each WGET call below so we could remove the disabling
                        # of errexit and the ERR trap.
                        if (( (WGET_OPTION_DISPOSITION == 1) || (WGET_OPTION_FILENAME_LOCATION == 1) )); then
                            if (( VERBOSITY >= 3 )) ; then
                                if (( WGET_OPTION_DISPOSITION == 1 )); then
                                    echo "    [ Progress meters disabled while using 'wget --content-disposition' ]"
                                fi
                                if (( WGET_OPTION_FILENAME_LOCATION == 1 )); then
                                        echo "    [ Progress meters disabled while using OPT_FILENAME_LOCATION ]"
                                fi
                            fi
                            # This has been moved here to handle long filenames given by some feeds that result in a WGET Error
                            if [[ -n ${MOD_FILENAME} ]]; then
                                wget "${WGET_OPTIONS[@]}" -q --server-response -O "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${MOD_FILENAME}" "${URL}" 2> "${DIR_SESSION}/${URL_FILENAME}.servresp" && WGET_EXITSTATUS=0 || WGET_EXITSTATUS=1
                            else
                                wget "${WGET_OPTIONS[@]}" -q --server-response -O "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${URL_FILENAME}" "${URL}" 2> "${DIR_SESSION}/${URL_FILENAME}.servresp" && WGET_EXITSTATUS=0 || WGET_EXITSTATUS=1
                            fi
                        else
                            # This has been moved here to handle long filenames given by some feeds that result in a WGET Error
                            #   ( I'm looking at you ITunes..... )
                            if [[ -n ${MOD_FILENAME} ]]; then
                                wget "${WGET_OPTIONS[@]}" -O "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${MOD_FILENAME}" "${URL}" && WGET_EXITSTATUS=0 || WGET_EXITSTATUS=1
                            else
                                wget "${WGET_OPTIONS[@]}" -O "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${URL_FILENAME}" "${URL}" && WGET_EXITSTATUS=0 || WGET_EXITSTATUS=1
                            fi
                        fi

                        if (( WGET_EXITSTATUS == 0 )); then
                            # make sure CONTENT_FILENAME hasn't been used before
                            unset -v CONTENT_FILENAME
                            unset -v LOCATION_FILENAME
                            unset -v FINAL_FILENAME

                            echo "${URL}" >> "${DIR_LOG}"/"${LOG_COMPLETE}"

                            # Remove any error log entries for the URL if it failed before
                            RemoveURL "${URL}" "${DIR_LOG}"/"${LOG_FAIL}"

                            # Make sure FILENAME variables are local.
                            local CONTENT_FILENAME
                            local FINAL_FILENAME
                            local LOCATION_FILENAME

                            # Before filename changes, set FINAL_FILENAME to URL_FILENAME
                            # IF MOD_FILENAME has already been used, then set FINAL_FILENAME to MOD_FILENAME
                            if [[ -n ${MOD_FILENAME} ]]; then
                                FINAL_FILENAME="${MOD_FILENAME}"
                            else
                                FINAL_FILENAME="${URL_FILENAME}"
                            fi

                            # if --content-disposition get filename and remove quotes around it.
                            if (( WGET_OPTION_DISPOSITION == 1 )); then
                                __MSG_DEBUG "CONTENT-DISPOSITION TESTS"
                                if [[ -s "${DIR_SESSION}/${URL_FILENAME}.servresp" ]]; then
                                    __MSG_DEBUG "SERVER RESPONSE FILE NONZERO SIZE"

                                    # Added '|| true' to catch when grep exits with a non-zero status because the
                                    # 'Content-Disposition' tag is not found.  This eliminates the need to disable errexit and the
                                    # ERR trap.
                                    CONTENT_FILENAME=$(grep "^\\s\\+Content-Disposition:" "${DIR_SESSION}/${URL_FILENAME}.servresp" | grep "filename=" | tail -1 | sed -e 's/.*filename=//' -e 's/"//g') || true

                                    # Test CONTENT_FILENAME is not null or consists solely of whitespace
                                    if [[ -n ${CONTENT_FILENAME} && -n ${CONTENT_FILENAME// } ]]; then
                                        __MSG_DEBUG "CONTENT_FILENAME: '${CONTENT_FILENAME}'"
                                    else
                                        __MSG_DEBUG "SERVER RESPONSE FILE - No Content-Disposition Tag"
                                        # if variable is effectively blank, we can unset it
                                        unset -v CONTENT_FILENAME

                                        if (( WGET_OPTION_DISPOSITION_FAIL > 0 )); then
                                            __MSG_DEBUG " - Removing URL from ${DIR_LOG}/${LOG_COMPLETE} to retry next session."

                                            # Remove any COMPLETE log entries to allow it to retry next session.
                                            RemoveURL "${URL}" "${DIR_LOG}"/"${LOG_COMPLETE}"
                                        fi
                                    fi
                                else
                                    __MSG_DEBUG "SERVER RESPONSE FILE ZERO SIZE - No Tags"
                                fi

                                # Do we need a cleanup on CONTENT_FILENAME here?
                                # Two step process.  First modify any BADCHARS into the REPLACECHAR and then squeeze each repetition of the REPLACECHAR
                                # down to a single time.
                                if [[ -n ${CONTENT_FILENAME+set} ]]; then
                                    CONTENT_FILENAME=$(echo "${CONTENT_FILENAME}" | tr "${FILENAME_BADCHARS}" "${FILENAME_REPLACECHAR}" | tr -s "${FILENAME_REPLACECHAR}")
                                fi
                            fi

                            if (( WGET_OPTION_FILENAME_LOCATION > 0 )); then
                                __MSG_DEBUG "FILENAME LOCATION TESTS"
                                if [[ -s "${DIR_SESSION}/${URL_FILENAME}.servresp" ]]; then
                                    __MSG_DEBUG "SERVER RESPONSE FILE NONZERO SIZE"

                                    # Added '|| true' to catch when grep exits with non-zero status because the 'Location' tag was
                                    # not found.  This eliminates the need to disable errexit and the ERR trap.
                                    LOCATION_FILENAME=$(grep "^\\s*Location:" "${DIR_SESSION}/${URL_FILENAME}.servresp" | tail -1 | sed -e 's/\s*Location:\s//' -e 's/\(.*\)?.*/\1/') || true

                                    LOCATION_FILENAME="${LOCATION_FILENAME##*/}"

                                    if (( VERBOSITY >= 2 )); then
                                        # Test if LOCATION_FILENAME is not null and does not consist solely of spaces.
                                        if [[ -n ${LOCATION_FILENAME} &&  -n ${LOCATION_FILENAME// } ]]; then
                                            __MSG_DEBUG "LOCATION_FILENAME: '${LOCATION_FILENAME}'"
                                        else
                                            __MSG_DEBUG "SERVER RESPONSE FILE - No Location Tag"
                                            # If LOCATION_FILENAME is effectively blank we can unset it
                                            unset -v LOCATION_FILENAME
                                        fi
                                    fi
                                else
                                    __MSG_DEBUG "SERVER RESPONSE FILE ZERO SIZE - No Tags"
                                fi

                                # Do we need a cleanup on LOCATION_FILENAME here?
                                # Two step process.  First modify any BADCHARS into the REPLACECHAR and then squeeze each repetition of the REPLACECHAR
                                # down to a single time.
                                if [[ -n ${LOCATION_FILENAME+set} ]]; then
                                    LOCATION_FILENAME=$(echo "${LOCATION_FILENAME}" | tr "${FILENAME_BADCHARS}" "${FILENAME_REPLACECHAR}" | tr -s "${FILENAME_REPLACECHAR}")
                                fi
                            fi

                            # Move filename to that provided by content-disposition
                            if [[ -n ${CONTENT_FILENAME+set} && -n ${CONTENT_FILENAME} ]]; then
                                if [[ ! -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${CONTENT_FILENAME}" ]]; then
                                    __MSG_INFO "Filename Change" "From ${FINAL_FILENAME} to ${CONTENT_FILENAME}"
                                    mv "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${CONTENT_FILENAME}"
                                    FINAL_FILENAME="${CONTENT_FILENAME}"
                                else
                                    if (( FORCE != 0 )); then
                                        if [[ "${FINAL_FILENAME}" == "${CONTENT_FILENAME}" ]]; then
                                            echo "Filename Change Blocked [ Same Filename ]"
                                        else
                                            __MSG_INFO "Filename Change" "Forced from ${FINAL_FILENAME} to ${CONTENT_FILENAME}"
                                            mv -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${CONTENT_FILENAME}"
                                            FINAL_FILENAME="${CONTENT_FILENAME}"
                                        fi
                                    else
                                        if (( VERBOSITY >= 2 )); then
                                            echo "Filename Change" "Blocked [ ${CONTENT_FILENAME} already exists ]"
                                        fi
                                    fi
                                fi
                            fi

                            # Move filename to that provided by LOCATION_FILENAME
                            if [[ -n ${LOCATION_FILENAME+set} && -n ${LOCATION_FILENAME} ]]; then
                                if [[ ! -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${LOCATION_FILENAME}" ]]; then
                                    __MSG_INFO "Filename Change" "From ${FINAL_FILENAME} to ${LOCATION_FILENAME}"
                                    mv "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${LOCATION_FILENAME}"
                                    FINAL_FILENAME="${LOCATION_FILENAME}"
                                else
                                    if (( FORCE != 0 )); then
                                        if [[ "${FINAL_FILENAME}" == "${LOCATION_FILENAME}" ]]; then
                                            if (( VERBOSITY >= 2 )); then
                                                echo "Filename Change" "Blocked [ Same Filename ]"
                                            fi
                                        else
                                            __MSG_INFO "Filename Change" "Forced from ${FINAL_FILENAME} to ${LOCATION_FILENAME}"
                                            mv -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${LOCATION_FILENAME}"
                                            FINAL_FILENAME="${LOCATION_FILENAME}"
                                        fi
                                    else
                                        if (( VERBOSITY >= 2 )); then
                                            echo "Filename Change Blocked [ ${LOCATION_FILENAME} already exists ]"
                                        fi
                                    fi
                                fi
                            fi

                            # Rename a file to title
                            if (( POST_WGET_RENAME_TITLETAG == 1 ))||(( POST_WGET_RENAME_REVTITLETAG == 1 )); then
                                if [[ -n "${TITLE}" ]]; then
                                    __MSG_DEBUG "Title with cleanup: ${TITLE}"
                                    # Get extension from downloaded filename
                                    local OLDEXT="${FINAL_FILENAME##*.}"
                                    local TITLEEXT="${TITLE##*.}"
                                    # To protect against hidden filenames that end in a period ('.')
                                    if [[ -z "${TITLEEXT}" ]]; then
                                        TITLEEXT="${TITLE}"
                                    fi

                                    local FINAL_TITLE

                                    # If TITLE already has filename extension then do not add a second time,
                                    # also check that OLDEXT
                                    if [[ "${OLDEXT}" != "${TITLEEXT}" ]] && [[ -n "${OLDEXT}" ]]; then
                                        # With pattern substitution to remove a trailing period from title before
                                        # we add one for the extension.
                                        FINAL_TITLE="${TITLE/%./}.${OLDEXT}"
                                    else
                                        FINAL_TITLE="${TITLE}"
                                    fi
                                    __MSG_DEBUG "Title with extension: ${FINAL_TITLE}"
                                    if [[ ! -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_TITLE}" ]]; then
                                        __MSG_INFO "Filename Change" "From ${FINAL_FILENAME} to ${FINAL_TITLE}"
                                        mv "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_TITLE}"
                                        FINAL_FILENAME="${FINAL_TITLE}"
                                    else
                                        if (( FORCE != 0 )); then
                                            __MSG_INFO "Filename Change" "Forced from ${FINAL_FILENAME} to ${FINAL_TITLE}"
                                            mv -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_TITLE}"
                                            FINAL_FILENAME="${FINAL_TITLE}"
                                        else
                                            if (( VERBOSITY >= 2 )); then
                                                echo "Filename Change Blocked [ ${FINAL_TITLE} already exists ]"
                                            fi
                                        fi
                                    fi
                                else
                                    __MSG_DEBUG "Title not set for this item"
                                fi
                            fi


                            # Rename file to start from modification date
                            if (( POST_WGET_RENAME_MDATE == 1 )); then
                                local FILE_MDATE
                                FILE_MDATE=$(date -r "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" '+%Y%m%d_%Hh%Mm')
                                local FILENAME_MDATE="${FILE_MDATE}_${FINAL_FILENAME}"
                                if [[ ! -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FILENAME_MDATE}" ]]; then
                                    __MSG_INFO "Filename Change" "From ${FINAL_FILENAME} to ${FILENAME_MDATE}"
                                    mv "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FILENAME_MDATE}"
                                    FINAL_FILENAME="${FILENAME_MDATE}"
                                else
                                    if (( FORCE != 0 )); then
                                        __MSG_INFO "Filename Change" "Forced from ${FINAL_FILENAME} to ${FILENAME_MDATE}"
                                        mv -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FILENAME_MDATE}"
                                        FINAL_FILENAME="${FILENAME_MDATE}"
                                    else
                                        if (( VERBOSITY >= 2 )); then
                                            echo "Filename Change Blocked [ ${FILENAME_MDATE} already exists ]"
                                        fi
                                    fi
                                fi
                            fi

                            # Add filename.suffix
                            if [[ -n ${FILENAME_SUFFIX+set} ]]; then
                                if [[ ! -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}.${FILENAME_SUFFIX}" ]]; then
                                    __MSG_INFO "Filename Change" "From ${FINAL_FILENAME} to ${FINAL_FILENAME}.${FILENAME_SUFFIX}"
                                    mv "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}.${FILENAME_SUFFIX}"
                                    FINAL_FILENAME="${FINAL_FILENAME}.${FILENAME_SUFFIX}"
                                else
                                    if (( FORCE != 0 )); then
                                        __MSG_INFO "Filename Change" "Forced from ${FINAL_FILENAME} to ${FINAL_FILENAME}.${FILENAME_SUFFIX}"
                                        mv -f  "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}.${FILENAME_SUFFIX}"
                                        FINAL_FILENAME="${FINAL_FILENAME}.${FILENAME_SUFFIX}"
                                    else
                                        if (( VERBOSITY >= 2 )); then
                                            echo "Filename Change Blocked [ ${FINAL_FILENAME}.${FILENAME_SUFFIX} already exists ]"
                                        fi
                                    fi
                                fi
                            fi

                            if (( NO_PLAYLIST == 0 )) || (( FEED_FULL_PLAYLIST >= 1 )) ; then
                                # If creating playlists, then add to file.  Added sed command to remove any './' from each item
                                # added to a playlist or the echo statement.
                                if [[ -n ${PLAYLIST_NAME+set} ]] ; then
                                    echo "${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" | sed -e 's|[.]/||g' >> "${DIR_LIBRARY}/${PLAYLIST_NAME}"
                                    if (( VERBOSITY >= 2 )); then
                                        echo "PLAYLIST: Adding ${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME} to ${DIR_LIBRARY}/${PLAYLIST_NAME}" | sed -e 's|[.]/||g'
                                    fi
                                fi
                            fi

                            # We're done with CONTENT_FILENAME and FINAL_FILENAME, make sure they are cleared
                            if [[ -n ${CONTENT_FILENAME+set} ]] ; then
                                unset -v CONTENT_FILENAME
                            fi
                            if [[ -n ${FINAL_FILENAME+set} ]] ; then
                                unset -v FINAL_FILENAME
                            fi
                        else
                            # if downloaded failed, add URL to LOG_FAIL
                            if (( VERBOSITY >= 2 )) ; then
                                echo "Adding URL to error log."
                            fi
                            echo "${URL}" >> "${DIR_LOG}"/"${LOG_FAIL}"
                            # If file has zero size then remove it.  Files that are larger than zero size are kept so WGET's
                            # continue function can work on later attempts.
                            local REMOVE_FILENAME
                            if [[ -n ${MOD_FILENAME} ]]; then
                                REMOVE_FILENAME="${MOD_FILENAME}"
                            else
                                REMOVE_FILENAME="${URL_FILENAME}"
                            fi
                            if [[ -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${REMOVE_FILENAME}" ]]; then
                                if (( VERBOSITY >= 2 )) ; then
                                    echo "Partial file exists."
                                fi
                                if [[ ! -s "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${REMOVE_FILENAME}" ]]; then
                                    if (( VERBOSITY >= 2 )) ; then
                                        echo "- Removing zero size file."
                                        rm -fv "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${REMOVE_FILENAME}"
                                    else
                                        rm -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${REMOVE_FILENAME}"
                                    fi
                                else
                                    if (( VERBOSITY >= 2 )) ; then
                                        echo "- Keeping for later attempts"
                                    fi
                                fi
                            else
                                if (( VERBOSITY >= 2 )) ; then
                                    echo "Partial file does not exist."
                                fi
                            fi
                        fi
                    else
                        # Remove any error log entries for the URL if it failed before
                        RemoveURL "${URL}" "${DIR_LOG}"/"${LOG_FAIL}"

                        if (( VERBOSITY >= 2 )) ; then
                            if (( VERBOSITY >= 4 )) ; then echo ; fi
                            echo "Already downloaded ${URL}."
                        fi
                    fi

                    # Remove server response file as it's no longer needed
                    if (( DEBUG >= 0 )); then
                        if [[ -n ${URL_FILENAME+set} && -f "${DIR_SESSION}/${URL_FILENAME}.servresp" ]]; then
                            rm -f "${DIR_SESSION}/${URL_FILENAME}.servresp"
                        fi
                    else
                        if [[ -n ${URL_FILENAME+set} && -f "${DIR_SESSION}/${URL_FILENAME}.servresp" ]] && (( DEBUG > 1 )) ; then
                            __MSG_DEBUG "Not deleting ${DIR_SESSION}/${URL_FILENAME}.servresp"
                        fi
                    fi

                    __MSG_DEBUG "Clear File Vars"
                    unset -v URL_FILENAME
                done <<< "${INDEXFILE}"

                if (( VERBOSITY >= 3 )) ; then echo; fi

                if (( (MOST_RECENT != 0) && (INSTALL_SESSION == 0) )); then
                    __MSG_DEBUG "Marking additional files in Index as already downloaded (RECENT > 0)."
                    # for URL in ${FULLINDEXFILE}
                    # do
                    while read -r DATA; do
                        # Check for blank line, if found just proceed to next line.
                        if [[ -z "${DATA}" ]]; then
                            continue
                        fi

                        # Divide URL and TITLE from DATA
                        local URL="${DATA%<Url-Title>*}"
                        local TITLE="${DATA#*<Url-Title>}"

                        # Safety check:  if ${DATA} does not contain '<Url-Title>'
                        if [[ "${URL}" == "${TITLE}" || "${TITLE}" == "" ]]; then
                            unset -v TITLE
                        fi

                        if ! grep -F "${URL}" "${DIR_LOG}"/"${LOG_COMPLETE}" >/dev/null ; then
                            local URL_FILENAME
                            URL_FILENAME=$(echo "${URL}" | sed -e 's/.*\/\([^\/]\+\)/\1/' -e 's/%20/ /g')
                            if (( VERBOSITY >= 2 )) ; then
                                if (( POST_WGET_RENAME_TITLETAG == 1 ))||(( POST_WGET_RENAME_REVTITLETAG == 1 )); then
                                    if [[ -n "${TITLE}" ]]; then
                                        echo "Marking as already downloaded ${TITLE}."
                                    else
                                        echo "Marking as already downloaded ${URL_FILENAME}."
                                    fi
                                else
                                    echo "Marking as already downloaded ${URL_FILENAME}."
                                fi
                            fi
                            echo "${URL}" >> "${DIR_LOG}"/"${LOG_COMPLETE}"
                        fi
                    done <<< "${SURPLUSINDEX}"
                fi

                # If doing individual playlists for each podcast Sort new playlist
                if (( NO_PLAYLIST == 0 )) && [[ -e "${DIR_LIBRARY}/$PLAYLIST_NAME" && -n "${PLAYLIST_PERPODCAST+set}" ]]; then
                    PlaylistSort "${DIR_LIBRARY}" "${PLAYLIST_NAME}"

                    # If doing individual playlists for each podcast, Create ASX Playlist
                    if (( ASX_PLAYLIST > 0 )); then
                        PlaylistConvertToASX "${DIR_LIBRARY}" "${PLAYLIST_NAME}"
                    fi

                    # Done with playlist, unset name.
                    unset -v PLAYLIST_NAME
                fi
            else
                if (( VERBOSITY >= 1 )) ; then
                    echo "  No enclosures in feed: ${FEED_URL}"
                fi
                echo "${FEED_URL}" >> "${DIR_LOG}"/"${LOG_FAIL}"
            fi


            __MSG_DEBUG "Clear Server Loop Vars"
            unset -v FEED_URL
            unset -v FEED_CATEGORY
            unset -v FEED_NAME
            unset -v URL_FILENAME
            unset -v URL_USERNAME
            unset -v URL_PASSWORD
        done < "${CURRENT_SERVERLIST}"
    done

    # If doing one combined playlist for all podcasts, Sort new playlist
    if (( NO_PLAYLIST == 0 )) && [[ -n ${PLAYLIST_NAME+set} ]]; then
        if [[ -e "${DIR_LIBRARY}/$PLAYLIST_NAME" ]]; then
            PlaylistSort "${DIR_LIBRARY}" "${PLAYLIST_NAME}"

            # If doing one combined playlist for all podcasts, Create ASX Playlist
            if (( ASX_PLAYLIST > 0 )); then
                PlaylistConvertToASX "${DIR_LIBRARY}" "${PLAYLIST_NAME}"
            fi
        fi
    fi
}
#                                                                                                                                }}}

# Function: RemoveURL                                                                                                           {{{
# Simple function to cleanup URLs for removal from FILE.
# Arguments:
# ${1} == URL to remove from file
# ${2} == FILE to remove URL from
RemoveURL() {
    local -r URL_INPUT=${1}
    local -r TARGET_FILE=${2}

    # Characters unlikely to appear in an URL that are suitable for use as delimiters in SED statements.
    # List has been pruned down to eliminate any characters that need to be escaped themselves.
    # Listed as "Unsafe" in RFC 1738
    # Source: https://www.ietf.org/rfc/rfc1738.txt
    local TEST_STRING="#|^~<>[] "

    # Find suitable TEST_CHAR to use for sed statements below.
    for (( i=0; i<${#TEST_STRING}; i++ )); do
        local TEST_CHAR=${TEST_STRING:$i:1}

        # grep looks for --fixed-strings so that certain characters are not
        # interpreted as regular expressions (like ^ $ or /)
        #
        # We're looking for a character NOT found in the string so its ! grep
        if ! grep --quiet --fixed-strings "${TEST_CHAR}" <<<"${URL_INPUT}"; then
            # When a character is not found in the string that we can use, break out of the loop.
            break
        fi
    done

    unset -v i

    # Both sed statements below use TEST_CHAR as their delimiter

    # Escape any characters in URL that can affect the sed command below, currently: *
    local URL_CLEAN
    # URL_CLEAN as it was before trying to correct implicit escaping.
    # URL_CLEAN=$(echo "${URL_INPUT}" | sed -e "s${TEST_CHAR}\([^\\]\)\*${TEST_CHAR}\1\\\*${TEST_CHAR}g")
    # shellcheck disable=SC2001
    URL_CLEAN=$(echo "${URL_INPUT}" | sed -e "s${TEST_CHAR}\\([^\\]\\)\\*${TEST_CHAR}\\1\\\\*${TEST_CHAR}g")

    sed -i "\\${TEST_CHAR}${URL_CLEAN}${TEST_CHAR}d" "${TARGET_FILE}"
}
#                                                                                                                                }}}

# Function: TitleFixFormat                                                                                                       {{{
# Minor issues in Title strings are fixed so that it is compatible with most filesystems.
# Arguments:
# ${1} == name of variable to hold return string
# ${2} == string to fix the format of
TitleFixFormat() {
    # variable to hold returned value.
    local -r VAR_RETURN=${1}

    # Filename to be modified.
    # Set original value for title format fixes and character substitutions.
    # Set according to what is passed as the second argument to function.
    local MODIFIED_TITLE=${2}

    # ORIGINAL and MODIFIED start out the same.
    local -r ORIGINAL_TITLE="${MODIFIED_TITLE}"

   __MSG_INFO "ORIGINAL TITLE" "${ORIGINAL_TITLE}"

    if [[ "${MODIFIED_TITLE}" =~ .*" ".* ]]; then
        MODIFIED_TITLE="${MODIFIED_TITLE// /${FILENAME_REPLACECHAR}}"
        __MSG_INFO "TITLE FORMAT FIXED: ${MODIFIED_TITLE}"
    fi

    # Fix for ampersand (&) is interesting because the character will be removed by the default FILENAME_BADCHARS list.
    # We include it here for people who remove the & from their FILENAME_BADCHARS.
    if [[ "${MODIFIED_TITLE}" =~ .*"&amp;".* ]]; then
        MODIFIED_TITLE="${MODIFIED_TITLE//\&amp;/\&}"
        __MSG_INFO "TITLE FORMAT FIXED: ${MODIFIED_TITLE}"
    fi

    # Case insensitive BASH regex test followed by case insensitive replacement by sed.
    if [[ "${MODIFIED_TITLE,,}" =~ "<![cdata[".*"]]>" ]]; then
        MODIFIED_TITLE=$(echo "${MODIFIED_TITLE}" | sed -n -e 's/<!\[cdata\[\(.*\)]]>/\1/Ip')
        __MSG_INFO "TITLE FORMAT FIXED: ${MODIFIED_TITLE}"
    fi

    # Test if BADCHARS set
    if [[ -n ${FILENAME_BADCHARS+set} ]] ; then
        # Test for BADCHARS in MODIFIED_TITLE
        if [[ ${MODIFIED_TITLE} =~ ["${FILENAME_BADCHARS}"] ]]; then
            # Two step process.  First modify any BADCHARS into the REPLACECHAR and then squeeze each repetition of the REPLACECHAR
            # down to a single time.
            MODIFIED_TITLE=$(echo "${MODIFIED_TITLE}" | tr "${FILENAME_BADCHARS}" "${FILENAME_REPLACECHAR}" | tr -s "${FILENAME_REPLACECHAR}")
            __MSG_INFO "TITLE FORMAT FIXED: ${MODIFIED_TITLE}"
        fi
    fi

    if [[ ${MODIFIED_TITLE} =~ [/] ]]; then
        # Replace forward slashes in titles with dash as the using a forward slash in a name is not POSIX compliant
        MODIFIED_TITLE="${MODIFIED_TITLE//\//-}"
        __MSG_INFO "TITLE FORMAT FIXED: ${MODIFIED_TITLE}"
    fi

    # After replacing characters, strings may look ugly because they start or end with the FILENAME_REPLACECHAR or a dash.
    # Therefore we remove those here.
    if [[ ${MODIFIED_TITLE:0:1} =~ ["${FILENAME_REPLACECHAR}"-] ]]; then
        MODIFIED_TITLE="${MODIFIED_TITLE:1}"
        __MSG_INFO "TITLE FORMAT FIXED: ${MODIFIED_TITLE}"
    fi
    # Negative indices from the trailing end of the string require a space before the dash.
    if [[ ${MODIFIED_TITLE: -1} =~ ["${FILENAME_REPLACECHAR}"-] ]]; then
        MODIFIED_TITLE="${MODIFIED_TITLE:: -1}"
        __MSG_INFO "TITLE FORMAT FIXED: ${MODIFIED_TITLE}"
    fi

    if [[ "${ORIGINAL_TITLE}" != "${MODIFIED_TITLE}" ]]; then
        __MSG_INFO "MODIFIED TITLE" "${MODIFIED_TITLE}"
    fi

    # Pass the modified filename back to the calling variable.
    printf -v "${VAR_RETURN}" '%s' "${MODIFIED_TITLE}"

    # close without error
    return 0
}
#                                                                                                                                }}}

#                                                                                                                                }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# Portability tests for OS other than Linux                                                                                      {{{
# A few tests to allow Podget to run on Mac OSX, FreeBSD, NetBSD and OpenBSD.

uname=$(uname)
case "$uname" in
    "Linux") :;;
    "Darwin")
        DARWIN_EXIT=0

        if ! hash gsed >/dev/null 2>&1; then
            echo "GNU Sed Required."
            echo "Try 'brew install gnu-sed'  (see https://brew.sh for details)"
            DARWIN_EXIT=1
        else
            hash -p "$(hash -t gsed)" sed
        fi
        if ! hash gtr >/dev/null 2>&1; then
            echo "GNU tr Required."
            echo "Try 'brew install coreutils'  (see https://brew.sh for details)"
            DARWIN_EXIT=1
        else
            hash -p "$(hash -t gtr)" tr
        fi
        if ! hash gdate >/dev/null 2>&1; then
            echo "GNU Date Required."
            echo "Try 'brew install gdate'  (see https://brew.sh for details)"
            DARWIN_EXIT=1
        else
            hash -p "$(hash -t gdate)" date
        fi
        if ! hash gstat >/dev/null 2>&1; then
            echo "GNU Stat Required."
            echo "Try 'brew install gstat'  (see https://brew.sh for details)"
            DARWIN_EXIT=1
        else
            hash -p "$(hash -t gstat)" stat
        fi
        if (( DARWIN_EXIT > 0 )); then
            CleanupAndExit 1
        fi
        unset -v DARWIN_EXIT
    ;;
    "OpenBSD"|"NetBSD"|"FreeBSD")
        missing_counter=0
        needed_commands=( gsed gdate gtr )
        if [[ $uname == FreeBSD ]]; then
            needed_commands+=(gnustat)
        else
            needed_commands+=(gstat)
        fi

        for needed_command in "${needed_commands[@]}"; do
            if ! hash "$needed_command" >/dev/null 2>&1; then
                printf "Command not found in PATH: %s\n" "$needed_command" >&2
                ((++missing_counter))
            else
                hash -p "$(hash -t "$needed_command")" "${needed_command##@(g|gnu)}"
            fi
        done
        if (( missing_counter > 0 )); then
            CleanupAndExit 1
        fi
        unset -v needed_command{,s} missing_counter
    ;;
esac

#                                                                                                                                }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# Podget Body Function                                                                                                           {{{

PodgetCore() {
    # ------------------------------------------------------------------------------------------------------------------------------
    # Version  (Update with changes!)                                                                                            {{{

    local VERSION=1.0.0
    local REPORT_VERSION=0

    #                                                                                                                            }}}
    # ------------------------------------------------------------------------------------------------------------------------------
    # Defaults                                                                                                                   {{{

         #########################################################################################################################
         ## Do not configure here.  Run podget once to install default user configuration files and edit there. ##
         #########################################################################################################################

    # Set DIR_LIBRARY, DIR_SESSION, and DIR_LOG  in config file.
    local CONFIG_CORE="podgetrc"
    local CONFIG_SERVERLIST="serverlist"

    # Configuration Directory:
    # This used to be stored by default in the base of the users home directory.
    #local DIR_CONFIG="${HOME}/.podget"
    #
    # However we've update Podget to use three possible locations to help reduce clutter in the home directory.
    # For locations are:
    #   1.  ${HOME}/.podget
    #   2.  ${XDG_CONFIG_HOME}/podget
    #   3.  ${HOME}/.config/podget
    # For existing users, when Podget runs it will test all three in that order.  The first one it finds will become the
    # default configuration directory.
    #
    # For new users, Podget will attempt to use XDG_CONFIG_HOME but if that is not set will fallback to ${HOME}/.config/podget
    #
    # To use default configuration directory, set DIR_CONFIG to "UNSET-use-DEFAULT"
    # Or you can configure it to use any directory you want by configuring it here.
    local DIR_CONFIG="UNSET-use-DEFAULT"

    # DEFAULT FILENAME_BADCHARS used to test the configuration filenames and then unset.  The value used later in the script may be
    # set in the configuration file.  If you have a genuine need to use one of these characters in the filenames of the serverlist
    # or core configuration file then you may need to remove it from this definition.  For all other uses, modify the setting in
    # your configuration file (by default in podgetrc).
    #
    # This is a subset of the FILENAME_BADCHARS set in the default configuration file.  Many of the symbols that have been removed
    # are because they will cause other errors when used on the command line that prevent these checks from working.
    local FILENAME_BADCHARS="~#^=+{}[]:\"'?\\"

    # Filename Replace Character: Character to use to replace any/all
    # bad characters found.
    local FILENAME_REPLACECHAR=_

    # Auto-Cleanup.
    # 0 == disabled
    # 1 == delete any old content
    local CLEANUP=0

    # Skip downloading and just run cleanup
    # 0 == disable
    local CLEANUP_ONLY=0

    # Simulate cleanup
    local CLEANUP_SIMULATE=0

    # Number of days to keep files.   Cleanup will remove anything
    # older than this.
    local CLEANUP_DAYS=7

    # Most Recent
    # 0  == download all new items.
    # 1+ == download only the <count> most recent
    local MOST_RECENT=0

    # Force
    # 0 == Only download new material.
    # 1 == Force download all items even those you've downloaded before.
    local FORCE=0

    # Install session.  This gets called when script is first installed.
    local INSTALL_SESSION=0

    # Stop downloads if available space drops below
    local MIN_SPACE=10000

    # Date format for new playlist names
    local DATE_FORMAT=+%F

    # ASX Playlists for Windows Media Player
    # 0 == do not create
    # 1 == create
    local ASX_PLAYLIST=0

    # Enable playlist creation
    local NO_PLAYLIST=0

    # Default Wget no options
    local WGET_BASEOPTS=""

    # Order that items appear in feed.
    # Default: DESCENDING - Newest items appear first, oldest last.
    local FEED_SORT_ORDER="DESCENDING"

    # Create or update full playlist for each feed of all available items.
    # 0 == Enable
    # 1 == Disable
    local FEED_FULL_PLAYLIST=0

         #########################################################################################################################
         ## Do not configure here.  Run podget once to install default user configuration files ($HOME/.podget) and edit there. ##
         #########################################################################################################################

    # Internal script defaults
    local NEWLINE=$'\n'

    #                                                                                                                            }}}
    # ------------------------------------------------------------------------------------------------------------------------------
    # Parse command line                                                                                                         {{{

    # Set defaults for command line options so variables do not conflict with 'set -o nounset' by being undeclared.
    local CMDL_CLEANUP_SIMULATE=0
    local CMDL_FORCE=0

    while (( $# >= 1 )); do
        case ${1} in
            -c | --config               ) local CONFIG_CORE=${2:-NONE}                            ; shift ; shift || :      ;;
                 --create-config        ) local CONFIG_CORE=${2:-NONE}; local CMDL_CREATECONFIG=1 ; shift ; shift || :      ;;
            -C | --cleanup              ) local CLEANUP_ONLY=1 ; local CLEANUP=1                  ; shift                   ;;
            --cleanup_days              ) local CMDL_CLEANUP_DAYS=${2:-NONE}                      ; shift ; shift || :      ;;
            --cleanup_simulate          ) local CMDL_CLEANUP_SIMULATE=1 ; local CLEANUP_ONLY=1 ; local CLEANUP=1 ; shift    ;;
            -d | --dir_config           ) local DIR_CONFIG=${2:-NONE}                             ; shift ; shift || :      ;;
                 --dir_session          ) local CMDL_SESSION=${2:-NONE}                           ; shift ; shift || :      ;;
            -f | --force                ) local CMDL_FORCE=1                                      ; shift                   ;;
                 --import_opml          ) local IMPORT_OPML=${2:-NONE}                            ; shift ; shift || :      ;;
                 --export_opml          ) local EXPORT_OPML=${2:-NONE}                            ; shift ; shift || :      ;;
                 --import_pcast         ) local IMPORT_PCAST=${2:-NONE}                           ; shift ; shift || :      ;;
            -l | --library              ) local CMDL_LIBRARY=${2:-NONE}                           ; shift ; shift || :      ;;
            -n | --no-playlist          ) local CMDL_NOPLAYLIST=1                                 ; shift                   ;;
            -p | --playlist-asx         ) local CMDL_ASX=1                                        ; shift                   ;;
                 --playlist-per-podcast ) local CMDL_PLAYLISTPERPODCAST=1                         ; shift                   ;;
            -r | --recent               ) local CMDL_MOSTRECENT=${2:-NONE}                        ; shift ; shift || :      ;;
                 --serverlist           ) local CMDL_SERVERLIST=${2:-NONE}                        ; shift ; shift || :      ;;
            -s | --silent               )  VERBOSITY=0                                            ; shift                   ;;
            -V | --version              )  VERBOSITY=2 ; REPORT_VERSION=1                         ; shift                   ;;
            -v                          )  VERBOSITY=1                                            ; shift                   ;;
            -vv                         )  VERBOSITY=2                                            ; shift                   ;;
            -vvv                        )  VERBOSITY=3                                            ; shift                   ;;
            -vvvv                       )  VERBOSITY=4                                            ; shift                   ;;
            --verbosity                 )  VERBOSITY=${2:-NONE}                                   ; shift ; shift || :      ;;
            *                           ) DisplayShortHelp ; CleanupAndExit ${ERR_DISPLAYHELP} ;;
        esac
    done

    if [[ -n ${VERBOSITY+set} ]] ; then
        if [[ -z ${VERBOSITY##*[!0-9]*} ]]; then
            echo "Verbosity is not a supported integer value"
            exit 1
        fi
    fi

    if [[ -n ${CMDL_SERVERLIST+set} ]] ; then
        if [[ ${CMDL_SERVERLIST} == "NONE" ]]; then
            echo "Unset filename for server list"
            CleanupAndExit 1
        fi
        CONFIG_SERVERLIST=${CMDL_SERVERLIST}
    fi

    if (( VERBOSITY >= 2 )) ; then
        echo "podget"
        echo
    fi

    if (( REPORT_VERSION == 1 )); then
        echo "Version: ${VERSION}"
        CleanupAndExit 0
    fi

    if [[ ${CONFIG_CORE} == "NONE" ]]; then
        echo "Unset filename for configuration"
        CleanupAndExit 1
    fi

    if [[ ${DIR_CONFIG} == "NONE" ]]; then
        echo "Unset directory to store configuration"
        CleanupAndExit 1
    fi

    __MSG_INFO "Parsing Config file." ""
    __MSG_INFO "Config directory:" "${DIR_CONFIG}"
    __MSG_INFO "Config file:" "${CONFIG_CORE}"
    __MSG_INFO "Server List:" "${CONFIG_SERVERLIST}"

    if [[ -n ${CMDL_NOPLAYLIST+set} ]]; then
        if [[ -n ${CMDL_ASX+set} ]]; then
            printf '%-30s %s' "Error:" "Conflicting playlist options."
            CleanupAndExit 1
        fi
    fi

    # for testing
    #echo "Verbosity: ${VERBOSITY}"
    #CleanupAndExit 0

    # Test filename for CONFIG_CORE, CMDL/CONFIG_SERVERLIST and directory for DIR_CONFIG
    __MSG_DEBUG "Loading temporary FILENAME_BADCHARS to test base configuration file and directory names."

    FilenameCheck CONFIG_CORE
    if [[ -n ${CMDL_SERVERLIST+set} ]] ; then
        FilenameCheck CMDL_SERVERLIST
    else
        FilenameCheck CONFIG_SERVERLIST
    fi

    DirectoryCheck DIR_CONFIG

    __MSG_DEBUG "Clearing temporary FILENAME_BADCHARS, will read configured version from ${CONFIG_CORE}"
    unset -v FILENAME_BADCHARS

    #                                                                                                                            }}}
    # ------------------------------------------------------------------------------------------------------------------------------
    # CONFIG TEST PART 1 of 4: Test for existing DIR_CONFIG, if missing create it and install CONFIG_CORE                        {{{

    if [[ "${DIR_CONFIG}" == "UNSET-use-DEFAULT" ]]; then
        __MSG_DEBUG "DIR_CONFIG is not configured, checking for other possible locations"
        DIR_CONFIG_NAME="podget"

        if [[ -d "${HOME}/.${DIR_CONFIG_NAME}" ]]; then
            __MSG_DEBUG "HOME/.${DIR_CONFIG_NAME} exists!"
            DIR_CONFIG="${HOME}/.${DIR_CONFIG_NAME}"
        elif [[ -n ${XDG_CONFIG_HOME+set} && -d "${XDG_CONFIG_HOME}/${DIR_CONFIG_NAME}" ]]; then
            __MSG_DEBUG "XDG_CONFIG_HOME is set and '${DIR_CONFIG_NAME}' exists within it"
            DIR_CONFIG="${XDG_CONFIG_HOME}/${DIR_CONFIG_NAME}"
        elif [[ -d "${HOME}/.config" && -d "${HOME}/.config/${DIR_CONFIG_NAME}" ]]; then
            __MSG_DEBUG "HOME/.config exists and '${DIR_CONFIG_NAME}' exists within it"
            DIR_CONFIG="${HOME}/.config/${DIR_CONFIG_NAME}"
        else
            __MSG_DEBUG "'${DIR_CONFIG_NAME}' directory does not exist in any of the likely locations."
            if [[ -n ${XDG_CONFIG_HOME+set} ]]; then
                if [[ -d "${XDG_CONFIG_HOME}" ]]; then
                    mkdir "${XDG_CONFIG_HOME}/${DIR_CONFIG_NAME}"
                    EXITSTATUS=$?
                    if (( EXITSTATUS != 0 )); then
                        printf '%-30s %s' "Error:" "Error creating directory: ${XDG_CONFIG_HOME}/${DIR_CONFIG_NAME}"
                        CleanupAndExit 1
                    fi
                    DIR_CONFIG="${XDG_CONFIG_HOME}/${DIR_CONFIG_NAME}"
                else
                    printf '%-30s %s' "Error:" "Error: XDG_CONFIG_HOME directory does not exist ('${XDG_CONFIG_HOME}')"
                    CleanupAndExit 1
                fi
            else
                if [[ ! -d "${HOME}/.config/${DIR_CONFIG_NAME}" ]]; then
                    mkdir -p "${HOME}/.config/${DIR_CONFIG_NAME}"
                    EXITSTATUS=$?
                    if (( EXITSTATUS != 0 )); then
                        printf '%-30s %s' "Error:" "Error creating directory: ${HOME}/.config/${DIR_CONFIG_NAME}"
                        CleanupAndExit 1
                    fi
                    DIR_CONFIG="${HOME}/.config/${DIR_CONFIG_NAME}"
                fi
            fi
            INSTALL_SESSION=1
        fi
    else
        if [[ ! -d "${DIR_CONFIG}" ]]; then
            mkdir -p "${DIR_CONFIG}"
            EXITSTATUS=$?
            if (( EXITSTATUS != 0 )); then
                printf '%-30s %s' "Error:" "Error creating directory: ${DIR_CONFIG}"
                CleanupAndExit 1
            fi
            INSTALL_SESSION=1
        fi
    fi

    # Exit if set to --create-config
    if [[ -n ${CMDL_CREATECONFIG+set} ]]; then
        if (( CMDL_CREATECONFIG == 1 )); then
            if [[ -f "${DIR_CONFIG}/${CONFIG_CORE}" ]]; then
                echo "  Configuration file ${DIR_CONFIG}/${CONFIG_CORE} already exists."
                echo "    If you would like to reuse this name, then the old file needs"
                echo "    to be deleted first. Or you need to pick a new name."
                CleanupAndExit 1
            fi
        fi
    fi

    #                                                                                                                            }}}
    # ------------------------------------------------------------------------------------------------------------------------------
    # CONFIG TEST PART 2 of 4: Test for existing CONFIG_CORE, if missing create it.                                              {{{

    if [[ ! -f "${DIR_CONFIG}/${CONFIG_CORE}" ]] ; then

        echo "  Installing default user configuration file in ${DIR_CONFIG}/${CONFIG_CORE}"
        sed --silent -e '/TEXT_DEFAULT_CONFIG$/,/^TEXT_DEFAULT_CONFIG/p' "$0" |
            sed -e '/TEXT_DEFAULT_CONFIG/d' |
            sed -e "s|@HOME@|${HOME}|" -e "s/@VERSION@/${VERSION}/" -e "s/@SERVERLIST@/${CONFIG_SERVERLIST}/"> "${DIR_CONFIG}"/"${CONFIG_CORE}"
        EXITSTATUS=$?
        if (( EXITSTATUS != 0 )); then
            printf '%-30s %s' "Error:" "Failed to create \"${DIR_CONFIG}/${CONFIG_CORE}\""
            CleanupAndExit 1
        fi
        INSTALL_SESSION=1
    fi

    #                                                                                                                            }}}
    # ------------------------------------------------------------------------------------------------------------------------------
    # CONFIG TEST PART 3 of 4: Test if configuration file was created by a version that supports all required items and formats. {{{

    if ! grep -F "Podget configuration file created by version" "${DIR_CONFIG}"/"${CONFIG_CORE}" >/dev/null ; then
        echo "${DIR_CONFIG}/${CONFIG_CORE} cannot be verified to be compatible with this version of podget."
        echo
        echo "It is missing the version line that is included in configuration files created by newer versions of podget."
        echo
        echo "Please create a new configuration file by running 'podget --create-config <FILENAME>',"
        echo "and then converting your old configuration to the new format.  Then move the new file"
        echo "in place of the old and podget will work as it used to."
        CleanupAndExit 1
    else
        # get version
        VERSION=$(grep -F "Podget configuration file created by version" "${DIR_CONFIG}"/"${CONFIG_CORE}" | \
                  sed -e 's/.*by version \([0-9.]\)/\1/')

        # Split version string into an array by replacing '.' with 'space'
        IFS='.' read -r -a VERSION_ARRAY <<< "${VERSION}"

        # Assign values from array to named variables with a default of '0' if unset.
        # NOTE: BASE is currently commented out because it is currently unused.  It is here if we need it.
        local BASE="${VERSION_ARRAY[0]:-0}"
        local MAJOR="${VERSION_ARRAY[1]:-0}"
        local MINOR="${VERSION_ARRAY[2]:-0}"

        __MSG_DEBUG "PODGETRC Version Check:  (looking for newer than 0.6.18)"
        __MSG_DEBUG "  BASE: ${BASE:-0}"
        __MSG_DEBUG "  MAJOR: ${MAJOR}"
        __MSG_DEBUG "  MINOR: ${MINOR}"

        # Version 0.6.18 was the last version before 0.7.0, so this check should catch any of it's configuration files.
        if (( (BASE < 1) && (MAJOR < 7) && (MINOR < 19) )); then
            echo "${DIR_CONFIG}/${CONFIG_CORE} was created by an older version of podget than is needed by this version."
            echo
            echo "This version of podget requires a configuration produced for version 0.7.0 or newer.  This configuration"
            echo  "was produced by version ${VERSION}"
            echo
            echo "Please update your configuration by creating a new one with the command 'podget --create-config <FILENAME>'"
            echo "and then comparing its contents to your old configuration.  Once the new file has been updated to reflect"
            echo "your desired configuration, move it in place of the old one."
            CleanupAndExit 1
        fi

        unset -v BASE
        unset -v MAJOR
        unset -v MINOR
    fi

    #                                                                                                                            }}}
    # ------------------------------------------------------------------------------------------------------------------------------
    # Read core configuration options                                                                                            {{{

    # SHELLCHECK SC1090
    # shellcheck source=/dev/null
    source "${DIR_CONFIG}"/"${CONFIG_CORE}"

    # Config adjustment: Restore serverlist setting from command line if necessary
    if [[ -n ${CMDL_SERVERLIST+set} ]]; then
        if (( VERBOSITY >= 1 )) ; then
            echo "Serverlist set on command line, overriding value from configuration file."
        fi
        CONFIG_SERVERLIST=${CMDL_SERVERLIST}
    fi

    #                                                                                                                            }}}
    # ------------------------------------------------------------------------------------------------------------------------------
    # CONFIG TEST PART 4 of 4: Test for existing DIR_SERVERLIST, if missing create it.                                           {{{

    # Note: This test needs to happen after CONFIG_CORE has been read, as it may specify a different serverlist name than the
    #       default.

    if [[ ! -f "${DIR_CONFIG}/${CONFIG_SERVERLIST}" ]] ; then
        echo "  Installing default server list configuration."
        sed --silent -e '/TEXT_DEFAULT_SERVERLIST$/,/^TEXT_DEFAULT_SERVERLIST/p' "$0" |
            sed -e '/TEXT_DEFAULT_SERVERLIST/d' > "${DIR_CONFIG}"/"${CONFIG_SERVERLIST}"
        EXITSTATUS=$?
        if (( EXITSTATUS != 0 )); then
            echo "  Failed to install \"${DIR_CONFIG}/${CONFIG_SERVERLIST}\""
            CleanupAndExit 1
        fi
        INSTALL_SESSION=1
    fi

    #                                                                                                                            }}}
    # ------------------------------------------------------------------------------------------------------------------------------
    # Exit if set to --create-config                                                                                             {{{

    if [[ -n ${CMDL_CREATECONFIG+set} ]]; then
        if (( CMDL_CREATECONFIG == 1 )); then
            CleanupAndExit 0
        fi
    fi

    #                                                                                                                            }}}
    # ------------------------------------------------------------------------------------------------------------------------------
    # Configuration adjustments for command line options                                                                         {{{

    if [[ -n ${CMDL_NOPLAYLIST+set} ]]; then
        if (( VERBOSITY >= 1 )) ; then
            printf '\t\t%s\n' "NO PLAYLIST set on command line, overriding value from configuration file."
        fi
        NO_PLAYLIST=${CMDL_NOPLAYLIST}
    fi

    if (( INSTALL_SESSION > 0 )); then
        echo "  Downloading a single item from each default server to test configuration."
        echo
        MOST_RECENT=1
        VERBOSITY=3
    fi

    if [[ -n ${CMDL_LIBRARY+set} ]] ; then
        if [[ ${CMDL_LIBRARY} == "NONE" ]]; then
            echo "Unset directory to store podcast library"
            CleanupAndExit 1
        fi
        if (( VERBOSITY >= 3 )) ; then
            printf '\t\t%s\n' "Overriding Library Directory specified in configuration file."
        fi
        DIR_LIBRARY=${CMDL_LIBRARY}
    fi

    __MSG_INFO "Library Directory" "${DIR_LIBRARY}"

    if [[ -z ${DIR_LIBRARY} ]] ; then
        echo "ERROR - Library directory not defined." 1>&2
        CleanupAndExit ${ERR_LIBNOTDEF}
    else
        DirectoryCheck DIR_LIBRARY
    fi

    if [[ -n ${CMDL_SESSION+set} ]] ; then
        if [[ ${CMDL_SESSION} == "NONE" ]]; then
            echo "Unset directory to store session files."
            CleanupAndExit 1
        fi
        DIR_SESSION=${CMDL_SESSION}
    fi

    # Added so old configuration files (that were created before this option was added) still work.
    if [[ -z ${DIR_SESSION+set} ]] ; then
        if [[ -n ${TMPDIR+set} ]]; then
            DIR_SESSION=${TMPDIR}/podget
        else
            DIR_SESSION=/tmp/podget
        fi
    fi

    if [[ -n ${DIR_SESSION+set} ]]; then
        DirectoryCheck DIR_SESSION
    fi

    __MSG_INFO "Session Directory" "${DIR_SESSION}"

    if [[ -n ${CMDL_CLEANUP_DAYS+set} ]] ; then
        if [[ -z ${CMDL_CLEANUP_DAYS##*[!0-9]*} ]]; then
            echo "Cleanup Days is not a positive integer value"
            CleanupAndExit 1
        fi
        if (( CMDL_CLEANUP_DAYS >= 0 )); then
            CLEANUP_DAYS=${CMDL_CLEANUP_DAYS}
        fi
    fi

    if [[ -n ${CMDL_CLEANUP_SIMULATE} ]] ; then
        CLEANUP_SIMULATE=${CMDL_CLEANUP_SIMULATE}
    fi

    if [[ -z ${DIR_LOG+set} ]] ; then
        DIR_LOG=${DIR_LIBRARY}/.LOG
    fi

    DirectoryCheck DIR_LOG

    __MSG_INFO "Log Directory" "${DIR_LOG}"

    if [[ -n ${CMDL_ASX+set} ]]; then
        ASX_PLAYLIST=${CMDL_ASX}
    fi

    if [[ -n ${CMDL_PLAYLISTPERPODCAST+set} ]]; then
        PLAYLIST_PERPODCAST=1
    fi

    if (( CMDL_FORCE != 0 )); then
        FORCE=${CMDL_FORCE}
        WGET_BASEOPTS="${WGET_BASEOPTS/-c /}"
    fi

    if [[ -n ${CMDL_MOSTRECENT+set} ]] ; then
        if [[ -z ${CMDL_MOSTRECENT##*[!0-9]*} ]]; then
            echo
            echo "Recent is not a positive integer value"
            CleanupAndExit 1
        fi
        if (( CMDL_MOSTRECENT != 0 )); then
            MOST_RECENT=${CMDL_MOSTRECENT}
        fi
    fi

    if (( VERBOSITY <= 1 )) ; then
            WGET_COMMON_OPTIONS="-q ${WGET_BASEOPTS}"
    elif (( VERBOSITY == 2 )) ; then
        WGET_COMMON_OPTIONS="-nv ${WGET_BASEOPTS}"
    elif (( VERBOSITY == 3 )) ; then
        WGET_COMMON_OPTIONS="${WGET_BASEOPTS} --progress=dot:mega"
    else
        WGET_COMMON_OPTIONS="${WGET_BASEOPTS} --progress=bar"
    fi

    # Remove any residual leading spaces from WGET_COMMON_OPTIONS
    WGET_COMMON_OPTIONS="${WGET_COMMON_OPTIONS#[ ]*}"

    __MSG_DEBUG "WGET COMMON OPTIONS" "${WGET_COMMON_OPTIONS}"

    if [[ -n ${FILENAME_BADCHARS+set} ]] ; then
        # make sure backslash is escaped.
        FILENAME_BADCHARS="${FILENAME_BADCHARS/\\/\\\\}"

        __MSG_DEBUG "Filename Bad Characters" "${FILENAME_BADCHARS}"
        __MSG_DEBUG "Filename Replace Character" "${FILENAME_REPLACECHAR}"
    fi

    if (( DEBUG == 0 )); then
        __MSG_INFO "Debug Disabled" "Delete temp files and reduced progress messages."
    else
        __MSG_DEBUG "Debug Enabled" "Do not delete temp files and increased progress messages."
    fi

    if (( VERBOSITY >= 1 )) ; then
        echo
    fi

    #                                                                                                                            }}}
    # ------------------------------------------------------------------------------------------------------------------------------
    # Test for another session.                                                                                                  {{{
    # Moved below the configuration reading so that the DIR_SESSION could be configurable.

    # Test that session directory exists (useful when placed on a tmpfs filesystem).
    if [[ ! -d ${DIR_SESSION} ]]; then
        __MSG_INFO "Session directory not found, creating"
        mkdir -p "${DIR_SESSION}"
    fi

    # The cleanup portion of the following procedure may be less needed because we have gotten a lot more complete in our cleanup
    # procedures with traps that mean that the session file should be deleted whenever the session exits (whether good or
    # bad).  This procedures main purpose is to prevent concurrent sessions for running on the same configuration file.

    TEST_SESSION=0
    while read -r -d $'\0' FILE ; do
        if [[ $(stat -c %u "${FILE}") == "${UID}" ]]; then
            __MSG_DEBUG "Session FILE found: ${FILE} (that my user owns)"
            TEST_SESSION=1
            # shellcheck disable=SC2094
            while read -r LINE ; do
                if [[ "${LINE}" =~ ^[Cc]onfig[[:space:]][Ff]ile:.* ]]; then
                    TEST_File=$(echo "${LINE}" | sed -n -e 's/^[^:]\+:\s\(.*\)$/\1/p')
                    if [[ ${TEST_File} == "${CONFIG_CORE}" ]] ; then
                        SESSION_PID=$(echo "${FILE}" | sed -n -e 's/.*podget.\([0-9]*\)$/\1/p')
                        __MSG_DEBUG "Testing PID ${SESSION_PID} to determine if its still running."

                        if ps --pid "${SESSION_PID}" &>/dev/null; then
                            echo "Another session with config file ${CONFIG_CORE} found running.  Killing session." 1>&2
                            CleanupAndExit ${ERR_RUNNINGSESSION}
                        else
                            __MSG_DEBUG "Session PID ${SESSION_PID} is not running, removing lock file"
                            rm -f "${FILE}"
                        fi
                    fi
                fi
            done < "${FILE}"
        fi
    done < <(find "${DIR_SESSION}" -maxdepth 1 -type f -name "podget.[0-9]*" -print0)

    if (( DEBUG > 1 )); then echo; fi
    if (( TEST_SESSION > 0 )) ; then
        __MSG_INFO "Old Session file(s) found and removed.  Creating new one."
    else
        __MSG_INFO "Session file not found.  Creating podget.$$"
    fi

    # Set session file.  Stores the configuration file used so that multiple sessions can be run per user simultaneously as
    # long as they each have different configuration files.
    # An example would be two sessions running as:
    #       podget -c podgetrc.1
    #       podget -c podgetrc.2
    echo -e "Config file: ${CONFIG_CORE}" > "${DIR_SESSION}"/podget.$$

    #                                                                                                                            }}}
    # ------------------------------------------------------------------------------------------------------------------------------
    # Loop over servers on list                                                                                                  {{{

    if (( CLEANUP_ONLY == 0 )) && [[ -z ${IMPORT_OPML+set} && -z ${EXPORT_OPML+set} && -z ${IMPORT_PCAST+set} ]] ; then
        PodgetServerLoop
    fi

    #                                                                                                                            }}}
    # ------------------------------------------------------------------------------------------------------------------------------
    # Removal of downloaded files older than CLEANUP_DAYS                                                                        {{{

    if [[ -z ${IMPORT_OPML+set} && -z ${EXPORT_OPML+set} && -z ${IMPORT_PCAST+set} ]] ; then
        if (( CLEANUP != 0 || CLEANUP_ONLY != 0 )) ; then
            PodgetCleanup
        fi
    fi

    #                                                                                                                            }}}
    # ------------------------------------------------------------------------------------------------------------------------------
    # Build individual Podcast Full Playlists                                                                                    {{{

    # Placed here so it is run after any session whether it includes cleanup or not.  Does not run before importing or exporting
    # OPML or PCAST feed lists.

    if [[ -z ${IMPORT_OPML+set} && -z ${EXPORT_OPML+set} && -z ${IMPORT_PCAST+set} ]] ; then
        PodgetBuildFeedPlaylist
    fi

    #                                                                                                                            }}}
    # ------------------------------------------------------------------------------------------------------------------------------
    # OPML import loop:                                                                                                          {{{

    if [[ -n ${IMPORT_OPML+set} ]]; then
        PodgetImportOPML "${IMPORT_OPML}"
    fi

    #                                                                                                                            }}}
    # ------------------------------------------------------------------------------------------------------------------------------
    # OPML export loop:                                                                                                          {{{

    if [[ -n ${EXPORT_OPML+set} ]]; then
        PodgetExportOPML "${EXPORT_OPML}"
    fi

    #                                                                                                                            }}}
    # ------------------------------------------------------------------------------------------------------------------------------
    # PCAST import:                                                                                                              {{{

    if [[ -n ${IMPORT_PCAST+set} ]] ; then
        PodgetImportPCAST "${IMPORT_PCAST}"
    fi


    #                                                                                                                            }}}
    # ------------------------------------------------------------------------------------------------------------------------------

    return 0
}

# Call main function to run this whole kit and caboodle.
PodgetCore "${@}"

#                                                                                                                                }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# Close session with '0' status and clean up:                                                                                    {{{

__MSG_DEBUG "============================================================"
__MSG_INFO "Closing session with '0' status and cleanup"

# Disable extended glob matches.
shopt -u extglob

CleanupAndExit 0

#                                                                                                                                }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# Notes:                                                                                                                         {{{
#
# 1. In version 1.0.0, we begin an experiment with limiting variable scope with functions and local declarations.  The default way
#    Bash implements this works well for most cases, however we ran into a small issue that a variable would have near global status
#    within any function (child) called from the function (parent) it was declared local in.  Not generally an issue but it could
#    make tracking down where a variable change happened a bit more difficult.  To address this issue, it was discovered that within
#    a child function when we declared a variable local read-only we could also assign it the value of a variable of the same name
#    from the parent function.  This allowed us to pass the value and name of the variable to the child function in a way that
#    effectively limited the scope of where the variable could be changed while still allowing us to use variables of the same name.
#
#    For example, in the function PodgetBuildFeedPlaylist() we have the following declaration:
#       local -r DIR_CONFIG="${DIR_CONFIG}"
#    This creates a local read-only variable named DIR_CONFIG and inherits its setting from a variable of the same name that was set
#    within the PodgetCore parent function before it called the child function.  The syntax might look a little redundant because
#    the local variable has the same name as the global but it works and Shellcheck does not complain.
#
#    Declaring the variable local provides the protection from altering it that we want, while declaring it read-only causes an
#    error if we ever mistakenly do so we know where to fix it.  In some cases, this may mean not protecting the variable and
#    allowing it to be changed.
#
#                                                                                                                                }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# vim:tw=132:ts=4:sw=4:foldmethod=marker