File: podget

package info (click to toggle)
podget 0.8.10-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid
  • size: 416 kB
  • sloc: sh: 2,877; python: 34; makefile: 24
file content (3256 lines) | stat: -rwxr-xr-x 156,878 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
#!/usr/bin/env bash

# Useful to follow command execution and determine where an extra echo outputs during silent mode.
#set -x

# ----------------------------------------------------------------------------------------------------------------------------------
# Filename:      podget                                                                                                          {{{
# Maintainer:    Dave Vehrs <davevehrs(at)users.sourceforge.net>
# Copyright:     (c) 2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017 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, debianutils, 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                                                                              }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# 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 'EXIT_ERROR ${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 'CLEANUP_AND_EXIT 143' TERM
trap 'CLEANUP_AND_EXIT 130' INT

#                                                                                                                                }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# Set Shell Options to catch errors ('man bash' for details)                                                                     {{{

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

# Enable errtrace so that the ERR trap is inherited by functions
# NOTE: Causes an error about line 1841 where we try to filter various items out of
# the category and name.  Speculation is it is caused by our use of the expr command
# that commonly gives non-zero exit status for commands that actually exited OK.
#
# We can get around the issue by adding a '|| true' to the end of each expr command
# but that seems a hack.  What about replacing expr?
#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

#                                                                                                                                }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# Help text and default file formats                                                                                             {{{

: << 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

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

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

# Set DIR_LIBRARY, DIR_SESSION, and DIR_LOG  in config file.
DIR_CONFIG="${HOME}/.podget"
CONFIG_CORE="podgetrc"
CONFIG_SERVERLIST="serverlist"

# 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.
FILENAME_BADCHARS="~#^=+{}[]:\"'?\\"

# 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.
VERBOSITY=2

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

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

# Simulate cleanup
CLEANUP_SIMULATE=0

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

# 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

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

# Fix filenames for FAT32 compatibility
MODIFY_FILENAME=0

# Stop downloads if available space drops below
MIN_SPACE=10000

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

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

# Enable playlist creation
NO_PLAYLIST=0

# 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
DEBUG_LEADER="DEBUG --"

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

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

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

#                                                                                                                                }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# 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.
#
# Wget options that include spaces need to be surrounded in quotes.
#
# 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:
# ----------------------------------------------------------------------------------------------------------------------------------
http://thelinuxlink.net/tllts/tllts.rss LINUX The Linux Link
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                                                                                                                      {{{

# Function: ARRAY_CONTAINS
# 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})
ARRAY_CONTAINS() {
    local element
    for element in "${@:2}"; do [[ "${element}" == "${1}" ]] && return 0; done
    return 1
}

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

    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
            printf '\n%s\n' "${DEBUG_LEADER} 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}"
}

display_shelp() {
	echo; echo "Usage $0 [options]"; echo
	sed --silent -e '/HELP_STEXT$/,/^HELP_STEXT/p' "$0" | sed -e '/HELP_STEXT/d'
}

# Function: DIRECTORY_CHECK 'Name of Variable to be tested'
# Simple function to verify that unsafe characters are not used in directory names.
DIRECTORY_CHECK() {
    # 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 DIRECTORY_CHECK.
    #
    # 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 DIRECTORY_CHECK."
        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
    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))
                echo "  ${COUNT}. '\\000' cannot be used in directory names as mkdir expects"
                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
            CLEANUP_AND_EXIT 1
        fi
    fi

}

EXIT_ERROR() {
  # 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

  CLEANUP_AND_EXIT 1
}

# Function: FILENAME_CHECK 'Name of Variable to be tested'
# 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:
FILENAME_CHECK() {
    # 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 FILENAME_CHECK.
    #
    # 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 FILENAME_CHECK."
        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
    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

        CLEANUP_AND_EXIT 1
    fi
}

# Function: filenameFixFormat ${1} ${2}
# 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}


    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
        if (( VERBOSITY >= 3 )) ; then
           printf '%-30s %s\n' "ORIGINAL FILENAME:" "${MODIFIED_FILENAME}"
        fi
    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 (( $(expr "${MODIFIED_FILENAME}" : "[0-9a-zA-Z]\\+[&]amp;source=podcast.php[&]amp;channel_id=[0-9]\\+\$") > 0 )); then
            MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed 's/.*stream.mp3[?]guid=\([0-9]\+\)-\([0-9]\+\)\/\([0-9]\+\)\/.*/\1-\2-\3.mp3/')
            if (( DEBUG == 1 )) ; then
                echo "${DEBUG_LEADER} FILENAME FORMAT(2) FIXED: ${MODIFIED_FILENAME}"
            fi
        fi
    fi


    # Filename format fix for podcasts hosted on http://www.catradio.cat
    if [[ -n ${FILENAME_FORMATFIX3+set} ]] && (( FILENAME_FORMATFIX3 > 0 )); then
        if (( $(expr "${MODIFIED_FILENAME}" : "[0-9]\\+\\.mp3\\?[&]programa=[0-9a-Z+=%&;]*\$") > 0 )); then
            # shellcheck disable=SC2001
            MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed 's/\(.*\)\.mp3\(.*\)/\1\.mp3/g')
            if (( DEBUG == 1 )) ; then
                echo "${DEBUG_LEADER} FILENAME FORMAT(3) FIXED: ${MODIFIED_FILENAME}"
            fi
        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 (( $(expr "${MODIFIED_FILENAME}" : "[-0-9a-zA-Z_]\\+\\.[gmopv34]\\+[?]referrer=rss") > 0 )); then
            MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed -r 's/([-A-Za-z0-9_]+.[ogmpv34]+)[?]referrer=rss/\1/g')
            if (( DEBUG == 1 )) ; then
                echo "${DEBUG_LEADER} FILENAME FORMAT(5) FIXED: ${MODIFIED_FILENAME}"
            fi
        fi
    fi

    # ZDF podcast filename fix
    if [[ -n ${FILENAME_FORMATFIX6+set} ]] && (( FILENAME_FORMATFIX6 > 0 )); then
        if (( $(expr "${MODIFIED_FILENAME}" : "[-_0-9a-zA-Z]\\+\\.[gmopv34]\\+[?][-_+0-9]\\+") > 0 )); then
            MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed -ru 's/([-_A-Za-z0-9]+.[ogmpv3-4]+)[?][-+0-9]*/\1/g')
            if (( DEBUG == 1 )) ; then
                echo "${DEBUG_LEADER} FILENAME FORMAT(6) FIXED: ${MODIFIED_FILENAME}"
            fi
        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 (( $(expr "${MODIFIED_FILENAME}" : "[+_%&=?.0-9a-zA-Z]*media_url=http") > 0 )); then
            MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed -ru 's/.*(media_url=http.*[.][gmopv34]+)"\ .*/\1/' | sed -ru 's/.*%2F([-0-9A-Za-z_.]+[.][gmopv34]+)/\1/')
            if (( DEBUG == 1 )) ; then
                echo "${DEBUG_LEADER} FILENAME FORMAT(7) FIXED: ${MODIFIED_FILENAME}"
            fi
        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 (( $(expr "${MODIFIED_FILENAME}" : "stream[.]mp3[?]client_id=[0-9a-zA-Z]\\+") > 0 )); then
            MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed -ru 's/(stream[.]mp3)[?]client_id=[0-9A-Za-z]+/\1/')
            if (( DEBUG == 1 )) ; then
                echo "${DEBUG_LEADER} FILENAME FORMAT(8) FIXED: ${MODIFIED_FILENAME}"
            fi
        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 (( $(expr "${MODIFIED_FILENAME}" : "[-_0-9a-zA-Z]\\+[.][gmopv34]\\+[?][%&;=0-9a-zA-Z]\\+") > 0 )) ; then
            MODIFIED_FILENAME=$(echo "${MODIFIED_FILENAME}" | sed -ru 's/([-_A-Za-z0-9]+[.][ogmpv3-4]+)[?][-%&#;=A-Za-z0-9]+/\1/g')
            if (( DEBUG == 1 )) ; then
                echo "${DEBUG_LEADER} FILENAME FORMAT(9) FIXED: ${MODIFIED_FILENAME}"
            fi
        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 (( $(expr "${MODIFIED_FILENAME}" : "[-0-9A-Za-z_]\\+[.][MmPp3]\\+[?][-0-9A-Za-z%=]\\+%26episodeName%3D[-0-9A-Za-z%.*]\\+%26episodeKind%3D") > 0 )); 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')
            if (( DEBUG == 1 )) ; then
                echo "${DEBUG_LEADER} FILENAME FORMAT(10) FIXED: ${MODIFIED_FILENAME}"
            fi
        fi
    fi

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


    # Test for filename modifications.
    if [[ -n ${MODIFY_FILENAME} ]] && (( MODIFY_FILENAME > 0 )); 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}")
        if (( VERBOSITY >= 3 )) ; then
            printf '%-30s %s\n' "MODIFIED FILENAME:" "${MODIFIED_FILENAME}"
        fi
    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: FILTER_OPTIONS ${1}
# Arguments:
# ${1} == name of variable to filter on (either FEED_CATEGORY or FEED_NAME)
FILTER_OPTIONS() {
    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]}"
#        eval "${FILTER_ITEM}=\${!FILTER_ITEM/PASS:+([^[:space:]])}"
        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]}"
#        eval "${FILTER_ITEM}=\${!FILTER_ITEM/USER:+([^[:space:]])}"
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/USER:+([^[:space:]])}"
    fi

    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_CONTENT_DISPOSITION.*$ ]]; then
        WGET_OPTION_DISPOSITION=1
#        eval "${FILTER_ITEM}=\${!FILTER_ITEM/OPT_CONTENT_DISPOSITION}"
        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
#        eval "${FILTER_ITEM}=\${!FILTER_ITEM/OPT_DISPOSITION_FAIL}"
        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"
#        eval "${FILTER_ITEM}=\${!FILTER_ITEM/OPT_FEED_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
#        eval "${FILTER_ITEM}=\${!FILTER_ITEM/OPT_FEED_PLAYLIST_NEWFIRST}"
        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
#        eval "${FILTER_ITEM}=\${!FILTER_ITEM/OPT_FEED_PLAYLIST_OLDFIRST}"
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_FEED_PLAYLIST_OLDFIRST}"
    fi

    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)OPT_FILENAME_LOCATION.*$ ]]; then
        WGET_OPTION_FILENAME_LOCATION=1
#        eval "${FILTER_ITEM}=\${!FILTER_ITEM/OPT_FILENAME_LOCATION}"
        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
#        eval "${FILTER_ITEM}=\${!FILTER_ITEM/OPT_FILENAME_RENAME_MDATE}"
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/OPT_FILENAME_RENAME_MDATE}"
    fi

    if [[ "${!FILTER_ITEM}" =~ ^(.+[[:space:]]|[[:space:]]?)ATOM_FILTER_SIMPLE.*$ ]]; then
        ATOM_FILTER_SIMPLE=1
#        eval "${FILTER_ITEM}=\${!FILTER_ITEM/ATOM_FILTER_SIMPLE}"
        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]}"
#        eval "${FILTER_ITEM}=\${!FILTER_ITEM/ATOM_FILTER_TYPE=+([^[:space:]])}"
        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]}"
#        eval "${FILTER_ITEM}=\${!FILTER_ITEM/ATOM_FILTER_LANG=+([^[:space:]])}"
        printf -v "${FILTER_ITEM}" '%s' "${!FILTER_ITEM/ATOM_FILTER_LANG=+([^[:space:]])}"
    fi

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

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

    # Remove any residual trailing whitespace from ${!FILTER_ITEM}
#    eval "${FILTER_ITEM}=\${!FILTER_ITEM%\${!FILTER_ITEM##*[![:space:]]}}"
    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.
#        eval "${FILTER_ITEM}=."
        printf -v "${FILTER_ITEM}" '%s' '.'
    fi

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

}

PLAYLIST_ConvertToASX() {
    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=$(echo "${line}" | sed 's/\//\\/g')
      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}"
}

PLAYLIST_Sort() {
    local DIR_LIBRARY=${1}
    local M3U_PLAYLISTNAME=${2}
    local REALPLAYLISTNAME="${DIR_LIBRARY}/$M3U_PLAYLISTNAME"

    # Sort Playlist
    unset 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 REALPLAYLISTNAME TEMPPLAYLISTNAME
        return
    fi

    cp -p "$REALPLAYLISTNAME" "$TEMPPLAYLISTNAME" && sort -o "$REALPLAYLISTNAME" "$TEMPPLAYLISTNAME" && rm "$TEMPPLAYLISTNAME"

    unset REALPLAYLISTNAME TEMPPLAYLISTNAME
}

# Function: REMOVE_URL
# Simple function to cleanup URLs for removal from FILE.
# Arguments:
# ${1} == URL to remove from file
# ${2} == FILE to remove URL from
REMOVE_URL() {
    local URL_INPUT=${1}
    local 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

    # 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}"
}

COMPARE_StringInString() {
    echo "Enter Compare ..."
    echo "1 == ${1}"
    echo "2 == ${2}"
    case "${2}" in
        *"${1}" )
            echo "Found!"
            return 0
            ;;
    esac
    return 1
}

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

VERSION=0.8.10
REPORT_VERSION=0

#                                                                                                                                }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# Portability code                                                                                                               {{{
# This allows Gnu/Linux podget to also run on Mac OSX
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 gexpr >/dev/null 2>&1; then
            echo "GNU Expr Required."
            echo "Try 'brew install coreutils'  (see https://brew.sh for details)"
            DARWIN_EXIT=1
        else
            hash -p "$(hash -t gexpr)" expr
        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
            CLEANUP_AND_EXIT 1
        fi
        unset DARWIN_EXIT
    ;;
    "OpenBSD"|"NetBSD"|"FreeBSD")
        missing_counter=0
        needed_commands=( gsed gexpr gdate )
        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
            CLEANUP_AND_EXIT 1
        fi
        unset needed_command{,s} missing_counter
    ;;
esac

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

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

while (( $# >= 1 )); do
	case ${1} in
        -c | --config               ) CONFIG_CORE=${2:-NONE}                            ; shift ; shift           ;;
             --create-config        ) CONFIG_CORE=${2:-NONE}; CMDL_CREATECONFIG=1       ; shift ; shift           ;;
        -C | --cleanup              ) CLEANUP_ONLY=1 ; CLEANUP=1                        ; shift                   ;;
        --cleanup_days              ) CMDL_CLEANUP_DAYS=${2:-NONE}                      ; shift ; shift           ;;
        --cleanup_simulate          ) CMDL_CLEANUP_SIMULATE=1 ; CLEANUP_ONLY=1 ; CLEANUP=1 ; shift                ;;
        -d | --dir_config           ) DIR_CONFIG=${2:-NONE}                             ; shift ; shift           ;;
             --dir_session          ) CMDL_SESSION=${2:-NONE}                           ; shift ; shift           ;;
        -f | --force                ) CMDL_FORCE=1                                      ; shift                   ;;
             --import_opml          ) IMPORT_OPML=${2:-NONE}                            ; shift ; shift           ;;
             --export_opml          ) EXPORT_OPML=${2:-NONE}                            ; shift ; shift           ;;
             --import_pcast         ) IMPORT_PCAST=${2:-NONE}                           ; shift ; shift           ;;
        -l | --library              ) CMDL_LIBRARY=${2:-NONE}                           ; shift ; shift           ;;
        -n | --no-playlist          ) CMDL_NOPLAYLIST=1                                 ; shift                   ;;
        -p | --playlist-asx         ) CMDL_ASX=1                                        ; shift                   ;;
             --playlist-per-podcast ) CMDL_PLAYLISTPERPODCAST=1                         ; shift                   ;;
        -r | --recent               ) CMDL_MOSTRECENT=${2:-NONE}                        ; shift ; shift           ;;
             --serverlist           ) 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           ;;
		*                           ) display_shelp                         ; CLEANUP_AND_EXIT ${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"
        CLEANUP_AND_EXIT 1
    fi
    CONFIG_SERVERLIST=${CMDL_SERVERLIST}
fi

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

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

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

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

# If DEBUG is manual set to 0 or 1 in podgetrc, then it does not have an effect
# until CONFIG_CORE is read at about line 1478.  On the other hand, if it is
# not configured to a fixed value there, then it can be enabled from the
# commandline by executing podget like so "DEBUG=1 ./podget [options]".  By
# default, DEBUG is set to be disabled (0).
if (( DEBUG == 1 )) ; then
    printf '\n%s %-30s %s\n' "${DEBUG_LEADER}" "Parsing Config file." ""
    printf '%s %-30s %s\n' "${DEBUG_LEADER}" "Config directory:" "${DIR_CONFIG}"
    printf '%s %-30s %s\n' "${DEBUG_LEADER}" "Config file:" "${CONFIG_CORE}"
    printf '%s %-30s %s\n' "${DEBUG_LEADER}" "Server List:" "${CONFIG_SERVERLIST}"
fi

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

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

# Test filename for CONFIG_CORE, CMDL/CONFIG_SERVERLIST and directory for DIR_CONFIG
if (( DEBUG == 1 )) ; then
    printf '\n%s %s\n' "${DEBUG_LEADER}" "Loading temporary FILENAME_BADCHARS to test base configuration file and directory names."
fi
FILENAME_CHECK CONFIG_CORE
if [[ -n ${CMDL_SERVERLIST+set} ]] ; then
    FILENAME_CHECK CMDL_SERVERLIST
else
    FILENAME_CHECK CONFIG_SERVERLIST
fi

DIRECTORY_CHECK DIR_CONFIG

if (( DEBUG == 1 )) ; then
    printf '%s %s\n\n' "${DEBUG_LEADER}" "Clearing temporary FILENAME_BADCHARS, will read configured version from ${CONFIG_CORE}"
    echo
fi
unset FILENAME_BADCHARS

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

if [[ ! -d ${DIR_CONFIG} ]] ; then
    echo "  Configuration directory not found.  Creating \"${DIR_CONFIG}\""
    mkdir "${DIR_CONFIG}"
    EXITSTATUS=$?
    if (( EXITSTATUS != 0 )); then
        printf '%-30s %s' "Error:" "Failed to create \"${DIR_CONFIG}\""
        CLEANUP_AND_EXIT 1
    fi
    INSTALL_SESSION=1
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."
            CLEANUP_AND_EXIT 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}\""
        CLEANUP_AND_EXIT 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."
    CLEANUP_AND_EXIT 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.
    # BASE="${VERSION_ARRAY[0]:-0}"
    MAJOR="${VERSION_ARRAY[1]:-0}"
    MINOR="${VERSION_ARRAY[2]:-0}"

    if (( DEBUG == 1 )) ; then
        echo "${DEBUG_LEADER} PODGETRC Version Check:  (looking for newer than 0.6.18)"
        echo "${DEBUG_LEADER}   BASE: ${BASE:-0}"
        echo "${DEBUG_LEADER}   MAJOR: ${MAJOR}"
        echo "${DEBUG_LEADER}   MINOR: ${MINOR}"
    fi

    if (( (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."
        CLEANUP_AND_EXIT 1
    fi
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}\""
        CLEANUP_AND_EXIT 1
    fi
    INSTALL_SESSION=1
fi

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

if [[ -n ${CMDL_CREATECONFIG+set} ]]; then
    if (( CMDL_CREATECONFIG == 1 )); then
        CLEANUP_AND_EXIT 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"
        CLEANUP_AND_EXIT 1
    fi
    if (( VERBOSITY >= 3 )) ; then
        printf '\t\t%s\n' "Overriding Library Directory specified in configuration file."
    fi
    DIR_LIBRARY=${CMDL_LIBRARY}
fi

if (( VERBOSITY >= 3 )) ; then
    printf '%-30s %s\n' "Library Directory:" "${DIR_LIBRARY}"
fi

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

if [[ -n ${CMDL_SESSION+set} ]] ; then
    if [[ ${CMDL_SESSION} == "NONE" ]]; then
        echo "Unset directory to store session files."
        CLEANUP_AND_EXIT 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
    DIRECTORY_CHECK DIR_SESSION
fi

if (( VERBOSITY >= 3 )) ; then
    printf '%-30s %s\n' "Session Directory:" "${DIR_SESSION}"
fi

if [[ -n ${CMDL_CLEANUP_DAYS+set} ]] ; then
    if [[ -z ${CMDL_CLEANUP_DAYS##*[!0-9]*} ]]; then
        echo "Cleanup Days is not a positive integer value"
        CLEANUP_AND_EXIT 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

DIRECTORY_CHECK DIR_LOG

if (( VERBOSITY >= 3 )) ; then
    printf '%-30s %s\n' "Log Directory:" "${DIR_LOG}"
fi

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=$(echo "${WGET_BASEOPTS}" | sed -e 's/-c //')
#    Change to ${variable/search/replace} format.
    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"
        CLEANUP_AND_EXIT 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

if (( DEBUG == 1 )) ; then
    # echo -e "WGet Options:\t\t\t${WGET_COMMON_OPTIONS}"
    printf '%-30s %s\n' "WGet Options:" "${WGET_COMMON_OPTIONS}"
fi

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

    if (( DEBUG == 1 )) ; then
        printf '%-30s %s\n' "Filename Bad Characters:" "${FILENAME_BADCHARS}"
        printf '%-30s %s\n' "Filename Replace Character:" "${FILENAME_REPLACECHAR}"
    fi

    MODIFY_FILENAME=1
fi

if (( VERBOSITY >= 3 )) ; then
    if (( DEBUG == 0 )); then
        printf '%-30s %s\n' "Debug:" "Disabled - Delete temp files and reduced progress messages."
    else
        printf '%-30s %s\n' "Debug:" "Enabled - Do not delete temp files and increased progress messages."
    fi
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
    if (( DEBUG == 1 )) ; then
        printf '\n%s\n' "Session directory not found, creating"
    fi
    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
        if (( DEBUG == 1 )) ; then
            echo "${DEBUG_LEADER} Session FILE found: ${FILE} (that my user owns)"
        fi
        TEST_SESSION=1
        # shellcheck disable=SC2094
        while read -r LINE ; do
            TEST_Index=$(expr "${LINE}" : "^[Cc]onfig\\sfile:")
            if [[ "A${TEST_Index}" != "A" ]]; 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')
                    if (( DEBUG == 1 )) ; then
                        echo "${DEBUG_LEADER}  Testing PID ${SESSION_PID} to determine if its still running."
                    fi

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

if (( VERBOSITY >= 2 )) ; then
    if (( DEBUG == 1 )); then echo; fi
    if (( TEST_SESSION > 0 )) ; then
        echo "Old Session file(s) found and removed.  Creating new one."
    else
        echo "Session file not found.  Creating podget.$$"
    fi
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
    if (( DEBUG == 1 )) ; then
        printf '\n%s %s\n' "${DEBUG_LEADER}" "Main loop:"
        printf '%s %-30s %s\n' "${DEBUG_LEADER}" "SERVER LIST FILE:" "$CONFIG_SERVERLIST"
        printf '%s %-30s %s\n' "${DEBUG_LEADER}" "WGET OPTIONS:" "${WGET_COMMON_OPTIONS}"
        if (( NO_PLAYLIST == 0 )); then
            printf '%s %s\n' "${DEBUG_LEADER}" "Playlist Creation Enabled."
        else
            printf '%s %s\n' "${DEBUG_LEADER}" "Playlist Creation Disabled."
        fi
        if [[ -n ${PLAYLIST_PERPODCAST+set} ]]; then
            printf '%s %s\n' "${DEBUG_LEADER}" "PLAYLIST_PERPODCAST: ${PLAYLIST_PERPODCAST} (Enabled)"
        fi
    fi

    mkdir -p "${DIR_LOG}"
    FILENAME_CHECK LOG_FAIL
    FILENAME_CHECK 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

        if (( VERBOSITY >= 3 )); then
            echo
            echo "Playlist name: ${SESSION_PLAYLIST_NAME}"
        fi
    fi

    # UTF-8/16 handling
    for FILETYPE in utf8 utf16 ; do
        if (( DEBUG == 1 )) ; then
            echo
            case ${FILETYPE} in
                'utf8')
                    echo "${DEBUG_LEADER} UTF-8 Loop running." ;;
                'utf16')
                    echo "${DEBUG_LEADER} UTF-16 Loop running." ;;
            esac
        fi
        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
                    CLEANUP_AND_EXIT $ERR_LIBC6NOTINSTALLED
                fi
                CURRENT_SERVERLIST="${DIR_CONFIG}/${CONFIG_SERVERLIST}.utf16" ;;
            *)
                echo "Unknown Filetype: ${FILETYPE}"
        esac
        if [[ ! -f ${CURRENT_SERVERLIST} ]]; then
            if (( DEBUG == 1 )) ; then
                echo "${DEBUG_LEADER} No config file found, exiting loop."
            fi
            continue
        fi

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

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

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

            # clear array and reimport
            unset -v WGET_OPTIONS

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

            if (( DEBUG == 1 )) ; then
                echo "${DEBUG_LEADER}  Reset FEED_FULL_PLAYLIST=0"
            fi
            FEED_FULL_PLAYLIST=0

            if (( DEBUG == 1 )) ; then
                echo "${DEBUG_LEADER}  Reset FEED_SORT_ORDER=DESCENDING"
            fi
            FEED_SORT_ORDER="DESCENDING"

            if (( DEBUG == 1 )) ; then
                echo "${DEBUG_LEADER}  Reset WGET_OPTION_FILENAME_LOCATION"
            fi
            WGET_OPTION_FILENAME_LOCATION=0

            if ARRAY_CONTAINS "--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 WGET_OPTIONS["${index}"]
                        WGET_OPTION_DISPOSITION=1
                        if (( DEBUG == 1 )) ; then
                            echo "${DEBUG_LEADER}  Reset WGET_OPTION_DISPOSITION to global setting(${WGET_OPTION_DISPOSITION})"
                        fi
                    fi
                done
            else
                WGET_OPTION_DISPOSITION=0
                if (( DEBUG == 1 )) ; then
                    echo "${DEBUG_LEADER}  Reset WGET_OPTION_DISPOSITION to global setting(${WGET_OPTION_DISPOSITION})"
                fi
            fi

            if (( DEBUG == 1 )) ; then
                echo "${DEBUG_LEADER}  Reset WGET_OPTION_DISPOSITION_FAIL"
            fi
            WGET_OPTION_DISPOSITION_FAIL=0

            if (( DEBUG == 1 )) ; then
                echo "${DEBUG_LEADER}  Reset WGET_OPTION_NO_CHECK_CERIFICATE"
            fi
            WGET_OPTION_NO_CHECK_CERIFICATE=0

            if (( DEBUG == 1 )) ; then
                echo "${DEBUG_LEADER}  Reset WGET_OPTION_PREFER_IP_TYPE"
            fi
            WGET_OPTION_PREFER_IP_TYPE=0

            if (( DEBUG == 1 )) ; then
                echo "${DEBUG_LEADER}  Reset POST_WGET_RENAME_MDATE"
            fi
            POST_WGET_RENAME_MDATE=0

            if (( DEBUG == 1 )) ; then
                echo "${DEBUG_LEADER}  Reset ATOM_FILTER_SIMPLE"
            fi
            ATOM_FILTER_SIMPLE=0

            if (( DEBUG == 1 )) ; then
                echo "${DEBUG_LEADER}  Reset ATOM_FILTER_TYPE"
            fi
            unset ATOM_FILTER_TYPE

            if (( DEBUG == 1 )) ; then
                echo "${DEBUG_LEADER}  Reset ATOM_FILTER_LANG"
            fi
            unset 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 FILTER_TARGET
            for FILTER_TARGET in FEED_CATEGORY FEED_NAME; do
                FILTER_OPTIONS "${FILTER_TARGET}"
            done

            # 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

            # 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 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 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
                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

            if (( DEBUG == 1 )) ; then
                printf '%s %-30s %s\n' "${DEBUG_LEADER}" "Loop WGET_OPTIONS:" "${WGET_OPTIONS[*]}"
            fi

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

                # Moved DIRECTORY_CHECK inside an IF statement so that a non-zero exit status would not trigger either the errexit
                # or the ERR trap conditions.
                if ! DIRECTORY_CHECK "${i}"; 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

            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 (( VERBOSITY >= 2 )) ; then
                if [[ -n ${URL_USERNAME+set} ]]; then
                    printf '%-30s %-50s\n' "" "Username: ${URL_USERNAME}"
                fi
                if [[ -n ${URL_PASSWORD+set} ]] && (( DEBUG == 1 )); 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.
                    echo "${DEBUG_LEADER} Password: ${URL_PASSWORD}"
                fi
                if (( VERBOSITY >= 4 )) ; then
                    printf '%-30s %-50s\n' "" "WGET OPTIONS: ${WGET_OPTIONS[*]}"
                fi
                if (( NO_PLAYLIST == 0 )) && [[ -n ${PLAYLIST_PERPODCAST+set} ]]; then
                    printf '%-30s %-50s\n' "" "Individual Podcast Playlist Name: ${PLAYLIST_NAME}"
                fi

                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
            TESTLINES=$(sed -n 1,9p <<< "${INDEXFILE}")

            if (( DEBUG == 1 )) ; then
                printf '%s %s\n' "${DEBUG_LEADER}" "------ Check for RSS or Atom feed --------"
                while IFS= read -r LINE; do
                    printf '%s %s\n' "${DEBUG_LEADER}" "${LINE}"
                done< <(printf "%s\n" "${TESTLINES}")
                printf '%s %s\n' "${DEBUG_LEADER}" "------ ( first 9 lines of feed --------"
                printf '%s %s\n' "${DEBUG_LEADER}" "------   looking for '<rss '   --------"
                printf '%s %s\n' "${DEBUG_LEADER}" "------   or '<feed ' )         --------"
                echo
            fi

            if grep -q '<rss ' <<< "${TESTLINES}" ;then
                if (( DEBUG == 1 )) ; then
                    printf '%s %s\n' "${DEBUG_LEADER}" "RSS Feed Found"
                    echo
                fi
                # if file is RSS then we look for '<enclosure '
                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;}')
            elif grep -q '<feed ' <<< "${TESTLINES}"; then
                if (( DEBUG == 1 )) ; then
                    printf '%s %s\n' "${DEBUG_LEADER}" "Atom Feed Found"
                    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

                # 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
#                    printf '%s %s\n' "${DEBUG_LEADER}" "------ Indexfile Contents --------"
#                    while IFS= read -r LINE; do
#                        printf '%s %s\n' "${DEBUG_LEADER}" "${LINE}"
#                    done< <(printf "%s\n" "${INDEXFILE}")
#                    printf '%s %s\n' "${DEBUG_LEADER}" "----------------------------------"
#                    printf '%s %s\n' "${DEBUG_LEADER}" "----------------------------------"
#                    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")
            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

            # 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')

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

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


                # TODO:  Add choice here to get most recent from beginning or end of INDEXFILE
                #        Possibly with -> echo ${INDEXFILE} | rev | cut -d \  -f -"${MOST_RECENT}" | rev
                #        PROBLEM: This would require added 'util-linux' to the dependencies.
                #
                #        Option just in Bash:
                #          Temp move to array
                #            IFS=" " read -r -a TEMP_ARRAY <<< "${INDEXFILE}"
                #          Move back to Index
                #            INDEXFILE="${TEMP_ARRAY[@]: -${MOST_RECENT}}"
                if (( MOST_RECENT > 0 )) ; then
                    if [[ "${FEED_SORT_ORDER}" == "ASCENDING" ]]; then
                        if (( DEBUG == 1 )) ; then
                            echo -e "${DEBUG_LEADER} FEED SORT ORDER: ASCENDING"
                        fi
                        FULLINDEXFILE="${INDEXFILE}"
                        IFS=" " read -r -a TEMP_ARRAY <<< "${INDEXFILE}"
                        INDEXFILE="${TEMP_ARRAY[*]: -${MOST_RECENT}}"
                    else
                        if (( DEBUG == 1 )) ; then
                            echo -e "${DEBUG_LEADER} FEED SORT ORDER: DESCENDING"
                        fi
                        FULLINDEXFILE="${INDEXFILE}"
                        INDEXFILE=$(echo "${INDEXFILE}" | cut -d \  -f -"${MOST_RECENT}")
                    fi
                fi

                if (( DEBUG == 1 )) ; then
                    if (( MOST_RECENT > 0 )) ; then
                        printf '%s %s\n' "${DEBUG_LEADER}" "Full Index List:"
                        URLCOUNT=0
                        for URL in ${FULLINDEXFILE}; do
                            printf '%s   %s. %s\n' "${DEBUG_LEADER}" "${URLCOUNT}" "${URL}"
                            URLCOUNT=$((URLCOUNT+1))
                        done
                        printf '%s %s\n' "${DEBUG_LEADER}" "Modified Index List:"
                        URLCOUNT=0
                        for URL in ${INDEXFILE}; do
                            printf '%s   %s. %s\n' "${DEBUG_LEADER}" "${URLCOUNT}" "${URL}"
                            URLCOUNT=$((URLCOUNT+1))
                        done
                        unset URLCOUNT
                    else
                        printf '%s %s\n' "${DEBUG_LEADER}" "Index List:"
                        URLCOUNT=0
                        for URL in ${INDEXFILE}; do
                            printf '%s   %s. %s\n' "${DEBUG_LEADER}" "${URLCOUNT}" "${URL}"
                            URLCOUNT=$((URLCOUNT+1))
                        done
                        unset URLCOUNT
                    fi
                fi

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

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

                        # Without the 'sed' statements.
                        URL_FILENAME="${URL##*/}"
                        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
                        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
                            CLEANUP_AND_EXIT ${ERR_LIBLOWSPACE}
                        fi

                        # 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.
                        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
                            MOD_PREFIX="${URL_BASE%%/}"
                            MOD_PREFIX="${MOD_PREFIX##*/}"
                            MOD_FILENAME="${MOD_PREFIX##*/}_${MOD_FILENAME}"
                            if (( DEBUG == 1 )) ; then
                                echo "${DEBUG_LEADER} FILENAME FORMAT(4) FIXED: ${MOD_FILENAME}"
                            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 CONTENT_FILENAME
                            unset LOCATION_FILENAME
                            unset FINAL_FILENAME

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

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

                            # 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
                                if (( DEBUG == 1 )) ; then
                                    echo "${DEBUG_LEADER} CONTENT-DISPOSITION TESTS"
                                fi
                                if [[ -s "${DIR_SESSION}/${URL_FILENAME}.servresp" ]]; then
                                    if (( DEBUG == 1 )) ; then
                                        echo "${DEBUG_LEADER} SERVER RESPONSE FILE NONZERO SIZE"
                                    fi

                                    # 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
                                        if (( DEBUG == 1 )) ; then
                                            echo "${DEBUG_LEADER} CONTENT_FILENAME: '${CONTENT_FILENAME}'"
                                        fi
                                    else
                                        if (( DEBUG == 1 )) ; then
                                            echo "${DEBUG_LEADER} SERVER RESPONSE FILE - No Content-Disposition Tag"
                                        fi
                                        # if variable is effectively blank, we can unset it
                                        unset CONTENT_FILENAME

                                        if (( WGET_OPTION_DISPOSITION_FAIL > 0 )); then
                                            if (( DEBUG == 1 )) ; then
                                                echo "${DEBUG_LEADER}  - Removing URL from ${DIR_LOG}/${LOG_COMPLETE} to retry next session."
                                            fi

                                            # Remove any COMPLETE log entries to allow it to retry next session.
                                            REMOVE_URL "${URL}" "${DIR_LOG}"/"${LOG_COMPLETE}"
                                        fi
                                    fi
                                else
                                    if (( DEBUG == 1 )) ; then
                                        echo "${DEBUG_LEADER} SERVER RESPONSE FILE ZERO SIZE - No Tags"
                                    fi
                                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
                                if (( DEBUG == 1 )) ; then
                                    echo "${DEBUG_LEADER} FILENAME LOCATION TESTS"
                                fi
                                if [[ -s "${DIR_SESSION}/${URL_FILENAME}.servresp" ]]; then
                                    if (( DEBUG == 1 )) ; then
                                        echo "${DEBUG_LEADER} SERVER RESPONSE FILE NONZERO SIZE"
                                    fi

                                    # 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
                                            if (( DEBUG == 1 )) ; then
                                                echo "${DEBUG_LEADER} LOCATION_FILENAME: '${LOCATION_FILENAME}'"
                                            fi
                                        else
                                            if (( DEBUG == 1 )) ; then
                                                echo "${DEBUG_LEADER} SERVER RESPONSE FILE - No Location Tag"
                                            fi
                                            # If LOCATION_FILENAME is effectively blank we can unset it
                                            unset LOCATION_FILENAME
                                        fi
                                    fi
                                else
                                    if (( DEBUG == 1 )) ; then
                                        echo "${DEBUG_LEADER} SERVER RESPONSE FILE ZERO SIZE - No Tags"
                                    fi
                                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
                                    if (( VERBOSITY >= 2 )); then
                                        echo "FILENAME CHANGE from ${FINAL_FILENAME} to ${CONTENT_FILENAME}"
                                    fi
                                    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
                                            if (( VERBOSITY >= 2 )); then
                                                echo "FILENAME CHANGE PREVENTED [ Same Filenames ]"
                                            fi
                                        else
                                            if (( VERBOSITY >= 2 )); then
                                                echo "Forced FILENAME CHANGE from ${FINAL_FILENAME} to ${CONTENT_FILENAME}"
                                            fi
                                            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 PREVENTED [ ${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
                                    if (( VERBOSITY >= 2 )); then
                                        echo "FILENAME CHANGE from ${FINAL_FILENAME} to ${LOCATION_FILENAME}"
                                    fi
                                    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 (( VERBOSITY >= 2 )); then
                                            echo "Forced FILENAME CHANGE from ${FINAL_FILENAME} to ${LOCATION_FILENAME}"
                                        fi
                                        mv -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${LOCATION_FILENAME}"
                                        FINAL_FILENAME="${LOCATION_FILENAME}"
                                    else
                                        if (( VERBOSITY >= 2 )); then
                                            echo "FILENAME CHANGE PREVENTED [ ${LOCATION_FILENAME} already exists ]"
                                        fi
                                    fi
                                fi
                            fi

                            # Rename file to start from modification date
                            if (( POST_WGET_RENAME_MDATE == 1 )); then
                                FILE_MDATE=$(date -r "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FINAL_FILENAME}" '+%Y%m%d_%Hh%Mm')
                                FILENAME_MDATE="${FILE_MDATE}_${FINAL_FILENAME}"
                                if [[ ! -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${FILENAME_MDATE}" ]]; then
                                    if (( VERBOSITY >= 2 )); then
                                        echo "FILENAME CHANGE from ${FINAL_FILENAME} to ${FILENAME_MDATE}"
                                    fi
                                    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
                                        if (( VERBOSITY >= 2 )); then
                                            echo "Forced FILENAME CHANGE from ${FINAL_FILENAME} to ${FILENAME_MDATE}"
                                        fi
                                        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 PREVENTED [ ${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
                                    if (( VERBOSITY >= 2 )); then
                                        echo "FILENAME CHANGE from ${FINAL_FILENAME} to ${FINAL_FILENAME}.${FILENAME_SUFFIX}"
                                    fi
                                    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
                                        if (( VERBOSITY >= 2 )); then
                                            echo "Forced FILENAME CHANGE from ${FINAL_FILENAME} to ${FINAL_FILENAME}.${FILENAME_SUFFIX}"
                                        fi
                                        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 PREVENTED [ ${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 CONTENT_FILENAME
                            fi
                            if [[ -n ${FINAL_FILENAME+set} ]] ; then
                                unset FINAL_FILENAME
                            fi
                        else
                            # if downloaded failed, add URL to LOG_FAIL
                            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.
                            if [[ -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${URL_FILENAME}" ]]; then
                                if [[ ! -s "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${URL_FILENAME}" ]]; then
                                    rm -f "${DIR_LIBRARY}/${FEED_CATEGORY}/${FEED_NAME}/${URL_FILENAME}"
                                fi
                            fi
                        fi
                    else
                        # Remove any error log entries for the URL if it failed before
                        REMOVE_URL "${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
                            echo "${DEBUG_LEADER} Not deleting ${DIR_SESSION}/${URL_FILENAME}.servresp"
                        fi
                    fi

                    if (( DEBUG == 1 )) ; then
                        echo "${DEBUG_LEADER} Clear File Vars"
                    fi
                    unset URL_FILENAME
                done

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

                if (( (MOST_RECENT != 0) && (INSTALL_SESSION == 0) )); then
                    for URL in ${FULLINDEXFILE}
                    do
                        if ! grep -F "${URL}" "${DIR_LOG}"/"${LOG_COMPLETE}" >/dev/null ; then
                            URL_FILENAME=$(echo "${URL}" | sed -e 's/.*\/\([^\/]\+\)/\1/' -e 's/%20/ /g')
                            if (( VERBOSITY >= 2 )) ; then
                                    echo "Marking as already downloaded ${URL_FILENAME}."
                            fi
                            echo "${URL}" >> "${DIR_LOG}"/"${LOG_COMPLETE}"
                        fi
                    done
                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
                    PLAYLIST_Sort "${DIR_LIBRARY}" "${PLAYLIST_NAME}"

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

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


            if (( DEBUG == 1 )) ; then
                echo "${DEBUG_LEADER} Clear Server Loop Vars"
            fi
            unset FEED_URL
            unset FEED_CATEGORY
            unset FEED_NAME
            unset URL_FILENAME
            unset URL_USERNAME
            unset 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
            PLAYLIST_Sort "${DIR_LIBRARY}" "${PLAYLIST_NAME}"

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

#                                                                                                                                }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# CLEANUP loop                                                                                                                   {{{


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

    if (( CLEANUP != 0 || CLEANUP_ONLY != 0 )) ; then
        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
        fi
        FILELIST=$(find "${DIR_LIBRARY}"/ -maxdepth 1 -type f -name "*.m3u")
        # Convert CLEANUP_DAYS to CLEANUP_SECONDS (86400 == seconds in a day)
        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.
        DATE_CLEAN2=$(($(date +%s --date 0:00)-CLEANUP_SECONDS))
        while IFS= read -r FILE; do
            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}:"
            fi
            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
                            if (( VERBOSITY >= 2 )) ; then
                                rm -v "${DIR_LIBRARY}/${LINE}"
                            else
                                rm -f "${DIR_LIBRARY}/${LINE}"
                            fi
                        fi
                    fi
                else
                    if (( VERBOSITY >= 2 || CLEANUP_SIMULATE > 0 )) ; then
                        echo "File not found:  ${DIR_LIBRARY}/${LINE}"
                    fi
                fi
            done < "${FILE}"
            if (( CLEANUP_SIMULATE > 0 )); then
                echo "Playlist to remove: ${FILE}"
            else
                if (( VERBOSITY <= 1 )) ; then
                    rm -f "${FILE}"
                else
                    rm -fv "${FILE}"
                fi
            fi
        done <<<"${FILELIST}"
    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
    # 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
        if (( DEBUG == 1 )) ; then
            echo "${DEBUG_LEADER} Build OPT_FEED_PLAYLISTs"
        fi
        # Set header to not be displayed unless active feed configured to require one.
        FEED_PLAYLIST_HEADER=0

        for FILETYPE in utf8 utf16 ; do
            if (( DEBUG == 1 )) ; then
                echo
                case ${FILETYPE} in
                    'utf8')
                        echo "${DEBUG_LEADER} UTF-8 Loop running." ;;
                    'utf16')
                        echo "${DEBUG_LEADER} UTF-16 Loop running." ;;
                esac
            fi
            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
                if (( DEBUG == 1 )) ; then
                    echo "${DEBUG_LEADER} No config file found, exiting loop."
                fi
                continue
            fi

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

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

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

                unset FILTER_TARGET
                for FILTER_TARGET in FEED_CATEGORY FEED_NAME; do
                    FILTER_OPTIONS "${FILTER_TARGET}"
                done

                # Unset options that are not required in this while loop
                unset URL_PASSWORD
                unset URL_USERNAME
                unset WGET_OPTION_DISPOSITION
                unset WGET_OPTION_DISPOSITION_FAIL
                unset WGET_OPTION_NO_CHECK_CERIFICATE
                unset WGET_OPTION_PREFER_IP_TYPE
                unset WGET_OPTION_FILENAME_LOCATION
                unset FEED_SORT_ORDER
                unset POST_WGET_RENAME_MDATE
                unset ATOM_FILTER_SIMPLE
                unset ATOM_FILTER_TYPE
                unset 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

#                    FULL_PLAYLIST_NAME="PLAYLIST_${FEED_NAME//[[:space:]]/_}.m3u"
                    # Replace spaces with underscores and then pipe through tr to limit repetitions.
                    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 -v "${DIR_LIBRARY}/${FULL_PLAYLIST_NAME}"
                        else
                            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}"
                        fi
                        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
                            while read -r ITEM; do
                                if (( DEBUG == 1 )) ; then
                                    echo "${DEBUG_LEADER} FEED Full Playist add ${ITEM}"
                                fi
                                # 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}"
                        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 FEED_URL
                unset FEED_CATEGORY
                unset FEED_NAME
                unset FEED_FULL_PLAYLIST
            done < "${CURRENT_SERVERLIST}"
        done
    fi
fi

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

if [[ -n ${IMPORT_OPML+set} ]]; then
    if [[ ${IMPORT_OPML} == "NONE" ]]; then
        echo
        echo "unset FILE or URL to import from."
        CLEANUP_AND_EXIT 1
    fi

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

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

    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

    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

        OLD_IFS=$IFS
        IFS=$'\n'

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

            new_label=$(echo "${data}" | sed -n -e 's/.*text="\([^"]\+\)".*/\1/Ip' | sed -e 's/^\s*[0-9]\+\.\s\+//' -e "s/[:;'\".,!/?<>\\|]//g")
            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.
            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}"
        CLEANUP_AND_EXIT ${ERR_IMPORTOPML}
    fi
fi

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

if [[ -n ${EXPORT_OPML+set} ]]; then
    if [[ ${EXPORT_OPML} == "NONE" ]]; then
        echo
        echo "unset FILE to import to."
        CLEANUP_AND_EXIT 1
    fi

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

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

	while read -r FEED_URL FEED_CATEGORY FEED_NAME ; do
        if   [[ "${FEED_URL:0:1}" == "#" ]] || [[ -z "${FEED_URL-empty}" ]] ; then
            if (( VERBOSITY >= 3 )) ; then
                echo "  Discarding line (comment or blank line)."
            fi
            continue
        fi

        # Remove PASSWORD from FEED_NAME if found.
        FEED_NAME=${FEED_NAME/PASS:+([^[:space:]])}

        # Remove USERNAME from FEED_NAME if found.
        FEED_NAME=${FEED_NAME/USER:+([^[:space:]])}

        # Remove any residual trailing spaces from ${FEED_NAME}
        while (( $(expr "${FEED_NAME}" : ".*[ ]\\+$") > 0 )); do
            FEED_NAME=${FEED_NAME%[ ]*}
        done

        # Remove any residual leading spaces from ${FEED_NAME}
        while (( $(expr "${FEED_NAME}" : "[ ]\\+.*$") > 0 )); do
            FEED_NAME=${FEED_NAME#[ ]*}
        done

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

	echo '</body>
</opml>' >> "${EXPORT_OPML}"
    else
        echo "OPML Export Error: ${EXPORT_OPML}" >> "${DIR_LOG}"/"${LOG_FAIL}"
        CLEANUP_AND_EXIT ${ERR_EXPORTOPML}
    fi
fi

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

if [[ -n ${IMPORT_PCAST+set} ]] ; then
    if [[ ${IMPORT_PCAST} == "NONE" ]]; then
        echo
        echo "unset FILE or URL to import from."
        CLEANUP_AND_EXIT 1
    fi

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

    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

    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.
    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
fi


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

# Disable extended glob matches.
shopt -u extglob

CLEANUP_AND_EXIT 0

#                                                                                                                                }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# Notes:                                                                                                                         {{{
# 1.  Best viewed in Vim (http://vim.sf.net) with the Relaxedgreen colorscheme (vimscripts #791).
#                                                                                                                                }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# vim:tw=132:ts=4:sw=4