#!/usr/bin/env bash

# ----------------------------------------------------------------------------------------------------------------------------------
# Filename:      podget                                                                                                          {{{
# Maintainer:    Dave Vehrs (dvehrs on Github.com)
# Copyright:     (c) 2005-2025 Dave Vehrs
#
#                This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
#                License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any
#                later version.
#
#                This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
#                warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
#                details.
#
# Description:   Podget is a simple bash script to automate the downloading and
#                organizing of podcast content.
# Dependencies:  bash, coreutils, findutils, grep, gawk or mawk, libc-bin (for iconv), sed, and wget.
# Installation:  cp podget.sh /usr/local/bin
#                chmod 755 /usr/local/bin/podget.sh                                                                              }}}
# ----------------------------------------------------------------------------------------------------------------------------------
# Debug and Info messages                                                                                                        {{{

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

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

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

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

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

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

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

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

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

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

            fi
        fi
    fi
fi

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

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

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

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

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

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

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

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

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

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

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

  CleanupAndExit 1
}
#                                                                                                                                }}}

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

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

# "Our" Exit codes

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

# Library directory not defined.
ERR_LIBNOTDEF=50

# Library directory available space below limit
ERR_LIBLOWSPACE=51

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

# Another running session already exists.
ERR_RUNNINGSESSION=70

# OPML import error.
ERR_IMPORTOPML=80

# OPML export error.
ERR_EXPORTOPML=90

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

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

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

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

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

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

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

# Enable extended glob matches.
shopt -s extglob

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

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

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

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

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

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

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

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

# Set logging file names
LOG_FAIL=errors
LOG_COMPLETE=done

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

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

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

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

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

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

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

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

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

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

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

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

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

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

# FILENAME_SUFFIX="newtag"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

TEXT_DEFAULT_SERVERLIST

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

: << TEXT_ASX_END
</ASX>
TEXT_ASX_END

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

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

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

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

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

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

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

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

        unset -v i
    fi

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

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

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

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

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

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

}
#                                                                                                                                }}}

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

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

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

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

        unset -v i
    fi

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

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

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

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


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

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

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

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

        CleanupAndExit 1
    fi
}
#                                                                                                                                }}}

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

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

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


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

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

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


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

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

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

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

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

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

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

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

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

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

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

    # close without error
    return 0
}
#                                                                                                                                }}}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}
#                                                                                                                                }}}

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

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

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

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

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

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

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

    unset -v REALPLAYLISTNAME TEMPPLAYLISTNAME
}
#                                                                                                                                }}}

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

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

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

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

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

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

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

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

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

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

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

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

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

                fi

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    local opml_list

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            unset -v WGET_SUBCHAR
            local WGET_SUBCHAR
            WGET_NOTCOUNT=0

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

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

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

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

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

            # clear array and reimport
            unset -v WGET_OPTIONS

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

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

            __MSG_DEBUG "Reset FEED_FULL_PLAYLIST=0"
            local FEED_FULL_PLAYLIST=0

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

            __MSG_DEBUG "Reset WGET_OPTION_DEFAULT_USERAGENT"
            local WGET_OPTION_DEFAULT_USERAGENT=0

            __MSG_DEBUG "Reset WGET_OPTION_FILENAME_LOCATION"
            local WGET_OPTION_FILENAME_LOCATION=0

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

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

            __MSG_DEBUG "Reset WGET_OPTION_DISPOSITION_FAIL"
            local WGET_OPTION_DISPOSITION_FAIL=0

            __MSG_DEBUG "Reset WGET_OPTION_NO_CHECK_CERIFICATE"
            local WGET_OPTION_NO_CHECK_CERIFICATE=0

            __MSG_DEBUG "Reset WGET_OPTION_PREFER_IP_TYPE"
            local WGET_OPTION_PREFER_IP_TYPE=0

            __MSG_DEBUG "Reset WGET_OPTION_RSS_MEDIACONTENT"
            local WGET_OPTION_RSS_MEDIACONTENT=0

            __MSG_DEBUG "Reset POST_WGET_RENAME_MDATE"
            local POST_WGET_RENAME_MDATE=0

            __MSG_DEBUG "Reset POST_WGET_RENAME_TITLETAG"
            local POST_WGET_RENAME_TITLETAG=0

            __MSG_DEBUG "Reset POST_WGET_RENAME_REVTITLETAG"
            local POST_WGET_RENAME_REVTITLETAG=0

            __MSG_DEBUG "Reset ATOM_FILTER_SIMPLE"
            local ATOM_FILTER_SIMPLE=0

            __MSG_DEBUG "Reset ATOM_FILTER_TYPE"
            unset -v ATOM_FILTER_TYPE
            local ATOM_FILTER_TYPE

            __MSG_DEBUG "Reset ATOM_FILTER_LANG"
            unset -v ATOM_FILTER_LANG
            local ATOM_FILTER_LANG

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

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

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

            # Unset options that are not required in this while loop

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            local INDEXFILE_TMP
            local INDEXFILE_TMP2

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

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

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

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

                unset -v i

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

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

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

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

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

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

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

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

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

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

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

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

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

                    fi
                fi

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                    local FINAL_TITLE

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

    unset -v i

    # Both sed statements below use TEST_CHAR as their delimiter

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

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

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

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

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

   __MSG_INFO "ORIGINAL TITLE" "${ORIGINAL_TITLE}"

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

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

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

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

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

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

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

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

    # close without error
    return 0
}
#                                                                                                                                }}}

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

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

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

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

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

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

    local VERSION=1.0.0
    local REPORT_VERSION=0

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

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

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

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

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

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

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

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

    # Simulate cleanup
    local CLEANUP_SIMULATE=0

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

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

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

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

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

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

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

    # Enable playlist creation
    local NO_PLAYLIST=0

    # Default Wget no options
    local WGET_BASEOPTS=""

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    DirectoryCheck DIR_CONFIG

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    __MSG_INFO "Library Directory" "${DIR_LIBRARY}"

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

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

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

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

    __MSG_INFO "Session Directory" "${DIR_SESSION}"

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

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

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

    DirectoryCheck DIR_LOG

    __MSG_INFO "Log Directory" "${DIR_LOG}"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

    return 0
}

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

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

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

# Disable extended glob matches.
shopt -u extglob

CleanupAndExit 0

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