#
# <20240304.1724.44>
#
# The expand routine expands wildcards characters and produces as a result
# a list of file names of the found files.
#
# The wildcard input should conform to the 'glob' command with an extension.
# The extension is the 'bash' 'globstar' extension '**/' which must be prefixed
# to the wildcard pattern.
#
# If the 'globstar' (**) precedes the pattern the remainder of the pattern selects
# files as follows:
#
#     pat       result
#     **        all files in '.' and subdirs (including dirs)
#     **/       all dirs in '.'  and subdirs
#     **/*      same as '**'
#     **/<pat>  all files matching <pat> in '.' and subdirs (including dirs)
#     ***       same as '*'
#
# The '**' must be the first two chars in the pattern and the next char. must
# be nil or '/'. These chars form the pattern to use on the files in each dir found
# by '**'.

# First we will determine if we have any wild card patterns at all. If not pass back
# a list containing only the string passed in.

# In all cases we expect a string as input and return a list.
#

proc stringExpand {string} {
  global config dirs
  if {!$config(expandWildCards) ||\
	  ([set first [string index $string 0]] == [set last [string index $string end]] && \
	       $first in {"'" "\""}) ||\
	  ($first == "\{" && $last == "\}") ||\
	  (![string match {*[?*]*} $string] &&
	   ![string match {*\[*\]*} $string])} {
    frputs string "[list $string] "
    return [list $string]
  }
  # Well, it looks like we have pattern
  if {[set globstar [expr {$config(globstar) &&\
			  [string range $string 0 1] == "**" &&\
			       [string index $string 2] != "*"}]]} {
    set pat [string range $string 2 end]
  } else {
    set pat $string
  }
  
  set dirs {""}
  set n -1
  set ret  {}
  # no recursion here, but still...
  while {[set thisDir [lindex $dirs [incr n]]] != {} || $n == 0} {
    frputs thisDir pat globstar n ret
    if {$globstar} {
      lappend dirs {*}[glob -nocomplain -tails -path ./ -type d -- "$thisDir/*"]
      # This supresses a return of "/"
      if {"$thisDir$pat" == "/" } {continue}
    }
    # The "{*}" send no pattern (not {}) to glob which suppresses a "." return
    lappend ret {*}[glob -nocomplain -tails -path ./ -- {*}$thisDir$pat]
  }
  frputs ret dirs n
  return $ret
}
