Elizium.Loopz.psm1

using module Elizium.Krayola;
Set-StrictMode -Version 1.0
function Convert-Emojis {
  <#
  .NAME
    Convert-Emojis
 
  .SYNOPSIS
    Converts emojis defined as short codes inside markdown files into their correspond code points.
 
  .DESCRIPTION
    The need for command as a result of the fact that external documentation platforms, in particular
  gitbook, do not currently support the presence of emoji references inside markdown files. Currently,
  emojis can only be correctly rendered if the emoji is represented via its code point representation.
  A user may have a large amount of markdown in multiple projects and converting these all by hand would
  be onerous and impractical. This command will automatically convert all emoji short code references
  into their HTML compliant code point representation; eg, the smiley emoji in short code form :smiley:
  is converted to &#x1f603; The command takes files from the pipeline performs the conversion and depending
  on supplied parameters, will either overwrite the original file or write to a new one. The user can
  feed multiple items via the pipeline and they will all be processed in a batch.
    Emoji code point definitions are acquired via the github emoji api, so only github defined emojis
  are currently supported. Some emojis have multiple code points defined for them and are defined as
  a range of values by the github api, eg ascension_island is defined as range: 1f1e6-1f1e8, so in
  this case, the first item in the range is taken to be the value: 1f1e6.
    WhatIf is supported and when enabled, the files are converted but not saved. This allows the user
  to see if all the emojis contained within are converted successfully as an errors are reported during
  the run.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER InputObject
    The current pipeline item representing a file. Any command that can deliver FileInfo items can be
  used, eg Get-Item for a single item or Get-ChildItem for a collection.
 
  .PARAMETER OutputSuffix
    The suffix appended to the original filename. When specified, the new file generated by the conversion
  process is written with this suffix. When omitted, the original file is over-written.
 
  .PARAMETER QuerySpan
    Defines a period of time during which successive calls to the github api can not be made. The emoji
  list does not change very often, so the result is cached and is referred to on successive invocations
  to avoid un-necessary api calls. The default value is 7 days, which means (assuming the cache has not
  been deleted) that no 2 queries inside the space of a week are issued to the github api.
 
  .EXAMPLE 1
 
  Convert a single and over the original
 
  Get-Item -Path ./README.md | Convert-Emojis
 
  .EXAMPLE 2
 
  Convert a single and create a new corresponding file with 'out' suffix (README-out.md)
 
  Get-Item -Path ./README.md | Convert-Emojis -OutputSuffix out
 
  .EXAMPLE 3
 
  Convert a collection of markdown files with out suffix
 
  Get-ChildItem ./*.md | Convert-Emojis -OutputSuffix out
 
  .EXAMPLE 4
 
  Convert a collection of markdown files without saving
 
  Get-ChildItem ./*.md | Convert-Emojis -WhatIf
 
  #>

  [CmdletBinding(SupportsShouldProcess)]
  [Alias('coji')]
  param(
    [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
    [System.IO.FileInfo[]]$InputObject,

    [Parameter()]
    [string]$OutputSuffix,

    [Parameter()]
    [TimeSpan]$QuerySpan = $(New-TimeSpan -Days 7),

    [Parameter()]
    [DateTime]$Now = $(Get-Date),

    [Parameter()]
    [switch]$Test
  )

  begin {
    [Krayon]$krayon = Get-Krayon
    [hashtable]$signals = Get-Signals;
    [Scribbler]$scribbler = New-Scribbler -Krayon $krayon -Test:$Test.IsPresent;

    [MarkDownEmojiConverter]$converter = New-EmojiConverter -Now $Now -QuerySpan $QuerySpan;
    $converter.Init();

    [string]$resetSn = $scribbler.Snippets('Reset');
    [string]$lnSn = $scribbler.Snippets('Ln');
    [string]$metaSn = $scribbler.WithArgSnippet('ThemeColour', 'meta');

    function Group-Pairs {
      # to go into Krayola
      [CmdletBinding()]
      [OutputType([line[]])]
      param(
        [Parameter(Mandatory)]
        [couplet[]]$Pairs,

        [Parameter(Mandatory)]
        [int]$Size
      )

      [line[]]$lines = @();
      [couplet[]]$current = @();
      [int]$counter = 0;
      $Pairs | ForEach-Object {
        if ((($counter + 1) % $Size) -eq 0) {
          $current += $_;
          $lines += New-Line $current;
          $current = @();
        }
        else {
          $current += $_;
        }
        $counter++;
      }

      if ($current.Count -gt 0) {
        $lines += New-Line $current;
      }

      return $lines;
    }
    $scribbler.Scribble("$($resetSn)$($metaSn)$($LoopzUI.LightDashLine)$($lnSn)");
  }

  process {
    [string]$documentPath = $_.FullName;
    [System.IO.DirectoryInfo]$directory = $_.Directory;
    [string[]]$document = $converter.Read($documentPath);
    [PSCustomObject]$result = $converter.Convert($document);
    $scribbler.Reset().End();

    [string]$outputPath = if ($PSBoundParameters.ContainsKey('OutputSuffix')) {
      if (-not(Test-IsFileSystemSafe -Value $OutputSuffix)) {
        throw [ArgumentException]::new(
          "OutputSuffix ('$($OutputSuffix)') parameter contains characters not safe for the file system"
        )
      }

      [string]$filename = [System.IO.Path]::GetFileNameWithoutExtension($documentPath);
      [string]$extension = [System.IO.Path]::GetExtension($documentPath);
      [string]$outputFilename = "$($filename)-$($OutputSuffix)$($extension)";
      Join-Path -Path $directory.FullName -ChildPath $outputFilename;
    }
    else {
      $documentPath;
    }

    if (-not($PSBoundParameters.ContainsKey('WhatIf'))) {
      $converter.Write($outputPath, $result.Document);
    }    

    [string]$outputSpecifier = [string]::IsNullOrEmpty($OutputSuffix) `
      ? "OVERWRITE" : $([System.IO.Path]::GetFileName($outputPath));

    [string]$outputAffirm = [string]::IsNullOrEmpty($OutputSuffix);

    [string]$indicator = $signals[$($result.TotalMissingCount -eq 0 ? 'OK-A' : 'BAD-A')].Value;
    [string]$message = "Converted document {0}" -f $indicator;
    [string]$filler = [string]::new(' ', $message.Length);

    [couplet]$documentPair = New-Pair $($documentPath, $outputSpecifier, $outputAffirm);
    [couplet[]]$documentPairs = @($documentPair);

    if ($PSBoundParameters.ContainsKey('WhatIf')) {
      [couplet]$whatIfSignal = Get-FormattedSignal -Name 'WHAT-IF' `
        -Signals $signals -EmojiAsValue -EmojiOnlyFormat '{0}';
      $documentPairs += $whatIfSignal;
    }

    [line]$documentLine = New-Line $($documentPairs);

    $scribbler.Line($message, $documentLine).End();

    if ($result.TotalMissingCount -gt 0) {
      [couplet[]]$pairs = $result.MissingConversions.Keys | Sort-Object | ForEach-Object {
        [int]$lineNo = $_;
        [string[]]$emojis = $result.MissingConversions[$_];

        New-Pair $("line: $lineNo", $($emojis -join ', '));
      }

      Group-Pairs -Pairs $pairs -Size 4 | ForEach-Object {
        $scribbler.Line($filler, $_).End();        
      }
    }

    $scribbler.Flush();
  }

  end {
    $scribbler.Scribble("$($resetSn)$($metaSn)$($LoopzUI.LightDashLine)$($lnSn)");
    $scribbler.Flush();
  }
}

function Select-Patterns {
  <#
  .NAME
    Select-Patterns
 
  .SYNOPSIS
    This is a simplified yet enhanced version of standard Select-String command (or
  the grep command on Linux/Unix/mac) that allows the user to run multiple searches
  which are chained together to produce its final result.
 
  .DESCRIPTION
    The main rationale for using this command ("greps" as in multiple grep invokes) instead
  of Select-String, is for the provision of multiple patterns. Now, Select-String does
  allow the user to provide multiple Patterns, but the result is a logical OR rather
  than an AND. greps uses AND by piping the result of each individual Pattern search to
  the next Pattern search so the result is those lines found that match all the patterns
  provided rather than all lines that match 1 or more of the patterns. The user can achieve
  OR functionality by using a | inside the same string; for example to find all lines
  that contain any of the patterns 'red', 'green' or 'blue', they could just use
  'red|green|blue'.
    At the end of the run, greps displays the full command (containing multiple pipeline
  legs, one for each pattern provided). If so required, the user can re-run the command
  by running the full command which is displayed and providing different parameters not
  directly supported by greps.
    'greps', does not currently support input from the pipeline. Perhaps this will be
  implemented in a future release.
    At some point in the future, it is intended to further enhance greps using a coloured
  output, whereby a colour is assigned to each pattern and that colour is used to render the
  result. So where the user has provided multiple patterns, currently, only the first pattern
  is highlighted in the result. With the coloured enhancement, the user will be able to see
  all pattern matches in the result with each match displayed in the corresponding allocated
  colour.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER filter
    Defines which files are considered in the search. It can be a path with a wildcard or
  simply a wildcard. If its just a wildcard (eg *.txt), then files considered will be from
  the current directory only.
    The user can define a default filter in the environment as variable 'LOOPZ_GREPS_FILTER'
  which should be a glob such as '*.txt' to represent all text files. If no filter parameter
  is supplied to the greps invoke, then the filter is defined by the value of
  'LOOPZ_GREPS_FILTER'.
 
  .PARAMETER Patterns
    An array of patterns. The result shows all lines that match all the patterns specified.
  An individual pattern can be prefixed with a not op: '!', which means exclude those lines
  which match the subsequent pattern; it is a more succinct way of specifying the -NotMatch
  operator on Select-String. The '!' is not part of the pattern.
 
  .EXAMPLE 1
    Show lines in all .txt files in the current directory files that contain the patterns
  'red' and 'blue':
  greps red, blue *.txt
 
  .EXAMPLE 2
    Show lines in all .txt files in home directory that contain the patterns 'green lorry' and
  'yellow lorry':
  greps 'green lorry', 'yellow lorry' ~/*.txt
 
  .EXAMPLE 3
    Show lines in all files defined in environment as 'LOOPZ_GREPS_FILTER' that contains
  'foo' but not 'bar':
  greps foo, !bar
 
  #>

  [CmdletBinding()]
  [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingInvokeExpression', '')]
  [Alias("greps")]
  param
  (
    [parameter(Mandatory = $true, Position = 0)]
    [ValidateNotNullOrEmpty()]
    [String[]]$Patterns,

    [parameter(Position = 1)]
    [String]$Filter = $(Get-EnvironmentVariable -Variable 'LOOPZ_GREPS_FILTER' -Default './*.*'),

    [Parameter()]
    [switch]$Test
  )
  function build-command {
    [OutputType([string])]
    param(
      [string]$Pattern,
      [string]$Filter,
      [switch]$Pipe,
      [string]$NotOpSymbol = '!'
    )
    [string]$platform = Get-PlatformName;
    [System.Text.StringBuilder]$builder = [System.Text.StringBuilder]::new();

    if ($Pipe.ToBool()) {
      $null = $builder.Append(' | ');
    }

    if ($platform -eq 'windows') {
      $null = $builder.Append('select-string ');
      if ($pattern.StartsWith($NotOpSymbol)) {
        $null = $builder.Append($('-notmatch -pattern "{0}" ' -f $Pattern.Substring(1)));
      }
      else {
        $null = $builder.Append($('-pattern "{0}" ' -f $Pattern));
      }
    }
    else {
      $builder.Append('grep ');
      if ($pattern.StartsWith($NotOpSymbol)) {
        $null = $builder.Append($('-v -i "{0}" ' -f $Pattern.Substring(1)));
      }
      else {
        $null = $builder.Append($('-i "{0}" ' -f $Pattern));
      }
    }

    if (-not([string]::IsNullOrWhiteSpace($Filter))) {
      $null = $builder.Append("$Filter ");
    }

    return $builder.ToString();
  } # build-command

  [boolean]$first = $true;
  [string]$command = -join $(foreach ($pat in $Patterns) {
      ($first) `
        ? $(build-command -Pattern $Patterns[0] -Filter $Filter) `
        : $(build-command -Pipe -Pattern $pat);

      $first = $false;
    });

  [hashtable]$signals = $(Get-Signals);
  [Scribbler]$scribbler = New-Scribbler -Test:$Test.IsPresent;
    
  [couplet]$formattedSignal = Get-FormattedSignal -Name 'GREPS' -Value $command -Signals $signals;

  # This is one of those very few situations where we don't re-direct to null the result of executing a
  # command; this is the command's raison d'etre.
  #
  Invoke-Expression $command;

  [string]$keySnippet = $scribbler.Snippets('blue');
  [string]$arrowSnippet = $scribbler.Snippets('red');
  [string]$signalSnippet = $scribbler.Snippets('green');
  [string]$lnSnippet = $scribbler.Snippets('Ln');

  $scribbler.Scribble(
    $("$($keySnippet)$($formattedSignal.Key)$($arrowSnippet) --> $($signalSnippet)$($command)$($lnSnippet)")
  );

  $scribbler.Flush();
}

function Show-Signals {
  <#
  .NAME
    Show-Signals
 
  .SYNOPSIS
    Shows all defined signals, including user defined signals.
 
  .DESCRIPTION
    User can override signal definitions in their profile, typically using the provided
  function Update-CustomSignals.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER SourceSignals
    Hashtable containing signals to be displayed.
 
  .PARAMETER Registry
    Hashtable containing information concerning commands usage of signals.
 
  .PARAMETER Include
    Provides a filter. When specified, only the applications included in the list
  will be shown.
 
  .EXAMPLE 1
 
  Show-Signals
 
  Show signal definitions and references for all registered commands
 
  .EXAMPLE 2
 
  Show-Signals -Include remy, ships
 
  Show the signal definitions and references for commands 'remy' and 'ships' only
  #>

  [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '')]
  param(
    [Parameter()]
    [hashtable]$SourceSignals = $(Get-Signals),

    [Parameter()]
    [hashtable]$Registry = $($Loopz.SignalRegistry),

    [Parameter()]
    [string[]]$Include = @(),

    [Parameter()]
    [switch]$Test
  )

  function get-GraphemeLength {
    param(
      [Parameter(Position = 0)]
      [string]$Value
    )
    [System.Text.StringRuneEnumerator]$enumerator = $Value.EnumerateRunes();
    [int]$count = 0;

    while ($enumerator.MoveNext()) {
      $count++;
    }

    return $count;
  }

  function get-TextElementLength {
    param(
      [Parameter(Position = 0)]
      [string]$Value
    )
    # This function is of no use, but leaving it in for reference, until the
    # issue of bad emoji behaviour has been fixed.
    #
    [System.Globalization.TextElementEnumerator]$enumerator = `
      [System.Globalization.StringInfo]::GetTextElementEnumerator($Value);

    [int]$count = 0;

    while ($enumerator.MoveNext()) {
      $count++;
    }

    return $count;
  }

  [hashtable]$theme = Get-KrayolaTheme;
  [Krayon]$krayon = New-Krayon -Theme $theme;
  [Scribbler]$scribbler = New-Scribbler -Krayon $krayon -Test:$Test.IsPresent;

  if ($Include.Count -eq 0) {
    $Include = $Registry.PSBase.Keys;
  }

  [scriptblock]$renderCell = {
    [OutputType([boolean])]
    param(
      [string]$column,
      [string]$value,
      [PSCustomObject]$row,
      [PSCustomObject]$options,
      [object]$scribbler,
      [int]$counter
    )
    [boolean]$result = $true;
    [boolean]$alternate = ($counter % 2) -eq 1;
    [string]$backSnippet = $alternate `
      ? $options.Custom.Snippets.ResetAlternateBack 
    : $options.Custom.Snippets.ResetDefaultBack;

    switch -Regex ($column) {
      'Name' {
        [string]$nameSnippet = ($row.Length.Trim() -eq '2') `
          ? $options.Custom.Snippets.Standard : $options.Custom.Snippets.Cell;

        $scribbler.Scribble("$($backSnippet)$($nameSnippet)$($value)");
        break;
      }

      'Icon' {
        # This tweak is required because unfortunately, some emojis are ill
        # defined causing misalignment.
        #
        if ($options.Custom.UsingEmojis) {
          [string]$length = $row.Length.Trim();
          if ($length -eq '1') {
            # Chop off the last character
            #
            $value = $value -replace ".$";
          }
        }
        $scribbler.Scribble("$($backSnippet)$($value)");
        break;
      }

      'Length|GraphLn' {
        $scribbler.Scribble("$($backSnippet)$($value)");
        break;
      }

      'Custom' {
        [string]$padded = Format-BooleanCellValue -Value $value -TableOptions $options;
        $null = $scribbler.Scribble("$($backSnippet)$($padded)$($endOfRowSnippet)");

        break;
      }

      default {
        if ($Registry.ContainsKey($column)) {
          [string]$padded = Format-BooleanCellValue -Value $value -TableOptions $options;
          $null = $scribbler.Scribble("$($backSnippet)$($padded)");
        }
        else {
          $scribbler.Scribble("$($backSnippet)$($value)");
        }
      }
    }

    return $result;
  } # RenderCell

  [string]$resetSnippet = $scribbler.Snippets(@('Reset'));
  [string]$endOfRowSnippet = $resetSnippet;
  [string]$headerSnippet = $scribbler.Snippets(@('white', 'bgDarkBlue'));
  [string]$underlineSnippet = $scribbler.Snippets(@('darkGray'));
  [string]$standardSnippet = $scribbler.Snippets(@('darkGreen'));
  [string]$alternateBackSnippet = $scribbler.Snippets(@('bgDarkGray'));
  [string]$defaultBackSnippet = $scribbler.Snippets(@(
      'bg' + $scribbler.Krayon.getDefaultBack()
    ));

  # Make sure that 'Custom' is always the last column
  #
  [string[]]$columnSelection = @('Name', 'Label', 'Icon', 'Length', 'GraphLn') + $(
    $Registry.PSBase.Keys | Where-Object { $Include -contains $_ } | ForEach-Object { $_; }
  ) + 'Custom';

  [PSCustomObject]$custom = [PSCustomObject]@{
    Snippets    = [PSCustomObject]@{
      Header             = $headerSnippet;
      Underline          = $underlineSnippet;
      Standard           = $standardSnippet;
      ResetAlternateBack = "$($resetSnippet)$($alternateBackSnippet)";
      AlternateBack      = "$($alternateBackSnippet)";
      ResetDefaultBack   = "$($resetSnippet)$($defaultBackSnippet)";
    }
    Colours     = [PSCustomObject]@{
      Title = 'darkYellow';
    }
    UsingEmojis = Test-HostSupportsEmojis;
  }

  [PSCustomObject]$tableOptions = Get-TableDisplayOptions -Select $columnSelection `
    -Signals $SourceSignals -Scribbler $scribbler -Custom $custom;

  [string[]]$customKeys = $Loopz.CustomSignals.PSBase.Keys;
  [PSCustomObject[]]$source = $($SourceSignals.GetEnumerator() | ForEach-Object {
      [string]$signalKey = $_.Key;

      [PSCustomObject]$signalDef = [PSCustomObject]@{
        Name    = $_.Key;
        Label   = $_.Value.Key;
        Icon    = $_.Value.Value;
        Length  = $_.Value.Value.Length;
        GraphLn = $(get-GraphemeLength $_.Value.Value);
        Custom  = $($customKeys -contains $signalKey);
      }

      # Now add onto the signal definition, the dependent registered commands
      #
      $Registry.GetEnumerator() | Foreach-Object {
        [string]$commandAlias = $_.Key;
        [boolean]$isUsedBy = $_.Value -contains $signalKey;
        $signalDef | Add-Member -MemberType NoteProperty -Name $commandAlias -Value $isUsedBy;
      }

      $signalDef;
    });

  # NB: The $_ here is within the context of the Select-Object statement just below
  #
  [array]$selection = @(
    'Name'
    @{Name = 'Label'; Expression = { $_.Label }; }
    @{Name = 'Icon'; Expression = { $_.Icon }; }
    @{Name = 'Length'; Expression = { $_.Length }; }
    @{Name = 'GraphLn'; Expression = { $_.GraphLn }; }
    @{Name = 'Custom'; Expression = { $_.Custom }; }
  );

  $selection += $(foreach ($alias in $Registry.PSBase.Keys) {
      @{Name = $alias; Expression = { $_.$alias }; }
    })

  [PSCustomObject[]]$resultSet = ($source | Select-Object -Property $selection);
  [hashtable]$fieldMetaData = Get-FieldMetaData -Data $resultSet;

  [hashtable]$headers, [hashtable]$tableContent = Get-AsTable -MetaData $fieldMetaData `
    -TableData $source -Options $tableOptions;

  [string]$title = 'Signal definitions and references';
  Show-AsTable -MetaData $fieldMetaData -Headers $headers -Table $tableContent `
    -Scribbler $scribbler -Options $tableOptions -Render $renderCell -Title $title;

  $scribbler.Scribble("$($tableOptions.Snippets.Ln)");

  $scribbler.Flush();
} # Show-Signals

function Update-CustomSignals {
  <#
  .NAME
    Update-CustomSignals
 
  .SYNOPSIS
    Allows user to override the emoji's for commands
 
  .DESCRIPTION
    A user may want to customise the appear of commands that use signals in their
  display. The user can specify overrides for any of the declared signals (See
  Show-Signals). Typically, the user should invoke this in their profile script.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Signals
    A hashtable containing signal overrides.
 
  .EXAMPLE 1
  Override signals 'PATTERN' and 'LOCKED' with custom emojis.
 
  [hashtable]$myOverrides = @{
    'PATTERN' = $(kp(@('Capture', '👾')));
    'LOCKED' = $(kp(@('No soup for you', '🥣')));
  }
  Update-CustomSignals -Signals $myOverrides
  #>

  [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
  param(
    [Parameter(Mandatory)]
    [hashtable]$Signals
  )

  if ($Signals -and ($Signals.Count -gt 0)) {
    if ($Loopz) {
      if (-not($Loopz.CustomSignals)) {
        $Loopz.CustomSignals = @{}
      }

      $Signals.GetEnumerator() | ForEach-Object {
        if ($_.Value -and ($_.Value -is [couplet])) {
          $Loopz.CustomSignals[$_.Key] = $_.Value;
        }
        else {
          Write-Warning "Loopz: Skipping custom signal('$($_.Key)'); not a valid couplet/pair: -->$($_.Value)<--";
        }
      }
    }
  }
}

function Get-FormattedSignal {
  <#
  .NAME
    Get-FormattedSignal
 
  .SYNOPSIS
    Controls and standardises the way that signals are displayed.
 
  .DESCRIPTION
    This function enables the display of key/value pairs where the key includes
  an emoji. The value may also include the emoji depending on how the function
  is used.
    Generally, this function returns either a Pair object or a single string.
  The user can define a format string (or simply use the default) which controls
  how the signal is displayed. If the function is invoked without a Value, then
  a formatted string is returned, otherwise a pair object is returned.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER CustomLabel
    An alternative label to display overriding the signal's defined label.
 
  .PARAMETER EmojiAsValue
    switch which changes the result so that the emoji appears as part of the
  value as opposed to the key.
 
  .PARAMETER EmojiOnly
    Changes what is returned, to be a single value only, formatted as EmojiOnlyFormat.
 
  .PARAMETER EmojiOnlyFormat
    When the switch EmojiOnly is enabled, EmojiOnlyFormat defines the format used to create
  the result. Should contain at least 1 occurrence of {1} representing the
  emoji.
 
  .PARAMETER Format
    A string defining the format defining how the signal is displayed. Should
  contain either {0} representing the signal's emoji or {1} the label. They
  can appear as many time as is required, but there should be at least either
  one of these.
 
  .PARAMETER Name
    The name of the signal
 
  .PARAMETER Signals
    The signals hashtable collection from which to select the signal from.
 
  .PARAMETER Value
    A string defining the Value displayed when the signal is a Key/Value pair.
 
  #>

  param(
    [Parameter(Mandatory)]
    [string]$Name,

    [Parameter()]
    [string]$Format = '[{1}] {0}', # 0=Label, 1=Emoji

    [Parameter()]
    [string]$Value,

    [Parameter()]
    [hashtable]$Signals = $(Get-Signals),

    [Parameter()]
    [string]$CustomLabel,

    [Parameter()]
    [string]$EmojiOnlyFormat = '[{0}] ',

    [Parameter()]
    [switch]$EmojiOnly,

    [Parameter()]
    [switch]$EmojiAsValue
  )

  [couplet]$signal = $Signals.ContainsKey($Name) `
    ? $Signals[$Name] `
    : $(New-Pair(@($("??? ({0})" -f $Name), $(Resolve-ByPlatform -Hash $Loopz.MissingSignal).Value)));

  [string]$label = ($PSBoundParameters.ContainsKey('CustomLabel') -and
    (-not([string]::IsNullOrEmpty($CustomLabel)))) ? $CustomLabel : $signal.Key;

  [string]$formatted = $EmojiOnly.ToBool() `
    ? $EmojiOnlyFormat -f $signal.Value : $Format -f $label, $signal.Value;

  $result = if ($PSBoundParameters.ContainsKey('Value')) {
    New-Pair($formatted, $Value);
  }
  elseif ($EmojiAsValue.ToBool()) {
    New-Pair($label, $($EmojiOnlyFormat -f $signal.Value));
  }
  else {
    $formatted;
  }

  return $result;
}

function Get-PaddedLabel {
  <#
  .NAME
    Get-PaddedLabel
 
  .SYNOPSIS
    Controls and standardises the way that signals are displayed.
 
  .DESCRIPTION
    Pads out a string with leading or trailing spaces depending on
  alignment.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Align
    Left or right alignment of the label.
 
  .PARAMETER Label
    The string to be padded
 
  .PARAMETER Width
    Size of the field into which the label is to be placed.
 
  #>

  [OutputType([string])]
  param(
    [Parameter()]
    [string]$Label,

    [Parameter()]
    [string]$Align = 'right',

    [Parameter()]
    [int]$Width
  )
  [int]$length = $Label.Length;

  [string]$result = if ($length -lt $Width) {
    [string]$padding = [string]::new(' ', $($Width - $length))
    ($Align -eq 'right') ? $($padding + $Label) : $($Label + $padding);
  } else {
    $Label;
  }

  $result;
}

function Get-Signals {
  <#
  .NAME
    Get-Signals
 
  .SYNOPSIS
    Returns a copy of the Signals hashtable.
 
  .DESCRIPTION
    The signals returned include the user defined signal overrides.
 
  NOTE: 3rd party commands need to register their signal usage with the signal
  registry. This can be done using command Register-CommandSignals and would
  be best performed at module initialisation stage invoked at import time.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Custom
    The hashtable instance containing custom overrides. Does not need to be
  specified by the client as it is defaulted.
 
  .PARAMETER SourceSignals
    The hashtable instance containing the main signals. Does not need to be
  specified by the client as it is defaulted.
 
  #>

  [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '')]
  [OutputType([hashtable])]
  param(
    [Parameter()]
    [hashtable]$SourceSignals = $global:Loopz.Signals,

    [Parameter()]
    [hashtable]$Custom = $global:Loopz.CustomSignals
  )

  [hashtable]$result = $SourceSignals.Clone();

  if ($Custom -and ($Custom.Count -gt 0)) {
    $Custom.GetEnumerator() | ForEach-Object {
      try {
        $result[$_.Key] = $_.Value;
      }
      catch {
        Write-Error "Skipping custom signal: '$($_.Key)'";
      }
    }
  }

  return $result;
}
$global:LoopzHelpers = @{
  # Helper Script Blocks
  #
  WhItemDecoratorBlock = [scriptblock] {
    param(
      [Parameter(Mandatory)]
      $_underscore,

      [Parameter(Mandatory)]
      [int]$_index,

      [Parameter(Mandatory)]
      [hashtable]$_exchange,

      [Parameter(Mandatory)]
      [boolean]$_trigger
    )

    return Write-HostFeItemDecorator -Underscore $_underscore `
      -Index $_index `
      -Exchange $_exchange `
      -Trigger $_trigger
  } # WhItemDecoratorBlock

  HeaderBlock          = [scriptblock] {
    param(
      [hashtable]$Exchange = @{}
    )

    Show-Header -Exchange $Exchange;
  } # HeaderBlock

  SummaryBlock         = [scriptblock] {
    param(
      [int]$Count,
      [int]$Skipped,
      [int]$Errors,
      [boolean]$Triggered,
      [hashtable]$Exchange = @{}
    )

    Show-Summary -Count $Count -Skipped $Skipped `
      -Errors $Errors -Triggered $Triggered -Exchange $Exchange;
  } # SummaryBlock
}

# Session UI state
#
[int]$global:_LineLength = 121;
[int]$global:_SmallLineLength = 81;
#
$global:LoopzUI = [ordered]@{
  # Line definitions:
  #
  UnderscoreLine      = ([string]::new("_", $_LineLength));
  EqualsLine          = ([string]::new("=", $_LineLength));
  DotsLine            = ([string]::new(".", $_LineLength));
  DashLine            = ([string]::new("-", $_LineLength));
  LightDotsLine       = (([string]::new(".", (($_LineLength - 1) / 2))).Replace(".", ". ") + ".");
  LightDashLine       = (([string]::new("-", (($_LineLength - 1) / 2))).Replace("-", "- ") + "-");
  TildeLine           = ([string]::new("~", $_LineLength));

  SmallUnderscoreLine = ([string]::new("_", $_SmallLineLength));
  SmallEqualsLine     = ([string]::new("=", $_SmallLineLength));
  SmallDotsLine       = ([string]::new(".", $_SmallLineLength));
  SmallDashLine       = ([string]::new("-", $_SmallLineLength));
  SmallLightDotsLine  = (([string]::new(".", (($_SmallLineLength - 1) / 2))).Replace(".", ". ") + ".");
  SmallLightDashLine  = (([string]::new("-", (($_SmallLineLength - 1) / 2))).Replace("-", "- ") + "-");
  SmallTildeLine      = ([string]::new("~", $_SmallLineLength));
}

$global:Loopz = [PSCustomObject]@{
  InlineCodeToOption    = [hashtable]@{
    'm' = 'Multiline';
    'i' = 'IgnoreCase';
    'x' = 'IgnorePatternWhitespace';
    's' = 'Singleline';
    'n' = 'ExplicitCapture';
  }

  FsItemTypePlaceholder = '*{_fileSystemItemType}';
  DependencyPlaceholder = '*{_dependency}';

  SignalLabel           = 0;
  SignalEmoji           = 1;

  MissingSignal         = @{
    'windows' = (@('???', '🔻', '?!'));
    'linux'   = (@('???', '🔴', '?!'));
    'mac'     = (@('???', '🔺', '?!'));
  }

  # TODO:
  # - See
  # * https://devblogs.microsoft.com/commandline/windows-command-line-unicode-and-utf-8-output-text-buffer/
  # * https://stackoverflow.com/questions/49476326/displaying-unicode-in-powershell
  #
  DefaultSignals        = [ordered]@{
    # Operations
    #
    'CUT-A'           = (@('Cut', '✂️', ' Σ'));
    'CUT-B'           = (@('Cut', '🦄', ' Σ'));
    'COPY-A'          = (@('Copy', '🍒', ' ©️'));
    'COPY-B'          = (@('Copy', '😺', ' ©️'));
    'MOVE-A'          = (@('Move', '🍺', '≈≈'));
    'MOVE-B'          = (@('Move', '🦊', '≈≈'));
    'PASTE-A'         = (@('Paste', '🌶️', ' ¶'));
    'PASTE-B'         = (@('Paste', '🦆', ' ¶'));
    'OVERWRITE-A'     = (@('Overwrite', '♻️', ' Ø'));
    'OVERWRITE-B'     = (@('Overwrite', '❗', '!!'));
    'PREPEND'         = (@('Prepend', '⏭️', '>|'));
    'APPEND'          = (@('Append', '⏮️', '|<'));
    'EJECT'           = (@('Append', '⏏️', '^_'));

    # Thingies
    #
    'DIRECTORY-A'     = (@('Directory', '📁', 'd>'));
    'DIRECTORY-B'     = (@('Directory', '📂', 'D>'));
    'FILE-A'          = (@('File', '💠', 'f>'));
    'FILE-B'          = (@('File', '📝', 'F>'));
    'PATTERN'         = (@('Pattern', '🛡️', 'p:'));
    'WITH'            = (@('With', '🍑', ' Ψ'));
    'CRUMB-A'         = (@('Crumb', '🎯', '+'));
    'CRUMB-B'         = (@('Crumb', '🧿', '+'));
    'CRUMB-C'         = (@('Crumb', '💎', '+'));
    'SUMMARY-A'       = (@('Summary', '🔆', '*'));
    'SUMMARY-B'       = (@('Summary', '✨', '*'));
    'MESSAGE'         = (@('Message', 'Ⓜ️', '()'));
    'CAPTURE'         = (@('Capture', '☂️', 'λ'));
    'MISSING-CAPTURE' = (@('Missing Capture', '☔', '!λ'));

    # Media
    #
    'AUDIO'           = (@('Audio', '🎶', '_A'));
    'TEXT'            = (@('Text', '🆎', '_T'));
    'DOCUMENT'        = (@('Document', '📜', '_D'));
    'IMAGE'           = (@('Image', '🌌', '_I'));
    'MOVIE'           = (@('Movie', '🎬', '_M'));

    # Indicators
    #
    'WHAT-IF'         = (@('WhatIf', '☑️', '✓'));
    'WARNING-A'       = (@('Warning', '⚠️', ')('));
    'WARNING-B'       = (@('Warning', '👻', ')('));
    'SWITCH-ON'       = (@('On', '✔️', '✓'));
    'SWITCH-OFF'      = (@('Off', '✖️', '×'));
    'INVALID'         = (@('Invalid', '❌', 'XX'));
    'BECAUSE'         = (@('Because', '⚗️', '??'));
    'OK-A'            = (@('OK', '🚀', ':)'));
    'OK-B'            = (@('OK', '🌟', ':D'));
    'BAD-A'           = (@('Bad', '💥', ' ß'));
    'BAD-B'           = (@('Bad', '💢', ':('));
    'PROHIBITED'      = (@('Prohibited', '🚫', ' þ'));
    'INCLUDE'         = (@('Include', '➕', '++'));
    'EXCLUDE'         = (@('Exclude', '➖', '--'));
    'SOURCE'          = (@('Source', '🎀', '+='));
    'DESTINATION'     = (@('Destination', '☀️', '=+'));
    'TRIM'            = (@('Trim', '🌊', '%%'));
    'MULTI-SPACES'    = (@('Spaces', '❄️', '__'));
    'DIAGNOSTICS'     = (@('Diagnostics', '🧪', ' Δ'));
    'LOCKED'          = (@('Locked', '🔐', '>/'));
    'NOVICE'          = (@('Novice', '🔰', ' Ξ'));
    'TRANSFORM'       = (@('Transform', '🤖', ' τ'));
    'BULLET-A'        = (@('Bullet Point', '🔶', '⬥'));
    'BULLET-B'        = (@('Bullet Point', '🟢', '⬡'));
    'BULLET-C'        = (@('Bullet Point', '🟨', '⬠'));
    'BULLET-D'        = (@('Bullet Point', '💠', '⬣'));

    # Outcomes
    #
    'FAILED-A'        = (@('Failed', '☢️', '$!'));
    'FAILED-B'        = (@('Failed', '💩', '$!'));
    'SKIPPED-A'       = (@('Skipped', '💤', 'zz'));
    'SKIPPED-B'       = (@('Skipped', '👾', 'zz'));
    'ABORTED-A'       = (@('Aborted', '✖️', 'o:'));
    'ABORTED-B'       = (@('Aborted', '👽', 'o:'));
    'CLASH'           = (@('Clash', '📛', '>¬'));
    'NOT-ACTIONED'    = (@('Not Actioned', '⛔', '-¬'));

    # Command Specific
    #
    'REMY.ANCHOR'     = (@('Anchor', '⚓', ' §'));
    'REMY.POST'       = (@('Post Process', '🌈', '=>'));
    'REMY.DROP'       = (@('Drop', '💧', ' ╬'));
    'REMY.UNDO'       = (@('Undo Rename', '❎', ' μ'));
    'REMY.DASHES'     = (@('Dashes', '➖', '--'));
    'GREPS'           = (@('greps', '🔍', 'γ'));
    'PLOG'            = (@('PoSh Log', '📜', '~|'));
  }

  OverrideSignals       = @{ # Label, Emoji
    'windows' = @{
      # defaults based on windows, so there should be no need for overrides
    };

    'linux'   = @{
      # tbd
    };

    'mac'     = @{
      # tbd
    };
  }

  # DefaultSignals resolved into Signals by Initialize-Signals
  #
  Signals               = $null;

  # User defined signals, should be populated by profile
  #
  CustomSignals         = $null;

  SignalRegistry        = @{
    'greps' = @('GREPS');

    'sharp' = @(
      'BULLET-A', 'BULLET-C', 'BULLET-D'
    );

    'ships' = @(
      'BULLET-B', 'SWITCH-ON', 'SWITCH-OFF'
    );

    'shire' = @(
      'FAILED-A', 'INVALID', 'OK-A'
    );

    'coji' = @(
      'OK-A', 'BAD-A', 'WHAT-IF'
    );
  }

  InvalidCharacterSet   = [char[]]'<>:"/\|?*';
}

function Initialize-ShellOperant {
  <#
  .NAME
    Initialize-ShellOperant
 
  .SYNOPSIS
    Operant factory function.
 
  .DESCRIPTION
    By default all operant related files are stored somewhere inside the home path.
  Actually, a predefined subpath under home is used. This can be customised by the user
  by them defining an alternative path (in the environment as 'ELIZIUM_PATH'). This
  alternative path can be relative or absolute. Relative paths are relative to the
  home directory.
    The options specify how the operant is created and must be a PSCustomObject with
  the following fields (examples provided inside brackets relate to Rename-Many command):
  + SubRoot: This field is optional and specifies another sub-directory under which
  + ShortCode ('remy'): a short string denoting the related command
  + OperantName ('UndoRename'): name of the operant class required
  + Shell ('PoShShell'): The type of shell that the command should be generated for. So
  for PowerShell the user would specify 'PoShShell' (which for the time being is the
  only shell supported).
  + BaseFilename ('undo-rename'): the core part of the file name which should reflect
  the nature of the operant (the operation, which ideally should be a verb noun pair
  but is not enforced)
  + DisabledEnVar ('REXFS_REMY_UNDO_DISABLED'): The environment variable used to disable
  this operant.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER DryRun
    Similar to WhatIf, but by passing ShouldProcess process for custom handling of
  dry run scenario. DryRun should be set if WhatIf is enabled.
 
  .PARAMETER Options
    (See command description for $Options field descriptions).
 
  .EXAMPLE 1
  Operant options for Rename-Many(remy) command
 
  [PSCustomObject]$operantOptions = [PSCustomObject]@{
    ShortCode = 'remy';
    OperantName = 'UndoRename';
    Shell = 'PoShShell';
    BaseFilename = 'undo-rename';
    DisabledEnVar = 'REXFS_REMY_UNDO_DISABLED';
  }
 
  The undo script is written to a directory denoted by the 'ShortCode'. The parent
  of the ShortCode is whatever has been defined in the environment variable
  'ELIZIUM_PATH'. If not defined, the operant script will be written to:
  $HOME/.elizium/ShortCode so in this case would be "~/.elizium/remy". If
  'ELIZIUM_PATH' has been defined, the path defined will be "'ELIZIUM_PATH'/remy".
 
  .EXAMPLE 2
  Operant options for Rename-Many(remy) command with SubRoot
 
  [PSCustomObject]$operantOptions = [PSCustomObject]@{
    SubRoot = 'foo-bar';
    ShortCode = 'remy';
    OperantName = 'UndoRename';
    Shell = 'PoShShell';
    BaseFilename = 'undo-rename';
    DisabledEnVar = 'REXFS_REMY_UNDO_DISABLED';
  }
 
  The undo script is written to a directory denoted by the 'ShortCode' and 'SubRoot'
  If 'ELIZIUM_PATH' has not been defined as an environment variable, the operant script
  will be written to: "~/.elizium/foo-bar/remy". If 'ELIZIUM_PATH' has been defined,
  the path defined will be "'ELIZIUM_PATH'/foo-bar/remy".
 
  #>

  [OutputType([Operant])]
  param(
    [Parameter()]
    [PSCustomObject]$Options
  )
  [string]$eliziumPath = Use-EliziumPath;

  [string]$envUndoRenameDisabled = $(Get-EnvironmentVariable -Variable $Options.DisabledEnVar);

  try {
    [boolean]$isDisabled = if (-not([string]::IsNullOrEmpty($envUndoRenameDisabled))) {
      [System.Convert]::ToBoolean($envUndoRenameDisabled);
    }
    else {
      $false;
    }
  }
  catch {
    [boolean]$isDisabled = $false;
  }

  [object]$operant = if (-not($isDisabled)) {
    [string]$subRoot = [string]::IsNullOrEmpty(${Options}?.SubRoot) ? [string]::Empty : $Options.SubRoot;

    [string]$operantPath = $([string]::IsNullOrEmpty($subRoot)) ? $eliziumPath `
      : $(Join-Path -Path $eliziumPath -ChildPath $subRoot);

    [string]$shortCode = [string]::IsNullOrEmpty(${Options}?.ShortCode) ? [string]::Empty : $Options.ShortCode;
    if (-not([string]::IsNullOrEmpty($shortCode))) {
      $operantPath = $(Join-Path -Path $operantPath -ChildPath $shortCode);
    }

    if (-not(Test-Path -Path $operantPath -PathType Container)) {
      $null = New-Item -Type Directory -Path $operantPath;
    }

    New-ShellOperant -BaseFilename $Options.BaseFilename `
      -Directory $operantPath -Operant $($Options.OperantName) -Shell $Options.Shell;
  }
  else {
    $null;
  }

  return $operant;
}

function Invoke-EmojiApiRequest {
  [CmdletBinding()]
  [OutputType([PSCustomObject])]
  param(
    [Parameter()]
    [string]$Uri,

    [Parameter()]
    [hashtable]$Headers
  )
  [Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject]$response = $(
    Invoke-WebRequest -Uri $Uri -Headers $Headers
  );

  [PSCustomObject]$result = [PSCustomObject]@{
    StatusCode        = $response.StatusCode;
    StatusDescription = $response.StatusDescription;
    Headers           = $response.Headers;
    Content           = $response.Content;
  }

  return $result;
}

function New-BootStrap {
  <#
  .NAME
    New-BootStrap
 
  .SYNOPSIS
    Bootstrap factory function
 
  .DESCRIPTION
  
  Creates a bootstrap instance for the client command. When a command designed to show a
  lot of output and indication signals, the bootstrap class can be used to help manage this
  complexity in a common way.
   
  A command may want to show the presence of user
  defined parameters with Signals. By using the Boot-strapper the client can be designed
  without having to implement the logic of showing indicators. All the client needs
  to do is to define a 'spec' object which describes a parameter or other indicator
  and then register this spec with the Boot-strapper. The Boot-strapper then creates an
  'Entity' that relates to the spec.
 
  There are 2 types of entity, primary and related. Primary entities should have a
  boolean Activate property. This denotes whether the entity is created, actioned
  and stored in the bootstrap. Relation entities are dependent on either other
  primary or related entities. Instead of a boolean Activate property, they should
  have an Activator predicate property which is a script block that returns a boolean.
  Typically, the Activator determines it's activated state by consulting other
  entities, returning true if it is active, false otherwise.
 
    Entities are used to tie together various pieces of information into a single bundle.
  This ensures that for a particular item the logic and info is centralised and handled
  in a consistent manner. The various concepts that are handled by an entity are:
 
  * handle items that needs some kind of transformation (eg, regex entities need to be
  constructed via New-RegularExpression)
  * populating exchange
  * creation of signal
  * formulation and validation of formatters
  * container selection
 
  There are currently four entity types:
 
  + **SimpleEntity**: Simple item that does not need any transformation of the value and is not
  represented by a signal. A simple entity can be used if all that is required
  is to populate an exchange entry (via Keys); this is why the Value member is
  optional.
 
  Spec properties:
  * Activate (primary: mandatory) -> flag to indicate if the entity is to be created.
  * Activator (relation: mandatory) -> predicate to indicate if the entity is to be created.
  * Name (mandatory) -> identifies the entity
  * SpecType (mandatory) -> 'simple'
  * Value (optional) -> typically the value of a parameter, but can be anything.
  * Keys (optional) -> Collection of key/value pairs to be inserted into exchange.
 
  + **SignalEntity**: For signalled entities. (eg a parameter that is associated with a signal)
 
    Spec properties:
  * Activate (primary: mandatory) -> flag to indicate if the entity is to be created.
  * Activator (relation: mandatory) -> predicate to indicate if the entity is to be created.
  * Name (mandatory) -> identifies the entity
  * SpecType (mandatory) -> 'signal'
  * Value (optional) -> the primary value for this entity (not necessarily the display value)
  * Signal (mandatory) -> name of the signal
  * SignalValue (optional) -> the display value of the signal
  * Force (optional) -> container selector.
  * Keys (optional) -> Collection of key/value pairs to be inserted into exchange.
 
  + **RegexEntity**: For regular expressions. Used to create a regex entity. The entity can
  represent either a parameter or an independent regex.
 
    A derived regex entity can be created which references another regex. The derived
  value must reference the dependency by including the static place holder string
  '*{_dependency}'.
 
  Spec properties:
  * Activate (primary: mandatory) -> flag to indicate if the entity is to be created.
  * Activator (relation: mandatory) -> predicate to indicate if the entity is to be created.
  * Name (mandatory) -> identifies the entity
  * Value (optional) -> the value of the user supplied expression (including occurrence)
  * Signal (optional) -> should be provided for parameters, optional for non parameters
  * WholeSpecifier (optional) -> single letter code identifying this regex parameter.
  * Force (optional) -> container selector.
  * RegExKey (optional) -> Key identifying where the internally created [regex] object
    is stored in exchange.
  * OccurrenceKey (optional) -> Key identifying where the occurrence value for this regex
    is stored in exchange.
  * Keys (optional) -> Collection of key/value pairs to be inserted into exchange.
 
  For derived:
  * Activate (primary: mandatory) -> flag to indicate if the entity is to be created.
  * Activator (relation: mandatory) -> predicate to indicate if the entity is to be created.
  * Dependency (mandatory) -> Name of required regex entity
  * Name (mandatory)
  * SpecType (mandatory) -> 'regex'
  * Value -> The pattern which should include placeholder '*{_dependency}'
  * RegExKey (optional)
  * OccurrenceKey (optional)
   
  + **FormatterEntity**: For formatter parameters, which formats a file or directory name.
    This is a signal entity with the addition of a validator which checks that the
  value represented does not contain file system unsafe characters. Uses function
  Test-IsFileSystemSafe to perform this check.
 
  Spec properties:
  * Activate (primary: mandatory) -> flag to indicate if the entity is to be created.
  * Activator (relation: mandatory) -> predicate to indicate if the entity is to be created.
  * Name (mandatory) -> identifies the entity
  * SpecType (mandatory) -> 'formatter'
  * Value (optional) -> the value of the user supplied expression (including occurrence)
  * Signal (optional) -> should be provided for parameters, optional for non parameters
  * WholeSpecifier (optional) -> single letter code identifying this regex parameter.
  * Force (optional) -> container selector.
  * Keys (optional) -> Collection of key/value pairs to be inserted into exchange.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Containers
    A PSCustomObject that must contain a 'Wide' property and a 'Props' property. Both of
  these must be of type Krayola.Line. 'Prop's are designed to show a small item of information,
  typically 5/6 characters long; multiple props would typically easily fit on a single line
  in the console. Wide items, are those which when show take up a lot of screen space, eg
  showing a file's full path is often a 'wide' item, so it would be best to present it on
  its own line.
 
  .PARAMETER Exchange
    The exchange instance to populate.
 
  .PARAMETER Options
    Not mandatory. Currently, only specifies a 'Whole' property. The 'Whole' property is a
  string containing multiple individual characters each one maps to a regex parameter and
  indicates if that regex pattern should be applied as a whole; ie it is wrapped up in
  the word boundary token '\b' to indicate that it should match on whole word basis only.
 
  #>

  [OutputType([BootStrap])]
  param(
    [Parameter()]
    [hashtable]$Exchange,

    [Parameter()]
    [PSCustomObject]$Containers,

    [Parameter()]
    [PSCustomObject]$Options = $([PSCustomObject]@{})
  )

  return [BootStrap]::new($Exchange, $Containers, $Options);
}

function New-ShellOperant {
  [OutputType([Operant])]
  param(
    [Parameter()]
    [string]$BaseFilename,

    [Parameter()]
    [string]$Directory,

    [Parameter()]
    [string]$DateTimeFormat = 'yyyy-MM-dd_HH-mm-ss',

    [Parameter()]
    [ValidateSet('UndoRename')]
    [string]$Operant = 'UndoRename',

    [Parameter()]
    [ValidateSet('PoShShell')]
    [string]$Shell = 'PoShShell'
  )
  [string]$filename = "{0}_{1}.ps1" -f $BaseFilename, $(get-CurrentTime -Format $DateTimeFormat);
  [string]$fullPath = Join-Path -Path $Directory -ChildPath $filename;

  [Shell]$shell = if ($Shell -eq 'PoShShell') {
    [PoShShell]::new($fullPath);
  }
  else {
    $null;
  }

  [Operant]$operant = if ($shell) {
    if ($Operant -eq 'UndoRename') {
      [UndoRename]::new($shell);
    }
    else {
      $null;
    }
  }
  else {
    $null;
  }

  return $operant;
}

function Resolve-PatternOccurrence {
  <#
  .NAME
    Resolve-PatternOccurrence
 
  .SYNOPSIS
    Helper function to assist in processing regular expression parameters that can
  be adorned with an occurrence value.
 
  .DESCRIPTION
    Since the occurrence part is optional and defaults to mean first occurrence only,
  this function will fill in the default 'f' when occurrence is not specified.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Value
    The value of a regex parameter, which is an array whose first element is the
  pattern and the second if present is the match occurrence.
 
  #>

  param (
    [Parameter(Position = 0)]
    [array]$Value
  )

  $Value[0], $(($Value.Length -eq 1) ? 'f' : $Value[1]);
} # resolve-PatternOccurrence

function Select-FsItem {
  <#
  .NAME
    Select-FsItem
 
  .SYNOPSIS
    A predicate function that indicates whether an item identified by the Name matches
  the include/exclude filters specified.
 
  .DESCRIPTION
    Use this utility function to help specify a Condition for Invoke-TraverseDirectory.
  This function is partly required because the Include/Exclude parameters on functions
  such as Get-ChildItems/Copy-Item/Get-Item etc only work on files not directories.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Case
    Switch parameter which controls case sensitivity of inclusion/exclusion. By default
  filtering is case insensitive. When The Case switch is specified, filtering is case
  sensitive.
 
  .PARAMETER Excludes
    An array containing a list of filters, each must contain a wild-card ('*'). If a
  particular filter does not contain a wild-card, then it will be ignored. If the Name
  matches any of the filters in the list, will cause the end result to be false.
  Any match in the Excludes overrides a match in Includes, so an item
  that is matched in Include, can be excluded by the Exclude.
 
  .PARAMETER Includes
      An array containing a list of filters, each must contain a wild-card ('*'). If a
  particular filter does not contain a wild-card, then it will be ignored. If Name matches
  any of the filters in Includes, and are not Excluded, the result will be true.
 
  .PARAMETER Name
    A string to be matched against the filters.
 
  .EXAMPLE 1
    Define a Condition that allows only directories beginning with A, but also excludes
    any directory containing '_' or '-'.
 
    [scriptblock]$filterDirectories = {
      [OutputType([boolean])]
      param(
        [System.IO.DirectoryInfo]$directoryInfo
      )
      [string[]]$directoryIncludes = @('A*');
      [string[]]$directoryExcludes = @('*_*', '*-*');
 
      $filterDirectories = Select-FsItem -Name $directoryInfo.Name `
        -Includes $directoryIncludes -Excludes $directoryExcludes;
 
      Invoke-TraverseDirectory -Path <path> -Block <block> -Condition $filterDirectories;
    }
  #>


  [OutputType([boolean])]
  param(
    [Parameter(Mandatory)]
    [string]$Name,

    [Parameter()]
    [string[]]$Includes = @(),

    [Parameter()]
    [string[]]$Excludes = @(),

    [Parameter()]
    [switch]$Case
  )

  # Note we wrap the result inside @() array designator just in-case the where-object
  # returns just a single item in which case the array would be flattened out into
  # an individual scalar value which is what we don't want, damn you powershell for
  # doing this and making life just so much more difficult. Actually, on further
  # investigation, we don't need to wrap inside @(), because we've explicitly defined
  # the type of the includes variables to be arrays, which would preserve the type
  # even in the face of powershell annoyingly flattening the single item array. @()
  # being left in for clarity and show of intent.
  #
  [string[]]$validIncludes = @($Includes | Where-Object { $_.Contains('*') })
  [string[]]$validExcludes = @($Excludes | Where-Object { $_.Contains('*') })

  [boolean]$resolvedInclude = $validIncludes `
    ? (select-ResolvedFsItem -FsItem $Name -Filter $Includes -Case:$Case) `
    : $false;

  [boolean]$resolvedExclude = $validExcludes `
    ? (select-ResolvedFsItem -FsItem $Name -Filter $Excludes -Case:$Case) `
    : $false;

  ($resolvedInclude) -and -not($resolvedExclude)
} # Select-FsItem

function Select-SignalContainer {
  <#
  .NAME
    Select-SignalContainer
 
  .SYNOPSIS
    Selects a signal into the container specified (either 'Wide' or 'Props').
  Wide items will appear on their own line, Props are for items which are
  short in length and can be combined into the same line.
 
  .DESCRIPTION
    This is a wrapper around Get-FormattedSignal in addition to selecting the
  signal into a container.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Containers
    PSCustomObject that contains Wide and Props properties which must be of Krayola's
  type [line].
 
  .PARAMETER CustomLabel
    A custom label applied to the formatted signal.
 
  .PARAMETER Force
    An override (bypassing $Threshold) to push a signal into a specific collection.
 
  .PARAMETER Format
    The format applied to the formatted signal.
 
  .PARAMETER Name
    The signal name.
 
  .PARAMETER Signals
    The signal hashtable collection from which to select the required signal denoted by
  $Name.
 
  .PARAMETER Threshold
    A threshold that defines whether the signal is added to Wide or Props.
 
  .PARAMETER Value
    The value associated wih the signal.
 
  #>

  param(
    [Parameter(Mandatory)]
    [PSCustomObject]$Containers,

    [Parameter(Mandatory)]
    [string]$Name,

    [Parameter(Mandatory)]
    [string]$Value,

    [Parameter()]
    [hashtable]$Signals = $(Get-Signals),

    [Parameter()]
    [string]$Format = '[{1}] {0}', # 0=Label, 1=Emoji,

    [Parameter()]
    [int]$Threshold = 6,

    [Parameter()]
    [string]$CustomLabel,

    [Parameter()]
    [ValidateSet('Wide', 'Props')]
    [string]$Force
  )

  [couplet]$formattedSignal = Get-FormattedSignal -Name $Name -Format $Format -Value $Value `
    -Signals $Signals -CustomLabel $CustomLabel;

  if ($PSBoundParameters.ContainsKey('Force')) {
    if ($Force -eq 'Wide') {
      $null = $Containers.Wide.append($formattedSignal);
    }
    else {
      $null = $Containers.Props.append($formattedSignal);
    }
  }
  else {
    if ($Value.Length -gt $Threshold) {
      $null = $Containers.Wide.append($formattedSignal);
    }
    else {
      $null = $Containers.Props.append($formattedSignal);
    }
  }
}

function Use-EliziumPath {
  <#
  .NAME
    Use-EliziumPath
 
  .SYNOPSIS
    Ensures that the directory referred to by the environment variable 'ELIZIUM_PATH'
  actually exists.
 
  .DESCRIPTION
    If the directory does not exist, the directory will be created, even if any
  intermediate sub-paths do not exist.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
  #>

  [OutputType([string])]
  param()

  [string]$homePath = Get-EnvironmentVariable 'HOME' -Default $HOME;
  [string]$eliziumPath = (Get-EnvironmentVariable 'ELIZIUM_PATH') ?? $(
    Join-Path -Path $homePath -ChildPath '.elizium'
  );

  if (-not(Test-Path -Path $eliziumPath -PathType Container)) {
    $null = New-Item -Path $eliziumPath -ItemType Directory -WhatIf:$false;
  }

  return $eliziumPath;
}

function Invoke-ForeachFsItem {
  <#
  .NAME
    Invoke-ForeachFsItem
 
  .SYNOPSIS
    Allows a custom defined script-block or function to be invoked for all file system
  objects delivered through the pipeline.
 
  .DESCRIPTION
    2 parameters sets are defined, one for invoking a named function (InvokeFunction) and
  the other (InvokeScriptBlock, the default) for invoking a script-block. An optional
  Summary script block can be specified which will be invoked at the end of the pipeline
  batch. The user should assemble the candidate items from the file system, be they files or
  directories typically using Get-ChildItem, or can be any other function that delivers
  file systems items via the PowerShell pipeline. For each item in the pipeline,
  Invoke-ForeachFsItem will invoke the script-block/function specified. Invoke-ForeachFsItem
  will deliver what ever is returned from the script-block/function, so the result of
  Invoke-ForeachFsItem can be piped to another command.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Block
    The script block to be invoked. The script block is invoked for each item in the
  pipeline that satisfy the Condition with the following positional parameters:
    * pipelineItem: the item from the pipeline
    * index: the 0 based index representing current pipeline item
    * Exchange: a hash table containing miscellaneous information gathered internally
  throughout the pipeline batch. This can be of use to the user, because it is the way
  the user can perform bi-directional communication between the invoked custom script block
  and client side logic.
    * trigger: a boolean value, useful for state changing idempotent operations. At the end
  of the batch, the state of the trigger indicates whether any of the items were actioned.
  When the script block is invoked, the trigger should indicate if the trigger was pulled for
  any of the items so far processed in the pipeline. This is the responsibility of the
  client's block implementation. The trigger is only of use for state changing operations
  and can be ignored otherwise.
 
  In addition to these fixed positional parameters, if the invoked script-block is defined
  with additional parameters, then these will also be passed in. In order to achieve this,
  the client has to provide excess parameters in BlockParam and these parameters must be
  defined as the same type and in the same order as the additional parameters in the
  script-block.
 
  .PARAMETER BlockParams
    Optional array containing the excess parameters to pass into the script block.
 
  .PARAMETER Condition
    This is a predicate script-block, which is invoked with either a DirectoryInfo or
  FileInfo object presented as a result of invoking Get-ChildItem. It provides a filtering
  mechanism that is defined by the user to define which file system objects are selected
  for function/script-block invocation.
 
  .PARAMETER Directory
    Switch to indicate that the invoked function/script-block (invokee) is to handle Directory
  objects.
 
  .PARAMETER File
    Switch to indicate that the invoked function/script-block (invokee) is to handle FileInfo
  objects. Is mutually exclusive with the Directory switch. If neither switch is specified, then
  the invokee must be able to handle both therefore the Underscore parameter it defines must
  be declared as FileSystemInfo.
 
  .PARAMETER Functee
    String defining the function to be invoked. Works in a similar way to the Block parameter
  for script-blocks. The Function's base signature is as follows:
    * Underscore: (See pipelineItem described above)
    * Index: (See index described above)
    * Exchange: (See PathThru described above)
    * Trigger: (See trigger described above)
 
  .PARAMETER FuncteeParams
    Optional hash-table containing the named parameters which are splatted into the Functee
  function invoke. As it's a hash table, order is not significant.
 
  .PARAMETER Exchange
    A hash table containing miscellaneous information gathered internally throughout the
  pipeline batch. This can be of use to the user, because it is the way the user can perform
  bi-directional communication between the invoked custom script block and client side logic.
 
  .PARAMETER Header
    A script-block that is invoked at the start of the pipeline batch. The script-block is
  invoked with the following positional parameters:
    * Exchange: (see Exchange previously described)
 
    The Header can be customised with the following Exchange entries:
    * 'LOOPZ.KRAYOLA-THEME': Krayola Theme generally in use
    * 'LOOPZ.HEADER-BLOCK.MESSAGE': message displayed as part of the header
    * 'LOOPZ.HEADER-BLOCK.CRUMB-SIGNAL': Lead text displayed in header, default: '[+] '
    * 'LOOPZ.HEADER.PROPERTIES': An array of Key/Value pairs of items to be displayed
    * 'LOOPZ.HEADER-BLOCK.LINE': A string denoting the line to be displayed. (There are
    predefined lines available to use in $LoopzUI, or a custom one can be used instead)
 
  .PARAMETER Summary
    A script-block that is invoked at the end of the pipeline batch. The script-block is
  invoked with the following positional parameters:
    * count: the number of items processed in the pipeline batch.
    * skipped: the number of items skipped in the pipeline batch. An item is skipped if
    it fails the defined condition or is not of the correct type (eg if its a directory
    but we have specified the -File flag). Also note that, if the script-block/function
    sets the Break flag causing further iteration to stop, then those subsequent items
    in the pipeline which have not been processed are not reflected in the skip count.
    * trigger: Flag set by the script-block/function, but should typically be used to
    indicate whether any of the items processed were actively updated/written in this batch.
    This helps in written idempotent operations that can be re-run without adverse
    consequences.
    * Exchange: (see Exchange previously described)
 
  .PARAMETER Top
    Restricts the number of items processed in the rename batch, the remaining items
  are skipped. User can set this for experimental purposes.
 
  .PARAMETER pipelineItem
    This is the pipeline object, so should not be specified explicitly and can represent
  a file object (System.IO.FileInfo) or a directory object (System.IO.DirectoryInfo).
 
  .EXAMPLE 1
  Invoke a script-block to handle .txt file objects from the same directory (without -Recurse):
  (NB: first parameter is of type FileInfo, -File specified on Get-ChildItem and
  Invoke-ForeachFsItem. If Get-ChildItem is missing -File, then any Directory objects passed in
  are filtered out by Invoke-ForeachFsItem. If -File is missing from Invoke-ForeachFsItem, then
  the script-block's first parameter, must be a FileSystemInfo to handle both types)
 
    [scriptblock]$block = {
      param(
        [System.IO.FileInfo]$FileInfo,
        [int]$Index,
        [hashtable]$Exchange,
        [boolean]$Trigger
      )
      ...
    }
 
    Get-ChildItem './Tests/Data/fefsi' -Recurse -Filter '*.txt' -File | `
      Invoke-ForeachFsItem -File -Block $block;
 
  .EXAMPLE 2
  Invoke a function with additional parameters to handle directory objects from multiple directories
  (with -Recurse):
 
  function invoke-Target {
    param(
      [System.IO.DirectoryInfo]$Underscore,
      [int]$Index,
      [hashtable]$Exchange,
      [boolean]$Trigger,
      [string]$Format
    )
    ...
  }
 
  [hashtable]$parameters = @{
    'Format'
  }
  Get-ChildItem './Tests/Data/fefsi' -Recurse -Directory | `
    Invoke-ForeachFsItem -Directory -Functee 'invoke-Target' -FuncteeParams $parameters
 
  .EXAMPLE 3
  Invoke a script-block to handle empty .txt file objects from the same directory (without -Recurse):
    [scriptblock]$block = {
      param(
        [System.IO.FileInfo]$FileInfo,
        [int]$Index,
        [hashtable]$Exchange,
        [boolean]$Trigger
      )
      ...
    }
 
    [scriptblock]$fileIsEmpty = {
      param(
        [System.IO.FileInfo]$FileInfo
      )
      return (0 -eq $FileInfo.Length)
    }
 
    Get-ChildItem './Tests/Data/fefsi' -Recurse -Filter '*.txt' -File | Invoke-ForeachFsItem `
      -Block $block -File -condition $fileIsEmpty;
 
  .EXAMPLE 4
  Invoke a script-block only for directories whose name starts with "A" from the same
  directory (without -Recurse); Note the use of the LOOPZ function "Select-FsItem" in the
  directory include filter:
 
    [scriptblock]$block = {
      param(
        [System.IO.FileInfo]$FileInfo,
        [int]$Index,
        [hashtable]$Exchange,
        [boolean]$Trigger
      )
      ...
    }
 
  [scriptblock]$filterDirectories = {
    [OutputType([boolean])]
    param(
      [System.IO.DirectoryInfo]$directoryInfo
    )
    Select-FsItem -Name $directoryInfo.Name -Includes 'A*';
  }
 
    Get-ChildItem './Tests/Data/fefsi' -Directory | Invoke-ForeachFsItem `
      -Block $block -Directory -DirectoryIncludes $filterDirectories;
 
  .EXAMPLE 5
  Invoke a script-block to handle .txt file objects from the same directory. This
  example illustrates the use of the Header and Summary blocks. Blocks predefined
  in LoopzHelpers are illustrated but the user can defined their own.
 
    [scriptblock]$block = {
      param(
        [System.IO.FileInfo]$FileInfo,
        [int]$Index,
        [hashtable]$Exchange,
        [boolean]$Trigger
      )
      ...
    }
 
    $exchange = @{
      'LOOPZ.KRAYOLA-THEME' = $(Get-KrayolaTheme);
      'LOOPZ.HEADER-BLOCK.MESSAGE' = 'The owls are not what they seem';
      'LOOPZ.HEADER-BLOCK.PROPERTIES' = @(@('A', 'One'), @('B', 'Two'), @('C', 'Three'));
      'LOOPZ.HEADER-BLOCK.LINE' = $LoopzUI.TildeLine;
      'LOOPZ.SUMMARY-BLOCK.LINE' = $LoopzUI.DashLine;
    }
 
    Get-ChildItem './Tests/Data/fefsi' -Recurse -Filter '*.txt' -File | `
      Invoke-ForeachFsItem -File -Block $block -Exchange $exchange `
        -Header $LoopzHelpers.DefaultHeaderBlock -Summary $LoopzHelpers.SimpleSummaryBlock;
  #>

  [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')]
  [CmdletBinding(DefaultParameterSetName = 'InvokeScriptBlock')]
  [Alias('ife', 'Foreach-FsItem')]
  param(
    [Parameter(ParameterSetName = 'InvokeScriptBlock', Mandatory, ValueFromPipeline = $true)]
    [Parameter(ParameterSetName = 'InvokeFunction', Mandatory, ValueFromPipeline = $true)]
    [System.IO.FileSystemInfo]$pipelineItem,

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [scriptblock]$Condition = ( { return $true; }),

    [Parameter(ParameterSetName = 'InvokeScriptBlock', Mandatory)]
    [scriptblock]$Block,

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [ValidateScript( { $_ -is [Array] })]
    $BlockParams = @(),

    [Parameter(ParameterSetName = 'InvokeFunction', Mandatory)]
    [ValidateScript( { -not([string]::IsNullOrEmpty($_)); })]
    [string]$Functee,

    [Parameter(ParameterSetName = 'InvokeFunction')]
    [hashtable]$FuncteeParams = @{},

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [hashtable]$Exchange = @{},

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [scriptblock]$Header = ( {
        param(
          [hashtable]$_exchange
        )
      }),

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [scriptblock]$Summary = ( {
        param(
          [int]$_count,
          [int]$_skipped,
          [int]$_errors,
          [boolean]$_trigger,
          [hashtable]$_exchange
        )
      }),

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [ValidateScript( { -not($PSBoundParameters.ContainsKey('Directory')) })]
    [switch]$File,

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [ValidateScript( { -not($PSBoundParameters.ContainsKey('File')) })]
    [switch]$Directory,

    [Parameter()]
    [ValidateScript( { $_ -gt 0 } )]
    [int]$Top
  ) # param

  begin {
    if (-not($Exchange.ContainsKey('LOOPZ.CONTROLLER'))) {
      $Exchange['LOOPZ.CONTROLLER'] = New-Controller -Type ForeachCtrl -Exchange $Exchange `
        -Header $Header -Summary $Summary;
    }
    $controller = $Exchange['LOOPZ.CONTROLLER'];
    $controller.ForeachBegin();

    [boolean]$topBreached = $false;
  }

  process {
    [boolean]$itemIsDirectory = ($pipelineItem.Attributes -band
      [System.IO.FileAttributes]::Directory) -eq [System.IO.FileAttributes]::Directory;

    [boolean]$acceptAll = -not($File.ToBool()) -and -not($Directory.ToBool());

    if (-not($controller.IsBroken())) {
      if ( $acceptAll -or ($Directory.ToBool() -and $itemIsDirectory) -or
        ($File.ToBool() -and -not($itemIsDirectory)) ) {
        if ($Condition.InvokeReturnAsIs($pipelineItem) -and -not($topBreached)) {
          [PSCustomObject]$result = $null;
          [int]$index = $controller.RequestIndex();
          [boolean]$trigger = $controller.GetTrigger();

          if ('InvokeScriptBlock' -eq $PSCmdlet.ParameterSetName) {
            $positional = @($pipelineItem, $index, $Exchange, $trigger);

            if ($BlockParams.Length -gt 0) {
              $BlockParams | ForEach-Object {
                $positional += $_;
              }
            }

            $result = Invoke-Command -ScriptBlock $Block -ArgumentList $positional;
          }
          elseif ('InvokeFunction' -eq $PSCmdlet.ParameterSetName) {
            [hashtable]$parameters = $FuncteeParams.Clone();

            $parameters['Underscore'] = $pipelineItem;
            $parameters['Index'] = $index;
            $parameters['Exchange'] = $Exchange;
            $parameters['Trigger'] = $trigger;

            $result = & $Functee @parameters;
          }

          $controller.HandleResult($result);
          if ($result -and $result.psobject.properties.match('Product') -and $result.Product) {
            $result.Product;
          }

          if ($PSBoundParameters.ContainsKey('Top') -and ($index -eq ($Top - 1))) {
            $topBreached = $true;
          }
        }
        else {
          # IDEA! We could allow the user to provide an extra script block which we
          # invoke for skipped items and set a string containing the reason why it was
          # skipped.
          $controller.SkipItem();
        }
      }
      else {
        $controller.SkipItem();
      }
    }
    else {
      $controller.SkipItem();
    }
  }

  end {
    $controller.ForeachEnd();
  }
} # Invoke-ForeachFsItem
function Invoke-MirrorDirectoryTree {
  <#
  .NAME
    Invoke-MirrorDirectoryTree
 
  .SYNOPSIS
    Mirrors a directory tree to a new location, invoking a custom defined scriptblock
  or function as it goes.
 
  .DESCRIPTION
    Copies a source directory tree to a new location applying custom functionality for each
  directory. 2 parameters set are defined, one for invoking a named function (InvokeFunction) and
  the other (InvokeScriptBlock, the default) for invoking a scriptblock. An optional
  Summary script block can be specified which will be invoked at the end of the mirroring
  batch.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Block
    The script block to be invoked. The script block is invoked for each directory in the
  source directory tree that satisfy the specified Directory Include/Exclude filters with
  the following positional parameters:
    * underscore: the DirectoryInfo object representing the directory in the source tree
    * index: the 0 based index representing current directory in the source tree
    * Exchange object: a hash table containing miscellaneous information gathered internally
    throughout the mirroring batch. This can be of use to the user, because it is the way
    the user can perform bi-directional communication between the invoked custom script block
    and client side logic.
    * trigger: a boolean value, useful for state changing idempotent operations. At the end
    of the batch, the state of the trigger indicates whether any of the items were actioned.
    When the script block is invoked, the trigger should indicate if the trigger was pulled for
    any of the items so far processed in the batch. This is the responsibility of the
    client's script-block/function implementation.
 
  In addition to these fixed positional parameters, if the invoked scriptblock is defined
  with additional parameters, then these will also be passed in. In order to achieve this,
  the client has to provide excess parameters in BlockParams and these parameters must be
  defined as the same type and in the same order as the additional parameters in the
  script-block.
 
  The destination DirectoryInfo object can be accessed via the Exchange denoted by
  the 'LOOPZ.MIRROR.DESTINATION' entry.
 
  .PARAMETER BlockParams
    Optional array containing the excess parameters to pass into the script-block/function.
 
  .PARAMETER CopyFiles
    Switch parameter that indicates that files matching the specified filters should be copied
 
  .PARAMETER CreateDirs
    switch parameter indicates that directories should be created in the destination tree. If
  not set, then Invoke-MirrorDirectoryTree turns into a function that traverses the source
  directory invoking the function/script-block for matching directories.
 
  .PARAMETER DestinationPath
    The destination Path denoting the root of the directory tree where the source tree
  will be mirrored to.
 
  .PARAMETER DirectoryIncludes
    An array containing a list of filters, each must contain a wild-card ('*'). If a
  particular filter does not contain a wild-card, then it will be ignored. If the directory
  matches any of the filters in the list, it will be mirrored in the destination tree.
  If DirectoryIncludes contains just a single element which is the empty string, this means
  that nothing is included (rather than everything being included).
 
  .PARAMETER DirectoryExcludes
    An array containing a list of filters, each must contain a wild-card ('*'). If a
  particular filter does not contain a wild-card, then it will be ignored. If the directory
  matches any of the filters in the list, it will NOT be mirrored in the destination tree.
  Any match in the DirectoryExcludes overrides a match in DirectoryIncludes, so a directory
  that is matched in Include, can be excluded by the Exclude.
 
  .PARAMETER Exchange
    A hash table containing miscellaneous information gathered internally
  throughout the pipeline batch. This can be of use to the user, because it is the way
  the user can perform bi-directional communication between the invoked custom script block
  and client side logic.
 
  .PARAMETER FileExcludes
    An array containing a list of filters, each may contain a wild-card ('*'). If a
  particular filter does not contain a wild-card, then it will be treated as a file suffix.
  If the file in the source tree matches any of the filters in the list, it will NOT be
  mirrored in the destination tree. Any match in the FileExcludes overrides a match in
  FileIncludes, so a file that is matched in Include, can be excluded by the Exclude.
 
  .PARAMETER FileIncludes
    An array containing a list of filters, each may contain a wild-card ('*'). If a
  particular filter does not contain a wild-card, then it will be treated as a file suffix.
  If the file in the source tree matches any of the filters in the list, it will be mirrored
  in the destination tree. If FileIncludes contains just a single element which is the empty
  string, this means that nothing is included (rather than everything being included).
 
 
  .PARAMETER Functee
    String defining the function to be invoked. Works in a similar way to the Block parameter
  for script-blocks. The Function's base signature is as follows:
  * "Underscore": (See underscore described above)
  * "Index": (See index described above)
  * "Exchange": (See PathThru described above)
  * "Trigger": (See trigger described above)
 
  The destination DirectoryInfo object can be accessed via the Exchange denoted by
  the 'LOOPZ.MIRROR.DESTINATION' entry.
 
  .PARAMETER FuncteeParams
    Optional hash-table containing the named parameters which are splatted into the Functee
  function invoke. As it's a hash table, order is not significant.
 
  .PARAMETER Header
    A script-block that is invoked for each directory that also contains child directories.
  The script-block is invoked with the following positional parameters:
    * Exchange: (see Exchange previously described)
 
    The Header can be customised with the following Exchange entries:
    * 'LOOPZ.KRAYOLA-THEME': Krayola Theme generally in use
    * 'LOOPZ.HEADER-BLOCK.MESSAGE': message displayed as part of the header
    * 'LOOPZ.HEADER-BLOCK.CRUMB-SIGNAL': Lead text displayed in header, default: '[+] '
    * 'LOOPZ.HEADER.PROPERTIES': An array of Key/Value pairs of items to be displayed
    * 'LOOPZ.HEADER-BLOCK.LINE': A string denoting the line to be displayed. (There are
    predefined lines available to use in $LoopzUI, or a custom one can be used instead)
 
  .PARAMETER Hoist
    switch parameter. Without Hoist being specified, the filters can prove to be too restrictive
  on matching against directories. If a directory does not match the filters then none of its
  descendants will be considered to be mirrored in the destination tree. When Hoist is specified
  then a descendant directory that does match the filters will be mirrored even though any of
  its ancestors may not match the filters.
 
  .PARAMETER Path
    The source Path denoting the root of the directory tree to be mirrored.
 
  .PARAMETER SessionHeader
    A script-block that is invoked at the start of the mirroring batch. The script-block has
  the same signature as the Header script block.
 
  .PARAMETER SessionSummary
    A script-block that is invoked at the end of the mirroring batch. The script-block has
  the same signature as the Summary script block.
 
  .PARAMETER Summary
    A script-block that is invoked foreach directory that also contains child directories,
  after all its descendants have been processed and serves as a sub-total for the current
  directory. The script-block is invoked with the following positional parameters:
    * count: the number of items processed in the mirroring batch.
    * skipped: the number of items skipped in the mirroring batch. An item is skipped if
    it fails the defined condition or is not of the correct type (eg if its a directory
    but we have specified the -File flag).
    * errors: the number of items which resulted in error. An error occurs when the function
    or the script-block has set the Error property on the invoke result.
    * trigger: Flag set by the script-block/function, but should typically be used to
    indicate whether any of the items processed were actively updated/written in this batch.
    This helps in written idempotent operations that can be re-run without adverse
    consequences.
    * Exchange: (see Exchange previously described)
 
  .EXAMPLE 1
    Invoke a named function for every directory in the source tree and mirror every
  directory in the destination tree. The invoked function has an extra parameter in it's
  signature, so the extra parameters must be passed in via FuncteeParams (the standard
  signature being the first 4 parameters shown.)
 
  function Test-Mirror {
    param(
      [System.IO.DirectoryInfo]$Underscore,
      [int]$Index,
      [hashtable]$Exchange,
      [boolean]$Trigger,
      [string]$Format
    )
    ...
  }
 
  [hashtable]$parameters = @{
    'Format' = '---- {0} ----';
  }
  Invoke-MirrorDirectoryTree -Path './Tests/Data/fefsi' `
    -DestinationPath './Tests/Data/mirror' -CreateDirs `
    -Functee 'Test-Mirror' -FuncteeParams $parameters;
 
  .EXAMPLE 2
  Invoke a script-block for every directory in the source tree and copy all files
 
  Invoke-MirrorDirectoryTree -Path './Tests/Data/fefsi' `
    -DestinationPath './Tests/Data/mirror' -CreateDirs -CopyFiles -block {
      param(
        [System.IO.DirectoryInfo]$Underscore,
        [int]$Index,
        [hashtable]$Exchange,
        [boolean]$Trigger
      )
      ...
    };
 
  .EXAMPLE 3
  Mirror a directory tree, including only directories beginning with A (filter A*)
 
  Invoke-MirrorDirectoryTree -Path './Tests/Data/fefsi' -DestinationPath './Tests/Data/mirror' `
    -DirectoryIncludes @('A*')
 
  Note the possible issue with this example is that any descendants named A... which are located
  under an ancestor which is not named A..., will not be mirrored;
 
  eg './Tests/Data/fefsi/Audio/mp3/A/Amorphous Androgynous', even though "Audio", "A" and
  "Amorphous Androgynous" clearly match the A* filter, they will not be mirrored because
  the "mp3" directory, would be filtered out.
  See the following example for a resolution.
 
  .EXAMPLE 4
  Mirror a directory tree, including only directories beginning with A (filter A*) regardless of
  the matching of intermediate ancestors (specifying -Hoist flag resolves the possible
  issue in the previous example)
 
  Invoke-MirrorDirectoryTree -Path './Tests/Data/fefsi' -DestinationPath './Tests/Data/mirror' `
    -DirectoryIncludes @('A*') -CreateDirs -CopyFiles -Hoist
 
  Note that the directory filter must include a wild-card, otherwise it will be ignored. So a
  directory include of @('A'), is problematic, because A is not a valid directory filter so its
  ignored and there are no remaining filters that are able to include any directory, so no
  directory passes the filter.
 
  .EXAMPLE 5
  Mirror a directory tree, including files with either .flac or .wav suffix
 
  Invoke-MirrorDirectoryTree -Path './Tests/Data/fefsi' -DestinationPath './Tests/Data/mirror' `
    -FileIncludes @('flac', '*.wav') -CreateDirs -CopyFiles -Hoist
 
  Note that for files, a filter may or may not contain a wild-card. If the wild-card is missing
  then it is automatically treated as a file suffix; so 'flac' means '*.flac'.
 
  .EXAMPLE 6
  Mirror a directory tree copying over just flac files
 
  [scriptblock]$summary = {
    param(
      [int]$_count,
      [int]$_skipped,
      [boolean]$_triggered,
      [hashtable]$_exchange
    )
    ...
  }
 
  Invoke-MirrorDirectoryTree -Path './Tests/Data/fefsi' -DestinationPath './Tests/Data/mirror' `
    -FileIncludes @('flac') -CopyFiles -Hoist -Summary $summary
 
  Note that -CreateDirs is missing which means directories will not be mirrored by default. They
  are only mirrored as part of the process of copying over flac files, so in the end the
  resultant mirror directory tree will contain directories that include flac files.
 
  .EXAMPLE 7
  Same as EXAMPLE 6, but using predefined Header and Summary script-blocks for Session header/summary
  and per directory header/summary.
 
  Invoke-MirrorDirectoryTree -Path './Tests/Data/fefsi' -DestinationPath './Tests/Data/mirror' `
  -FileIncludes @('flac') -CopyFiles -Hoist `
  -Header $LoopzHelpers.DefaultHeaderBlock -Summary $DefaultHeaderBlock.SimpleSummaryBlock `
  -SessionHeader $LoopzHelpers.DefaultHeaderBlock -SessionSummary $DefaultHeaderBlock.SimpleSummaryBlock;
  #>


  [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')]
  [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'InvokeScriptBlock')]
  [Alias('imdt', 'Mirror-Directory')]
  param
  (
    [Parameter(Mandatory, ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(Mandatory, ParameterSetName = 'InvokeFunction')]
    [ValidateScript( { Test-path -Path $_; })]
    [String]$Path,

    [Parameter(Mandatory, ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(Mandatory, ParameterSetName = 'InvokeFunction')]
    [String]$DestinationPath,

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [String[]]$DirectoryIncludes = @('*'),

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [String[]]$DirectoryExcludes = @(),

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [String[]]$FileIncludes = @('*'),

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [String[]]$FileExcludes = @(),

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [hashtable]$Exchange = @{},

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [scriptblock]$Block = ( {
        [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')]
        param(
          [System.IO.DirectoryInfo]$underscore,
          [int]$index,
          [hashtable]$exchange,
          [boolean]$trigger
        )
      } ),

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [ValidateScript( { $_ -is [Array] })]
    $BlockParams = @(),

    [Parameter(ParameterSetName = 'InvokeFunction', Mandatory)]
    [ValidateScript( { -not([string]::IsNullOrEmpty($_)); })]
    [string]$Functee,

    [Parameter(ParameterSetName = 'InvokeFunction')]
    [hashtable]$FuncteeParams = @{},

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [switch]$CreateDirs,

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [switch]$CopyFiles,

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [switch]$Hoist,

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [scriptblock]$Header = ( {
        param(
          [hashtable]$_exchange
        )
      }),

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [scriptblock]$Summary = ( {
        [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')]
        param(
          [int]$_index,
          [int]$_skipped,
          [int]$_errors,
          [boolean]$_trigger,
          [hashtable]$_exchange
        )
      }),

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [scriptblock]$SessionHeader = ( {
        param(
          [hashtable]$_exchange
        )
      }),

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [scriptblock]$SessionSummary = ( {
        param(
          [int]$_count,
          [int]$_skipped,
          [int]$_errors,
          [boolean]$_trigger,
          [hashtable]$_exchange
        )
      })
  ) # param

  # ================================================================== [doMirrorBlock] ===
  #
  [scriptblock]$doMirrorBlock = {
    param(
      [Parameter(Mandatory)]
      [System.IO.DirectoryInfo]$_underscore,

      [Parameter(Mandatory)]
      [int]$_index,

      [Parameter(Mandatory)]
      [hashtable]$_exchange,

      [Parameter(Mandatory)]
      [boolean]$_trigger
    )

    # Write-Host "[+] >>> doMirrorBlock: $($_underscore.Name)";

    [string]$rootSource = $_exchange['LOOPZ.MIRROR.ROOT-SOURCE'];
    [string]$rootDestination = $_exchange['LOOPZ.MIRROR.ROOT-DESTINATION'];

    $sourceDirectoryFullName = $_underscore.FullName;

    # sourceDirectoryFullName must end with directory separator
    #
    if (-not($sourceDirectoryFullName.EndsWith([System.IO.Path]::DirectorySeparatorChar))) {
      $sourceDirectoryFullName += [System.IO.Path]::DirectorySeparatorChar;
    }

    $destinationBranch = edit-RemoveSingleSubString -Target $sourceDirectoryFullName -Subtract $rootSource;

    $destinationDirectory = Join-Path -Path $rootDestination -ChildPath $destinationBranch;
    $_exchange['LOOPZ.MIRROR.BRANCH-DESTINATION'] = $destinationBranch;

    [boolean]$whatIf = $_exchange.ContainsKey('WHAT-IF') -and ($_exchange['WHAT-IF']);
    Write-Debug "[+] >>> doMirrorBlock: destinationDirectory: '$destinationDirectory'";

    if ($whatIf) {
      if (Test-Path -Path $destinationDirectory) {
        Write-Debug " [-] (WhatIf) Get existing destination branch directory: '$destinationBranch'";
        $destinationInfo = (Get-Item -Path $destinationDirectory);
      }
      else {
        Write-Debug " [-] (WhatIf) Creating synthetic destination branch directory: '$destinationBranch'";
        $destinationInfo = ([System.IO.DirectoryInfo]::new($destinationDirectory));
      }
    }
    else {
      if ($CreateDirs.ToBool()) {
        Write-Debug " [-] Creating destination branch directory: '$destinationBranch'";

        $destinationInfo = (Test-Path -Path $destinationDirectory) `
          ? (Get-Item -Path $destinationDirectory) `
          : (New-Item -ItemType 'Directory' -Path $destinationDirectory);
      }
      else {
        Write-Debug " [-] Creating destination branch directory INFO obj: '$destinationBranch'";
        $destinationInfo = New-Object -TypeName System.IO.DirectoryInfo ($destinationDirectory);
      }
    }

    if ($CopyFiles.ToBool()) {
      Write-Debug " [-] Creating files for branch directory: '$destinationBranch'";

      # To use the include/exclude parameters on Copy-Item, the Path specified
      # must end in /*. We only need to add the star though because we added the /
      # previously.
      #
      [string]$sourceDirectoryWithWildCard = $sourceDirectoryFullName + '*';

      [string[]]$adjustedFileIncludes = $FileIncludes | ForEach-Object {
        $_.Contains('*') ? $_ : "*.$_".Replace('..', '.');
      }

      [string[]]$adjustedFileExcludes = $FileExcludes | ForEach-Object {
        $_.Contains('*') ? $_ : "*.$_".Replace('..', '.');
      }

      # Ensure that the destination directory exists, but only if there are
      # files to copy over which pass the include/exclude filters. This is
      # required in the case where CreateDirs has not been specified.
      #
      [array]$filesToCopy = Get-ChildItem $sourceDirectoryWithWildCard `
        -Include $adjustedFileIncludes -Exclude $adjustedFileExcludes -File;

      if ($filesToCopy) {
        if (-not($whatIf)) {
          if (-not(Test-Path -Path $destinationDirectory)) {
            New-Item -ItemType 'Directory' -Path $destinationDirectory;
          }

          Copy-Item -Path $sourceDirectoryWithWildCard `
            -Include $adjustedFileIncludes -Exclude $adjustedFileExcludes `
            -Destination $destinationDirectory;
        }
        $_exchange['LOOPZ.MIRROR.COPIED-FILES.COUNT'] = $filesToCopy.Count;

        Write-Debug " [-] No of files copied: '$($filesToCopy.Count)'";
      }
      else {
        $_exchange.Remove('LOOPZ.MIRROR.COPIED-FILES.COUNT');
        $_exchange.Remove('LOOPZ.MIRROR.COPIED-FILES.INCLUDES');
      }
    }

    # To be consistent with Invoke-ForeachFsItem, the user function/block is invoked
    # with the source directory info. The destination for this mirror operation is
    # returned via 'LOOPZ.MIRROR.DESTINATION' within the Exchange.
    #
    $_exchange['LOOPZ.MIRROR.DESTINATION'] = $destinationInfo;

    $invokee = $_exchange['LOOPZ.MIRROR.INVOKEE'];

    if ($invokee -is [scriptblock]) {
      $positional = @($_underscore, $_index, $_exchange, $_trigger);

      if ($_exchange.ContainsKey('LOOPZ.MIRROR.INVOKEE.PARAMS')) {
        $_exchange['LOOPZ.MIRROR.INVOKEE.PARAMS'] | ForEach-Object {
          $positional += $_;
        }
      }

      $invokee.InvokeReturnAsIs($positional);
    }
    elseif ($invokee -is [string]) {
      [hashtable]$parameters = $_exchange.ContainsKey('LOOPZ.MIRROR.INVOKEE.PARAMS') `
        ? $_exchange['LOOPZ.MIRROR.INVOKEE.PARAMS'] : @{};
      $parameters['Underscore'] = $_underscore;
      $parameters['Index'] = $_index;
      $parameters['Exchange'] = $_exchange;
      $parameters['Trigger'] = $_trigger;

      & $invokee @parameters;
    }
    else {
      Write-Warning "User defined function/block not valid, not invoking.";
    }

    @{ Product = $destinationInfo }
  } #doMirrorBlock

  # ===================================================== [Invoke-MirrorDirectoryTree] ===

  [string]$resolvedSourcePath = Convert-Path $Path;
  [string]$resolvedDestinationPath = Convert-Path $DestinationPath;

  $Exchange['LOOPZ.MIRROR.ROOT-SOURCE'] = $resolvedSourcePath;
  $Exchange['LOOPZ.MIRROR.ROOT-DESTINATION'] = $resolvedDestinationPath;

  if ('InvokeScriptBlock' -eq $PSCmdlet.ParameterSetName) {
    $Exchange['LOOPZ.MIRROR.INVOKEE'] = $Block;

    if ($BlockParams.Count -gt 0) {
      $Exchange['LOOPZ.MIRROR.INVOKEE.PARAMS'] = $BlockParams;
    }
  }
  else {
    $Exchange['LOOPZ.MIRROR.INVOKEE'] = $Functee;

    if ($FuncteeParams.PSBase.Count -gt 0) {
      $Exchange['LOOPZ.MIRROR.INVOKEE.PARAMS'] = $FuncteeParams.Clone();
    }
  }

  if ($PSBoundParameters.ContainsKey('WhatIf') -and ($true -eq $PSBoundParameters['WhatIf'])) {
    $Exchange['WHAT-IF'] = $true;
  }

  if ($CopyFiles.ToBool()) {
    $Exchange['LOOPZ.MIRROR.COPIED-FILES.INCLUDES'] = $FileIncludes -join ', ';
  }

  [scriptblock]$filterDirectories = {
    [OutputType([boolean])]
    param(
      [System.IO.DirectoryInfo]$directoryInfo
    )
    Select-FsItem -Name $directoryInfo.Name `
      -Includes $DirectoryIncludes -Excludes $DirectoryExcludes;
  }

  $null = Invoke-TraverseDirectory -Path $resolvedSourcePath `
    -Block $doMirrorBlock -Exchange $Exchange -Header $Header -Summary $Summary `
    -SessionHeader $SessionHeader -SessionSummary $SessionSummary -Condition $filterDirectories -Hoist:$Hoist;
} # Invoke-MirrorDirectoryTree

function Invoke-TraverseDirectory {
  <#
  .NAME
    Invoke-TraverseDirectory
 
  .SYNOPSIS
    Traverses a directory tree invoking a custom defined script-block or named function
  as it goes.
 
  .DESCRIPTION
    Navigates a directory tree applying custom functionality for each directory. A Condition
  script-block can be applied for conditional functionality. 2 parameters set are defined, one
  for invoking a named function (InvokeFunction) and the other (InvokeScriptBlock, the default)
  for invoking a scriptblock. An optional Summary script block can be specified which will be
  invoked at the end of the traversal batch.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Block
    The script block to be invoked. The script block is invoked for each directory in the
  source directory tree that satisfy the specified Condition predicate with
  the following positional parameters:
    * underscore: the DirectoryInfo object representing the directory in the source tree
    * index: the 0 based index representing current directory in the source tree
    * Exchange object: a hash table containing miscellaneous information gathered internally
    throughout the mirroring batch. This can be of use to the user, because it is the way
    the user can perform bi-directional communication between the invoked custom script block
    and client side logic.
    * trigger: a boolean value, useful for state changing idempotent operations. At the end
    of the batch, the state of the trigger indicates whether any of the items were actioned.
    When the script block is invoked, the trigger should indicate if the trigger was pulled for
    any of the items so far processed in the batch. This is the responsibility of the
    client's script-block/function implementation.
 
  In addition to these fixed positional parameters, if the invoked scriptblock is defined
  with additional parameters, then these will also be passed in. In order to achieve this,
  the client has to provide excess parameters in BlockParams and these parameters must be
  defined as the same type and in the same order as the additional parameters in the
  script-block.
 
  .PARAMETER BlockParams
    Optional array containing the excess parameters to pass into the script-block.
 
  .PARAMETER Condition
    This is a predicate script-block, which is invoked with a DirectoryInfo object presented
  as a result of invoking Get-ChildItem. It provides a filtering mechanism that is defined
  by the user to define which directories are selected for function/script-block invocation.
 
  .PARAMETER Exchange
    A hash table containing miscellaneous information gathered internally throughout the
  traversal batch. This can be of use to the user, because it is the way the user can perform
  bi-directional communication between the invoked custom script block and client side logic.
 
  .PARAMETER Functee
    String defining the function to be invoked. Works in a similar way to the Block parameter
  for script-blocks. The Function's base signature is as follows:
  * "Underscore": (See underscore described above)
  * "Index": (See index described above)
  * "Exchange": (See PathThru described above)
  * "Trigger": (See trigger described above)
 
  The destination DirectoryInfo object can be accessed via the Exchange denoted by
  the 'LOOPZ.MIRROR.DESTINATION' entry.
 
  .PARAMETER FuncteeParams
    Optional hash-table containing the named parameters which are splatted into the Functee
  function invoke. As it's a hash table, order is not significant.
 
  .PARAMETER Header
    A script-block that is invoked for each directory that also contains child directories.
  The script-block is invoked with the following positional parameters:
    * Exchange: (see Exchange previously described)
 
    The Header can be customised with the following Exchange entries:
    * 'LOOPZ.KRAYOLA-THEME': Krayola Theme generally in use
    * 'LOOPZ.HEADER-BLOCK.MESSAGE': message displayed as part of the header
    * 'LOOPZ.HEADER-BLOCK.CRUMB-SIGNAL': Lead text displayed in header, default: '[+] '
    * 'LOOPZ.HEADER.PROPERTIES': An array of Key/Value pairs of items to be displayed
    * 'LOOPZ.HEADER-BLOCK.LINE': A string denoting the line to be displayed. (There are
    predefined lines available to use in $LoopzUI, or a custom one can be used instead)
 
  .PARAMETER Hoist
    Switch parameter. Without Hoist being specified, the Condition can prove to be too restrictive
  on matching against directories. If a directory does not match the Condition then none of its
  descendants will be considered to be traversed. When Hoist is specified then a descendant directory
  that does match the Condition will be traversed even though any of its ancestors may not match the
  same Condition.
 
  .PARAMETER Path
    The source Path denoting the root of the directory tree to be traversed.
 
  .PARAMETER SessionHeader
    A script-block that is invoked at the start of the traversal batch. The script-block has
  the same signature as the Header script block.
 
  .PARAMETER SessionSummary
    A script-block that is invoked at the end of the traversal batch. The script-block has
  the same signature as the Summary script block.
 
  .PARAMETER Summary
    A script-block that is invoked foreach directory that also contains child directories,
  after all its descendants have been processed and serves as a sub-total for the current
  directory. The script-block is invoked with the following positional parameters:
    * count: the number of items processed in the mirroring batch.
    * skipped: the number of items skipped in the mirroring batch. An item is skipped if
    it fails the defined condition or is not of the correct type (eg if its a directory
    but we have specified the -File flag).
    * errors: the number of items which resulted in error. An error occurs when the function
    or the script-block has set the Error property on the invoke result.
    * trigger: Flag set by the script-block/function, but should typically be used to
    indicate whether any of the items processed were actively updated/written in this batch.
    This helps in written idempotent operations that can be re-run without adverse
    consequences.
    * Exchange: (see Exchange previously described)
 
  .PARAMETER Depth
    Allows the restriction of traversal by depth (aligned with the Depth parameter on Get-ChildItem).
  0 means restrict invocations to immediate children of Path, with successive increments relating
  to generations thereafter.
 
  .EXAMPLE 1
    Invoke a script-block for every directory in the source tree.
 
    [scriptblock]$block = {
      param(
        $underscore,
        [int]$index,
        [hashtable]$exchange,
        [boolean]$trigger
      )
      ...
    }
 
  Invoke-TraverseDirectory -Path './Tests/Data/fefsi' -Block $block
 
  .EXAMPLE 2
    Invoke a named function with extra parameters for every directory in the source tree.
 
  function Test-Traverse {
    param(
      [System.IO.DirectoryInfo]$Underscore,
      [int]$Index,
      [hashtable]$Exchange,
      [boolean]$Trigger,
      [string]$Format
    )
    ...
  }
  [hashtable]$parameters = @{
    'Format' = "=== {0} ===";
  }
 
  Invoke-TraverseDirectory -Path './Tests/Data/fefsi' `
    -Functee 'Test-Traverse' -FuncteeParams $parameters;
 
  .EXAMPLE 3
  Invoke a named function, including only directories beginning with A (filter A*)
 
  function Test-Traverse {
    param(
      [System.IO.DirectoryInfo]$Underscore,
      [int]$Index,
      [hashtable]$Exchange,
      [boolean]$Trigger
    )
    ...
  }
 
  [scriptblock]$filterDirectories = {
    [OutputType([boolean])]
    param(
      [System.IO.DirectoryInfo]$directoryInfo
    )
 
    Select-FsItem -Name $directoryInfo.Name -Includes @('A*');
  }
 
  Invoke-TraverseDirectory -Path './Tests/Data/fefsi' -Functee 'Test-Traverse' `
    -Condition $filterDirectories;
 
  Note the possible issue with this example is that any descendants named A... which are located
  under an ancestor which is not named A..., will not be processed by the provided function
 
  .EXAMPLE 4
  Mirror a directory tree, including only directories beginning with A (filter A*) regardless of
  the matching of intermediate ancestors (specifying -Hoist flag resolves the possible
  issue in the previous example)
 
  function Test-Traverse {
    param(
      [System.IO.DirectoryInfo]$Underscore,
      [int]$Index,
      [hashtable]$Exchange,
      [boolean]$Trigger
    )
    ...
  }
 
  [scriptblock]$filterDirectories = {
    [OutputType([boolean])]
    param(
      [System.IO.DirectoryInfo]$directoryInfo
    )
 
    Select-FsItem -Name $directoryInfo.Name -Includes @('A*');
  }
 
  Invoke-TraverseDirectory -Path './Tests/Data/fefsi' -Functee 'Test-Traverse' `
    -Condition $filterDirectories -Hoist;
 
  Note that the directory filter must include a wild-card, otherwise it will be ignored. So a
  directory include of @('A'), is problematic, because A is not a valid directory filter so its
  ignored and there are no remaining filters that are able to include any directory, so no
  directory passes the filter.
 
  .EXAMPLE 5
  Same as EXAMPLE 4, but using predefined Header and Summary script-blocks for Session header/summary
  and per directory header/summary. (Test-Traverse and filterDirectories as per EXAMPLE 4)
 
  Invoke-TraverseDirectory -Path './Tests/Data/fefsi' -Functee 'Test-Traverse' `
    -Condition $filterDirectories -Hoist `
    -Header $LoopzHelpers.DefaultHeaderBlock -Summary $DefaultHeaderBlock.SimpleSummaryBlock `
    -SessionHeader $LoopzHelpers.DefaultHeaderBlock -SessionSummary $DefaultHeaderBlock.SimpleSummaryBlock;
 
  .EXAMPLE 6
    Invoke a script-block for every directory in the source tree within a depth of 2
 
    [scriptblock]$block = {
      param(
        $underscore,
        [int]$index,
        [hashtable]$exchange,
        [boolean]$trigger
      )
      ...
    }
 
    Invoke-TraverseDirectory -Path './Tests/Data/fefsi' -Block $block -Depth 2
  #>

  [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')]
  [CmdletBinding(DefaultParameterSetName = 'InvokeScriptBlock')]
  [Alias('itd', 'Traverse-Directory')]
  param
  (
    [Parameter(ParameterSetName = 'InvokeScriptBlock', Mandatory)]
    [Parameter(ParameterSetName = 'InvokeFunction', Mandatory)]
    [ValidateScript( { Test-path -Path $_ })]
    [String]$Path,

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [ValidateScript( { -not($_ -eq $null) })]
    [scriptblock]$Condition = (
      {
        [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')]
        param([System.IO.DirectoryInfo]$directoryInfo)
        return $true;
      }
    ),

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [hashtable]$Exchange = @{},

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [ValidateScript( { -not($_ -eq $null) })]
    [scriptblock]$Block,

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [ValidateScript( { $_ -is [Array] })]
    $BlockParams = @(),

    [Parameter(ParameterSetName = 'InvokeFunction', Mandatory)]
    [ValidateScript( { -not([string]::IsNullOrEmpty($_)); })]
    [string]$Functee,

    [Parameter(ParameterSetName = 'InvokeFunction')]
    [hashtable]$FuncteeParams = @{},

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [scriptblock]$Header = ( {
        param(
          [hashtable]$_exchange
        )
      }),

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [scriptblock]$Summary = ( {
        [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')]
        param(
          [int]$_count,
          [int]$_skipped,
          [int]$_errors,
          [boolean]$_triggered,
          [hashtable]$_exchange
        )
      }),

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [scriptblock]$SessionHeader = ( {
        param(
          [hashtable]$_exchange
        )
      }),

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [scriptblock]$SessionSummary = ( {
        param(
          [int]$_count,
          [int]$_skipped,
          [int]$_errors,
          [boolean]$_trigger,
          [hashtable]$_exchange
        )
      }),

    [Parameter(ParameterSetName = 'InvokeScriptBlock')]
    [Parameter(ParameterSetName = 'InvokeFunction')]
    [switch]$Hoist,

    [Parameter()]
    [ValidateScript( { $_ -ge 0 })]
    [int]$Depth
  ) # param

  function Test-DepthInRange {

    # Assuming 'traverse' is the root path
    #
    # Get-ChildItem depth/limit -----> 0 1 2
    # controller depth --------------> 1 2 3 4
    # .\Tests\Data\traverse\Audio\MINIMAL\FUSE
    #
    [OutputType([boolean])]
    param(
      [hashtable]$Exchange
    )

    [boolean]$isInRange = if ($Exchange.ContainsKey('LOOPZ.TRAVERSE.LIMIT-DEPTH')) {
      [int]$limitDepth = $Exchange['LOOPZ.TRAVERSE.LIMIT-DEPTH']; # 0 based
      [int]$controllerDepth = $Exchange['LOOPZ.CONTROLLER.DEPTH']; # 1 based

      $($controllerDepth -le ($limitDepth + 2));
    }
    else {
      $true;
    }

    return $isInRange;
  }

  # ======================================================= [recurseTraverseDirectory] ===
  #
  [scriptblock]$recurseTraverseDirectory = { # Invoked by adapter
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')]
    param(
      [Parameter(Position = 0, Mandatory)]
      [System.IO.DirectoryInfo]$directoryInfo,

      [Parameter(Position = 1)]
      [ValidateScript( { -not($_ -eq $null) })]
      [scriptblock]$condition,

      [Parameter(Position = 2, Mandatory)]
      [ValidateScript( { -not($_ -eq $null) })]
      [hashtable]$exchange,

      [Parameter(Position = 3)]
      [ValidateScript( { ($_ -is [scriptblock]) -or ($_ -is [string]) })]
      $invokee, # (scriptblock or function name; hence un-typed parameter)

      [Parameter(Position = 4)]
      [boolean]$trigger
    )

    $result = $null;
    $index = $exchange['LOOPZ.FOREACH.INDEX'];

    # This is the invoke, for the current directory
    #
    if ($invokee -is [scriptblock]) {
      $positional = @($directoryInfo, $index, $exchange, $trigger);

      if ($exchange.ContainsKey('LOOPZ.TRAVERSE.INVOKEE.PARAMS') -and
        ($exchange['LOOPZ.TRAVERSE.INVOKEE.PARAMS'].Count -gt 0)) {
        $exchange['LOOPZ.TRAVERSE.INVOKEE.PARAMS'] | ForEach-Object {
          $positional += $_;
        }
      }
      $result = $invokee.InvokeReturnAsIs($positional);
    }
    else {
      [hashtable]$parameters = $exchange.ContainsKey('LOOPZ.TRAVERSE.INVOKEE.PARAMS') `
        ? $exchange['LOOPZ.TRAVERSE.INVOKEE.PARAMS'] : @{};

      # These are directory specific overwrites. The custom parameters
      # will still be present
      #
      $parameters['Underscore'] = $directoryInfo;
      $parameters['Index'] = $index;
      $parameters['Exchange'] = $exchange;
      $parameters['Trigger'] = $trigger;

      $result = & $invokee @parameters;
    }

    if (Test-DepthInRange -Exchange $Exchange) {
      [string]$fullName = $directoryInfo.FullName;
      [System.IO.DirectoryInfo[]]$directoryInfos = Get-ChildItem -Path $fullName `
        -Directory | Where-Object { $condition.InvokeReturnAsIs($_) };

      [scriptblock]$adapter = $Exchange['LOOPZ.TRAVERSE.ADAPTOR'];

      if ($directoryInfos) {
        # adapter is always a script block, this has nothing to do with the invokee,
        # which may be a script block or a named function(functee)
        #
        $directoryInfos | Invoke-ForeachFsItem -Directory -Block $adapter `
          -Exchange $Exchange -Condition $condition -Summary $Summary;
      }
    }

    return $result;
  } # recurseTraverseDirectory

  # ======================================================================== [adapter] ===
  #
  [scriptblock]$adapter = {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')]
    param(
      [Parameter(Mandatory)]
      [System.IO.DirectoryInfo]$_underscore,

      [Parameter(Mandatory)]
      [int]$_index,

      [Parameter(Mandatory)]
      [hashtable]$_exchange,

      [Parameter(Mandatory)]
      [boolean]$_trigger
    )

    [scriptblock]$adapted = $_exchange['LOOPZ.TRAVERSE.ADAPTED'];
    $controller = $_exchange['LOOPZ.CONTROLLER'];

    try {
      $adapted.InvokeReturnAsIs(
        $_underscore,
        $_exchange['LOOPZ.TRAVERSE.CONDITION'],
        $_exchange,
        $Exchange['LOOPZ.TRAVERSE.INVOKEE'],
        $_trigger
      );
    }
    catch [System.Management.Automation.MethodInvocationException] {
      $controller.ErrorItem();
      # This is a mystery exception, that has no effect on processing the batch:
      #
      # Exception calling ".ctor" with "2" argument(s): "Count cannot be less than zero.
      #
      # Resolve-Error
      # Write-Error "Problem with: '$_underscore'" -ErrorAction Stop;
    }
    catch {
      $controller.ErrorItem();
      Write-Error "[!] Error: $($_.Exception.Message)" -ErrorAction Continue;

      throw;
    }
  } # adapter

  # ======================================================= [Invoke-TraverseDirectory] ===

  $controller = New-Controller -Type TraverseCtrl -Exchange $Exchange `
    -Header $Header -Summary $Summary -SessionHeader $SessionHeader -SessionSummary $SessionSummary;
  $Exchange['LOOPZ.CONTROLLER'] = $controller;

  if ($PSBoundParameters.ContainsKey('Depth')) {
    $Exchange['LOOPZ.TRAVERSE.LIMIT-DEPTH'] = $Depth;
  }

  $controller.BeginSession();

  # Handle top level directory, before recursing through child directories
  #
  [System.IO.DirectoryInfo]$directory = Get-Item -Path $Path;

  [boolean]$itemIsDirectory = ($directory.Attributes -band
    [System.IO.FileAttributes]::Directory) -eq [System.IO.FileAttributes]::Directory;

  if ($itemIsDirectory) {
    if ($Condition.InvokeReturnAsIs($directory)) {
      [boolean]$trigger = $controller.GetTrigger();

      # The index of the top level directory is always 0
      #
      [int]$index = $controller.RequestIndex();

      if ('InvokeFunction' -eq $PSCmdlet.ParameterSetName) {
        # set-up custom parameters
        #
        [hashtable]$parameters = $FuncteeParams.Clone();
        $parameters['Underscore'] = $directory;
        $parameters['Index'] = $index;
        $parameters['Exchange'] = $Exchange;
        $parameters['Trigger'] = $trigger;
        $Exchange['LOOPZ.TRAVERSE.INVOKEE.PARAMS'] = $parameters;
      }
      elseif ('InvokeScriptBlock' -eq $PSCmdlet.ParameterSetName) {
        $positional = @($directory, $index, $Exchange, $trigger);

        if ($BlockParams.Count -gt 0) {
          $BlockParams | Foreach-Object {
            $positional += $_;
          }
        }

        # Note, for the positional parameters, we can only pass in the additional
        # custom parameters provided by the client here via the Exchange otherwise
        # we could accidentally build up the array of positional parameters with
        # duplicated entries. This is in contrast to splatted arguments for function
        # invokes where parameter names are paired with parameter values in a
        # hashtable and naturally prevent duplicated entries. This is why we set
        # 'LOOPZ.TRAVERSE.INVOKEE.PARAMS' to $BlockParams and not $positional.
        #
        $Exchange['LOOPZ.TRAVERSE.INVOKEE.PARAMS'] = $BlockParams;
      }

      $result = $null;

      try {
        # No need to consider the depth here because this is the top level invoke
        # which should never be skipped because of the depth limit
        #
        if ('InvokeScriptBlock' -eq $PSCmdlet.ParameterSetName) {
          $result = $Block.InvokeReturnAsIs($positional);
        }
        elseif ('InvokeFunction' -eq $PSCmdlet.ParameterSetName) {
          $result = & $Functee @parameters;
        }
      }
      catch {
        $result = [PSCustomObject]@{
          ErrorReason = "Unhandled Error: $($_.Exception.Message)";
        }
      }
      finally {
        $controller.HandleResult($result);
      }
    }
    else {
      $controller.SkipItem();
    }

    # --- end of top level invoke ----------------------------------------------------------

    if ($Hoist.IsPresent) {
      # Perform non-recursive retrieval of descendant directories
      #
      [hashtable]$parametersGeChItem = @{
        'Path'      = $Path;
        'Directory' = $true;
        'Recurse'   = $true;
      }
      if ($PSBoundParameters.ContainsKey('Depth')) {
        $parametersGeChItem['Depth'] = $Depth;
      }

      [System.IO.DirectoryInfo[]]$directoryInfos = Get-ChildItem @parametersGeChItem | Where-Object {
        $Condition.InvokeReturnAsIs($_)
      }

      Write-Debug " [o] Invoke-TraverseDirectory (Hoist); Count: $($directoryInfos.Count)";

      if ($directoryInfos) {
        # No need to manage the index, let Invoke-ForeachFsItem do this for us,
        # except we do need to inform Invoke-ForeachFsItem to start the index at
        # +1, because 0 is for the top level directory which has already been
        # handled.
        #
        [hashtable]$parametersFeFsItem = @{
          'Directory' = $true;
          'Exchange'  = $Exchange;
          'Summary'   = $Summary;
        }

        if ('InvokeScriptBlock' -eq $PSCmdlet.ParameterSetName) {
          $parametersFeFsItem['Block'] = $Block;
          $parametersFeFsItem['BlockParams'] = $BlockParams;
        }
        else {
          $parametersFeFsItem['Functee'] = $Functee;
          $parametersFeFsItem['FuncteeParams'] = $FuncteeParams;
        }

        $directoryInfos | & 'Invoke-ForeachFsItem' @parametersFeFsItem;
      }
    }
    else {
      # Top level descendants
      #
      # Set up the adapter. (NB, can't use splatting because we're invoking a script block
      # as opposed to a named function.)
      #
      $Exchange['LOOPZ.TRAVERSE.CONDITION'] = $Condition;
      $Exchange['LOOPZ.TRAVERSE.ADAPTED'] = $recurseTraverseDirectory;
      $Exchange['LOOPZ.TRAVERSE.ADAPTOR'] = $adapter;

      if ('InvokeScriptBlock' -eq $PSCmdlet.ParameterSetName) {
        $Exchange['LOOPZ.TRAVERSE.INVOKEE'] = $Block;
      }
      elseif ('InvokeFunction' -eq $PSCmdlet.ParameterSetName) {
        $Exchange['LOOPZ.TRAVERSE.INVOKEE'] = $Functee;
      }

      # Now perform start of recursive traversal
      #
      [System.IO.DirectoryInfo[]]$directoryInfos = Get-ChildItem -Path $Path `
        -Directory | Where-Object { $Condition.InvokeReturnAsIs($_) }

      if ($directoryInfos) {
        $directoryInfos | Invoke-ForeachFsItem -Directory -Block $adapter `
          -Exchange $Exchange -Condition $Condition -Summary $Summary;
      }
    }
  }
  else {
    $controller.SkipItem();
    Write-Error "Path specified '$($Path)' is not a directory";
  }

  $controller.EndSession();
} # Invoke-TraverseDirectory
function get-Captures {
  [OutputType([hashtable])]
  param(
    [Parameter(Mandatory)]
    [System.Text.RegularExpressions.Match]$MatchObject
  )

  [hashtable]$captures = @{}
  [System.Text.RegularExpressions.GroupCollection]$groups = $MatchObject.Groups;

  foreach ($key in $groups.Keys) {
    $captures[$key] = $groups[$key];
  }

  return $captures;
}

function New-RegularExpression {
  <#
  .NAME
    New-RegularExpression
 
  .SYNOPSIS
    regex factory function.
 
  .DESCRIPTION
    Creates a regex object from the $Expression specified. Supports inline regex
  flags ('mixsn') which must be specified at the end of the $Expression after a
  '/'.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Escape
    switch parameter to indicate that the expression should be escaped. (This is an
  alternative to the '~' prefix).
 
  .PARAMETER Expression
    The pattern for the regular expression. If it starts with a tilde ('~'), then
  the whole expression is escaped so any special regex characters are interpreted
  literally.
 
  .PARAMETER Label
    string that gives a name to the regular expression being created and is used for
  logging/error reporting purposes only, so it's not mandatory.
 
  .PARAMETER WholeWord
    switch parameter to indicate the expression should be wrapped with word boundary
  markers \b, so an $Expression defined as 'foo' would be adjusted to '\bfoo\b'.
 
  .EXAMPLE 1 (Create a regular expression object)
  New-RegularExpression -Expression '(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})'
 
  .EXAMPLE 2 (with WholeWord)
  New-RegularExpression -Expression '(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})' -WholeWord
 
  .EXAMPLE 3 (Escaped)
  New-RegularExpression -Expression '(123)' -Escape
 
  .EXAMPLE 4 (Escaped with leading ~)
  New-RegularExpression -Expression '~(123)'
 
  .EXAMPLE 5 (Create a case insensitive expression)
  New-RegularExpression -Expression 'DATE/i'
  #>

  [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions',
    '', Justification = 'Not a state changing function, its a factory')]
  [OutputType([System.Text.RegularExpressions.RegEx])]
  param(
    [Parameter(Position = 0, Mandatory)]
    [string]$Expression,

    [Parameter()]
    [switch]$Escape,

    [Parameter()]
    [switch]$WholeWord,

    [Parameter()]
    [string]$Label
  )

  [System.Text.RegularExpressions.RegEx]$resultRegEx = $null;
  [System.Text.RegularExpressions.RegEx]$extractOptionsRegEx = New-Object `
    -TypeName System.Text.RegularExpressions.RegEx -ArgumentList (
    '[\/\\](?<codes>[mixsn]{1,5})$');

  try {
    [string]$adjustedExpression = ($Expression.StartsWith('~') -or $Escape.IsPresent) `
      ? [regex]::Escape($Expression.Substring(1)) : $Expression;

    [string[]]$optionsArray = @();

    [string]$options = if ($extractOptionsRegEx.IsMatch($adjustedExpression)) {
      $null, $adjustedExpression, [System.Text.RegularExpressions.Match]$optionsMatch = `
        Split-Match -Source $adjustedExpression -PatternRegEx $extractOptionsRegEx;

      [string]$inlineCodes = $optionsMatch.Groups['codes'];

      # NOTE, beware of [string]::ToCharArray, the returned result MUST be cast to [string[]]
      #
      [string[]]$inlineCodes.ToCharArray() | ForEach-Object {
        $optionsArray += $Loopz.InlineCodeToOption[$_]
      }

      $optionsArray -join ', ';
    } else {
      $null;
    }

    if (-not([string]::IsNullOrEmpty($options))) {
      Write-Debug "New-RegularExpression; created RegEx for pattern: '$adjustedExpression', with options: '$options'";
    }

    if ($WholeWord.ToBool()) {
      $adjustedExpression = '\b{0}\b' -f $adjustedExpression;
    }

    $arguments = $options ? @($adjustedExpression, $options) : @(, $adjustedExpression);
    $resultRegEx = New-Object -TypeName System.Text.RegularExpressions.RegEx -ArgumentList (
      $arguments);
  }
  catch [System.Management.Automation.MethodInvocationException] {
    [string]$message = ($PSBoundParameters.ContainsKey('Label')) `
      ? $('Regular expression ({0}) "{1}" is not valid, ... terminating ({2}).' `
        -f $Label, $adjustedExpression, $_.Exception.Message)
    : $('Regular expression "{0}" is not valid, ... terminating ({1}).' `
        -f $adjustedExpression, $_.Exception.Message);
    Write-Error -Message $message -ErrorAction Stop;
  }

  $resultRegEx;
}

function Split-Match {
  <#
  .NAME
    Split-Match
 
  .SYNOPSIS
    Splits out a match from the remainder of the $Source text returning the matched
  test, the remainder and the corresponding match object.
 
  .DESCRIPTION
    Helper function to get the pattern match and the remaining text. This helper
  helps us to avoid unnecessary duplicated reg ex matches. It returns
  up to 3 items inside an array, the first is the matched text, the second is
  the source with the matched text removed and the third is the match object
  that represents the matched text.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER CapturedOnly
    switch parameter to indicate what should be returned. When the client does not need
  the match object or the remainder, they can use this switch to ensure only the matched
  text is returned.
 
  .PARAMETER Marker
    A character used to mark the place where the $PatternRegEx's match was removed from.
  It should be a special character that is not easily typed on the keyboard by the user
  so as to not interfere wth $Anchor/$Copy matches which occur after $Pattern match is
  removed.
 
  .PARAMETER Occurrence
    Denotes which match should be used.
 
  .PARAMETER PatternRegEx
    The regex object to apply to the $Source.
 
  .PARAMETER Source
    The source value against which regular expression is applied.
 
  .EXAMPLE 1 (Return full match info)
  [regex]$re = New-RegularExpression -Expression '(?<d>\d{2})-(?<m>\d{2})-(?<y>\d{4})'
  [string]$captured, [string]$remainder, $matchInfo = Split-Match -Source '23-06-2006 - Ex' -PatternRegEx $re
 
  .EXAMPLE 2 (Return captured text only)
  [regex]$re = New-RegularExpression -Expression '(?<d>\d{2})-(?<m>\d{2})-(?<y>\d{4})'
  [string]$captured = Split-Match -Source '23-06-2006 - Ex' -PatternRegEx $re -CapturedOnly
  #>

  param(
    [Parameter(Mandatory)]
    [string]$Source,

    [Parameter()]
    [System.Text.RegularExpressions.RegEx]$PatternRegEx,

    [Parameter()]
    [ValidateScript( { $_ -ne '0' })]
    [string]$Occurrence = 'f',

    [Parameter()]
    [switch]$CapturedOnly,

    [Parameter()]
    [char]$Marker = 0x20DE
  )

  [System.Text.RegularExpressions.MatchCollection]$mc = $PatternRegEx.Matches($Source);

  if ($mc.Count -gt 0) {
    # Get the match instance
    #
    [System.Text.RegularExpressions.Match]$m = if ($Occurrence -eq 'f') {
      $mc[0];
    }
    elseif ($Occurrence -eq 'l') {
      $mc[$mc.Count - 1];
    }
    else {
      try {
        [int]$nth = [int]::Parse($Occurrence);
      }
      catch {
        [int]$nth = 1;
      }

      ($nth -le $mc.Count) ? $mc[$nth - 1] : $null;
    }
  }
  else {
    [System.Text.RegularExpressions.Match]$m = $null;
  }

  $result = $null;
  if ($m) {
    [string]$capturedText = $m.Value;

    $result = if ($CapturedOnly.ToBool()) {
      $capturedText;
    }
    else {
      # Splatting the arguments fails because the parameter validation in Get-InverseSubString
      # fails, due to parameters not having been bound yet.
      # https://github.com/PowerShell/PowerShell/issues/14457
      #
      [string]$remainder = $PSBoundParameters.ContainsKey('Marker') `
        ? $(Get-InverseSubString -Source $Source -StartIndex $m.Index -Length $m.Length -Marker $Marker) `
        : $(Get-InverseSubString -Source $Source -StartIndex $m.Index -Length $m.Length);

      @($capturedText, $remainder, $m);
    }
  }

  return $result;
} # Split-Match

function test-ValidPatternArrayParam {
  [OutputType([boolean])]
  param(
    [Parameter(Mandatory)]
    [array]$Arg,

    [Parameter()]
    [switch]$AllowWildCard
  )

  [boolean]$result = $Arg -and ($Arg.Count -gt 0) -and ($Arg.Count -lt 2) -and `
    -not([string]::IsNullOrEmpty($Arg[0])) -and (($Arg.Length -eq 1) -or $Arg[1] -ne '*');

  if ($result -and $Arg.Count -gt 1 -and $Arg[1] -eq '*') {
    $result = $AllowWildCard.ToBool();
  }

  $result;
}

function Update-GroupRefs {
  <#
  .NAME
    Update-GroupRefs
 
  .SYNOPSIS
    Updates group references with their captured values.
 
  .DESCRIPTION
    Returns a new string that reflects the replacement of group named references. The only
  exception is $0, meaning the whole match (not required).
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Source
    The source value containing group references. NB This MUST be an un-interpolated string,
  so if using a literal it should be in single quotes NOT double; this is to prevent the
  interpolation process from attempting to evaluate the group reference, eg ${count}.
 
  .PARAMETER Captures
    Hashtable mapping named group reference to group capture value.
 
  #>

  [OutputType([string])]
  [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
  param(
    [Parameter()]
    [string]$Source,

    [Parameter()]
    [Hashtable]$Captures
  )

  [string]$sourceText = $Source;
  $Captures.GetEnumerator() | ForEach-Object {
    if ($_.Key -ne '0') {
      [string]$groupRef = $('${' + $_.Key + '}');
      $sourceText = $sourceText.Replace($groupRef, $_.Value);
    }
  }

  return $sourceText;
}

function Format-BooleanCellValue {
  <#
  .NAME
    Format-BooleanCellValue
 
  .SYNOPSIS
    Table Render callback that can be passed into Show-AsTable
 
  .DESCRIPTION
    For table cells containing boolean fields, this callback function will
  render the cell with alternative values other than 'true' or 'false'. Typically,
  the client would set the alternative representation of these boolean values
  (the default values are emoji values 'SWITCH-ON'/'SWITCH-OFF') in the table
  options.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER TableOptions
    The PSCustomObject that contains the alternative boolean values (./Values/True
  and ./Values/False)
 
  .PARAMETER Value
    The original boolean value in string form.
  #>

  [OutputType([string])]
  param(
    [Parameter()]
    [string]$Value,

    [Parameter()]
    [PSCustomObject]$TableOptions
  )

  [string]$coreValue = $value.Trim() -eq 'True' `
    ? $TableOptions.Values.True : $TableOptions.Values.False;

  [string]$cellValue = Get-PaddedLabel -Label $coreValue -Width $value.Length `
    -Align $TableOptions.Align.Cell;

  return $cellValue;
}

function Format-StructuredLine {
  <#
  .NAME
    Format-StructuredLine
 
  .SYNOPSIS
    Helper function to make it easy to generate a line to be displayed.
 
  .DESCRIPTION
    A structured line is some text that includes embedded colour instructions that
  will be interpreted by the Krayola krayon writer. This function behaves like a
  layout manager for a single line.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER CrumbKey
    The key used to index into the $Exchange hashtable to denote which crumb is used.
 
  .PARAMETER Exchange
    The exchange hashtable object.
 
  .PARAMETER LineKey
    The key used to index into the $Exchange hashtable to denote the core line.
 
  .PARAMETER MessageKey
    The key used to index into the $Exchange hashtable to denote what message to display.
 
  .PARAMETER Options
 
   + this is the crumb
   |
   V <-- message ->|
  [@@] --------------------------------------------------- [ Rename (WhatIf) ] ---
                                                                                |<-- This is a trailing wing
                                                                                whose length is WingLength
       |<--- flex part (which must be at least -------->|
                        MinimumFlexSize in length, it shrinks to accommodate the message)
 
    A PSCustomObject that allows further customisation of the structured line. Can contain the following
  fields:
  - WingLength: The size of the lead and tail portions of the line ('---')
  - MinimumFlexSize: The smallest size that the flex part can shrink to, to accommodate
  the message. If the message is so large that is pushes up against the minimal flex size
  it will be truncated according to the presence of Truncate switch
  - Ellipses: When message truncation occurs, the ellipses string is used to indicate that
  the message has been truncated.
  - WithLead: boolean flag to indicate whether a leading wing is displayed which would precede
  the crumb. In the above example and by default, there is no leading wing.
 
  .PARAMETER Truncate
    switch parameter to indicate whether the message is truncated to fit the line length.
 
  #>

  [OutputType([string])]
  param(
    [Parameter(Mandatory)]
    [hashtable]$Exchange,

    # We need to replace the exchange key parameters with direct parameters
    [Parameter(Mandatory)]
    [string]$LineKey,

    [Parameter()]
    [string]$CrumbKey,

    [Parameter()]
    [string]$MessageKey,

    [Parameter()]
    [switch]$Truncate,

    [Parameter()]
    [PSCustomObject]$Options = (@{
        WingLength      = 3;
        MinimumFlexSize = 6;
        Ellipses        = ' ...';
        WithLead        = $false;
      })
  )
  [Scribbler]$scribbler = $Exchange['LOOPZ.SCRIBBLER'];
  if (-not($scribbler)) {
    throw [System.Management.Automation.MethodInvocationException]::new(
      "Format-StructuredLine: Scribbler missing from Exchange under key 'LOOPZ.SCRIBBLER'");
  }
  [Krayon]$krayon = $scribbler.Krayon;

  [string]$lnSnippet = $scribbler.Snippets(@('Ln'));
  [string]$metaSnippet = $scribbler.WithArgSnippet('ThemeColour', 'meta');
  [string]$messageSnippet = $scribbler.WithArgSnippet('ThemeColour', 'message');

  [int]$wingLength = Get-PsObjectField $Options 'WingLength' 3;
  [int]$minimumFlexSize = Get-PsObjectField $Options 'MinimumFlexSize' 6;
  [string]$ellipses = Get-PsObjectField $Options 'Ellipses' ' ...';
  [boolean]$withLead = Get-PsObjectField $Options 'WithLead' $false;

  [hashtable]$theme = $krayon.Theme;

  [string]$line = $Exchange.ContainsKey($LineKey) `
    ? $Exchange[$LineKey] : ([string]::new("_", 81));
  [string]$char = ($line -match '[^\s]') ? $matches[0] : ' ';
  [string]$wing = [string]::new($char, $wingLength);

  [string]$message = -not([string]::IsNullOrEmpty($MessageKey)) -and ($Exchange.ContainsKey($MessageKey)) `
    ? $Exchange[$MessageKey] : $null;

  [string]$crumb = if (-not([string]::IsNullOrEmpty($CrumbKey)) -and ($Exchange.ContainsKey($CrumbKey))) {
    if ($Exchange.ContainsKey('LOOPZ.SIGNALS')) {
      [hashtable]$signals = $Exchange['LOOPZ.SIGNALS'];
      [string]$crumbName = $Exchange[$CrumbKey];
      $signals[$crumbName].Value;
    }
    else {
      '+';
    }
  }
  else {
    $null;
  }

  [string]$structuredLine = if ([string]::IsNullOrEmpty($message) -and [string]::IsNullOrEmpty($crumb)) {
    $("$($metaSnippet)$($line)$($lnSnippet)");
  }
  else {
    [string]$open = $theme['OPEN'];
    [string]$close = $theme['CLOSE'];

    # TODO: The deductions need to be calculated in a dynamic form, to cater
    # for optional fields.
    #

    if (-not([string]::IsNullOrEmpty($message)) -and -not([string]::IsNullOrEmpty($crumb))) {
      # 'lead' + 'open' + 'crumb' + 'close' + 'mid' + 'open' + 'message' + 'close' + 'tail'
      #
      # '*{lead} *{open}*{crumb}*{close} *{mid} *{open} *{message} *{close} *{tail}' => Format
      # +-----------------------------------------------|--------|-----------------+
      # | Start | | End | => Snippet
      #
      [string]$startFormat = '*{open}*{crumb}*{close} *{mid} *{open} ';
      if ($withLead) {
        $startFormat = '*{lead} ' + $startFormat;
      }
      [string]$endFormat = ' *{close} *{tail}';

      [string]$startSnippet = $startFormat.Replace('*{lead}', $wing). `
        Replace('*{open}', $open). `
        Replace('*{crumb}', $crumb). `
        Replace('*{close}', $close);

      [string]$endSnippet = $endFormat.Replace('*{close}', $close). `
        Replace('*{tail}', $wing);

      [string]$withoutMid = $startSnippet.Replace('*{mid}', '') + $endSnippet;
      [int]$deductions = $withoutMid.Length + $minimumFlexSize;
      [int]$messageSpace = $line.Length - $deductions;
      [boolean]$overflow = $message.Length -gt $messageSpace;

      [int]$midSize = if ($overflow) {
        # message size is the unknown variable and $midSize is a known
        # quantity: minimumFlexSize.
        #
        if ($Truncate.ToBool()) {
          [int]$messageKeepAmount = $messageSpace - $ellipses.Length;
          $message = $message.Substring(0, $messageKeepAmount) + $ellipses;
        }
        $minimumFlexSize;
      }
      else {
        # midSize is the unknown variable and the message size is a known
        # quantity: $message.Length
        #
        [int]$deductions = $withoutMid.Length + $message.Length;
        $line.Length - $deductions;
      }

      [string]$mid = [string]::new($char, $midSize);
      $startSnippet = $startSnippet.Replace('*{mid}', $mid);

      $(
        "$($metaSnippet)$($startSnippet)" +
        "$($messageSnippet)$($message)" +
        "$($metaSnippet)$($endSnippet)$($lnSnippet)"
      );
    }
    elseif (-not([string]::IsNullOrEmpty($message))) {
      # 'lead' + 'open' + 'message' + 'close' + 'tail'
      #
      # '*{lead} *{open} *{message} *{close} *{tail}'
      # +----------------|--------|-----------------+
      # | Start | | End | => Snippet
      #
      # The lead is mandatory in this case so ignore withLead
      #
      [string]$startFormat = '*{lead} *{open} ';
      [string]$endFormat = ' *{close} *{tail}';
      [string]$endSnippet = $endFormat.Replace('*{close}', $close). `
        Replace('*{tail}', $wing);

      [string]$withoutLead = $startFormat.Replace('*{lead}', ''). `
        Replace('*{open}', $open);

      [int]$deductions = $minimumFlexSize + $withoutLead.Length + $endSnippet.Length;
      [int]$messageSpace = $line.Length - $deductions;
      [boolean]$overflow = $message.Length -gt $messageSpace;
      [int]$leadSize = if ($overflow) {
        if ($Truncate.ToBool()) {
          # Truncate the message
          #
          [int]$messageKeepAmount = $messageSpace - $Ellipses.Length;
          $message = $message.Substring(0, $messageKeepAmount) + $Ellipses;
        }
        $minimumFlexSize;
      }
      else {
        $line.Length - $withoutLead.Length - $message.Length - $endSnippet.Length;
      }

      # The lead is now the variable part so should be calculated last
      #
      [string]$lead = [string]::new($char, $leadSize);
      [string]$startSnippet = $startFormat.Replace('*{lead}', $lead). `
        Replace('*{open}', $open);

      $(
        "$($metaSnippet)$($startSnippet)" +
        "$($messageSnippet)$($message)" +
        "$($metaSnippet)$($endSnippet)$($lnSnippet)"
      );
    }
    elseif (-not([string]::IsNullOrEmpty($crumb))) {
      # 'lead' + 'open' + 'crumb' + 'close' + 'tail'
      #
      # '*{lead} *{open}*{crumb}*{close} *{tail}'
      # +--------------------------------+------+
      # |Start |End | => 2 Snippets can be combined into lineSnippet
      # because they use the same colours.
      #
      [string]$startFormat = '*{open}*{crumb}*{close} ';
      if ($withLead) {
        $startFormat = '*{lead} ' + $startFormat;
      }

      [string]$startFormat = '*{open}*{crumb}*{close} ';
      [string]$startSnippet = $startFormat.Replace('*{lead}', $wing). `
        Replace('*{open}', $open). `
        Replace('*{crumb}', $crumb). `
        Replace('*{close}', $close);

      [string]$withTailFormat = $startSnippet + '*{tail}';
      [int]$deductions = $startSnippet.Length;
      [int]$tailSize = $line.Length - $deductions;
      [string]$tail = [string]::new($char, $tailSize);
      [string]$lineSnippet = $withTailFormat.Replace('*{tail}', $tail);

      $("$($metaSnippet)$($lineSnippet)$($lnSnippet)");
    }
  }

  return $structuredLine;
}

function Get-AsTable {
  <#
  .NAME
    Get-AsTable
 
  .SYNOPSIS
    Selects the table header and data from source and meta data.
 
  .DESCRIPTION
    The client can override the behaviour to perform custom evaluation of
  table cell values. The default will space pad the cell value and align
  according the table options (./HeaderAlign and ./ValueAlign).
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Evaluate
    A script-block allowing client defined cell rendering logic. The Render script-block
  contains the following parameters:
  - Value: the current value of the cell being rendered.
  - columnData: column meta data
  - isHeader: flag to indicate if the current cell being evaluated is a header, if false
  then it is a data cell.
  - Options: The table display options
 
  .PARAMETER MetaData
    Hashtable instance which maps column titles to a PSCustomObject instance that
  contains display information pertaining to that column. The object must contain
  the following members:
   
  - FieldName: the name of the column
  - Max: the size of the largest value found in the table data for that column
  - Type: the type of data represented by that column
 
  .PARAMETER Options
    The table display options (See Get-TableDisplayOptions)
 
  .PARAMETER TableData
    Hashtable containing the table data.
  #>

  [OutputType([hashtable])]
  param(
    [Parameter()]
    [hashtable]$MetaData,

    [Parameter()]
    [PSCustomObject[]]$TableData,

    [Parameter()]
    [PSCustomObject]$Options,

    [Parameter()]
    [scriptblock]$Evaluate = $([scriptblock] {
        [OutputType([string])]
        param(
          [string]$value,
          [PSCustomObject]$columnData,
          [boolean]$isHeader,
          [PSCustomObject]$Options
        )
        # If the client wants to use this default, the meta data must
        # contain an int Max field denoting the max value size.
        #
        $max = $columnData.Max;

        [string]$align = $isHeader ? $Options.HeaderAlign : $Options.ValueAlign;
        return $(Get-PaddedLabel -Label $value -Width $max -Align $align);
      }
    )
  )
  # NB The table returned, uses the 'Name' as the row's key, and implies 2 things
  # 1) the table must have a Name column
  # 2) no 2 rows can have the same Name
  # This could be improved upon in the future to remove these 2 limitations
  #
  [hashtable]$headers = @{}
  $MetaData.GetEnumerator() | ForEach-Object {
    $headers[$_.Key] = $Evaluate.InvokeReturnAsIs($_.Key, $MetaData[$_.Key], $true, $Options)
  }

  [hashtable]$table = @{}
  foreach ($row in $TableData) {
    [PSCustomObject]$insert = @{}
    foreach ($field in $row.psobject.properties.name) { # .name here should not be assumed; it should be custom ID field
      [string]$raw = $row.$field;
      [string]$cell = $Evaluate.InvokeReturnAsIs($raw, $MetaData[$field], $false, $Options);
      $insert.$field = $cell;
    }
    # Insert table row here
    #
    $table[$row.Name] = $insert;
  }

  return $headers, $table;
}

function Get-SyntaxScheme {
  <#
  .NAME
    Get-SyntaxScheme
 
  .SYNOPSIS
    Get the scheme instance required by Command Syntax functionality in the
  parameter set tools.
 
  .DESCRIPTION
    The scheme is related to the Krayola theme. Some of the entries in the scheme
  are derived from the Krayola theme. The colours are subject to the presence of
  the environment variable 'KRAYOLA_LIGHT_TERMINAL', this is to prevent light
  foreground colours being selected when the background is also using light colours.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Theme
    The Krayola theme that the scheme will be associated with.
  #>

  [OutputType([Hashtable])]
  param(
    [Parameter()]
    [Hashtable]$Theme
  )
  [Hashtable]$scheme = @{
    'COLS.PUNCTUATION'    = $Theme['META-COLOURS'];
    'COLS.HEADER'         = 'black', 'bgYellow';
    'COLS.HEADER-UL'      = 'darkYellow';
    'COLS.UNDERLINE'      = $Theme['META-COLOURS'];
    'COLS.CELL'           = 'gray';
    'COLS.TYPE'           = 'darkCyan';
    'COLS.MAN-PARAM'      = $Theme['AFFIRM-COLOURS'];
    'COLS.OPT-PARAM'      = 'blue'
    'COLS.CMD-NAME'       = 'darkGreen';
    'COLS.PARAM-SET-NAME' = 'green';
    'COLS.SWITCH'         = 'cyan';
    'COLS.HI-LIGHT'       = 'white';
    'COLS.SPECIAL'        = 'darkYellow';
    'COLS.ERROR'          = 'black', 'bgRed';
    'COLS.OK'             = 'black', 'bgGreen';
    'COLS.COMMON'         = 'magenta';
  }

  if (Get-IsKrayolaLightTerminal) {
    $scheme['COLS.CELL'] = 'magenta';
    $scheme['COLS.HI-LIGHT'] = 'black';
  }

  return $scheme;
}

function Get-TableDisplayOptions {
  <#
  .NAME
    Get-TableDisplayOptions
 
  .SYNOPSIS
    Gets the default table display options.
 
  .DESCRIPTION
    The client can further customise by overwriting the members on the
  PSCustomObject returned.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Custom
    A client defined PSCustomObject that will be populated under the ./Custom in the
  PSCustomObject returned.
 
  .PARAMETER Scribbler
    The Krayola scribbler instance used to manage rendering to console.
 
  .PARAMETER Select
    An array of strings defining which columns are selected to be shown in the table.
 
  .PARAMETER Signals
    The signals hashtable collection from which to select the signals.
 
  #>

  [OutputType([PSCustomObject])]
  param(
    [Parameter()]
    [hashtable]$Signals,

    [Parameter()]
    [Object]$Scribbler,

    [Parameter()]
    [string[]]$Select,

    [Parameter()]
    [PSCustomObject]$Custom = $null
  )

  [string]$trueValue = ($PSBoundParameters.ContainsKey('Signals') -and
    $Signals.ContainsKey('SWITCH-ON')) `
    ? $signals['SWITCH-ON'].Value : 'true';

  [string]$falseValue = ($PSBoundParameters.ContainsKey('Signals') -and
    $Signals.ContainsKey('SWITCH-OFF')) `
    ? $signals['SWITCH-OFF'].Value : 'false';

  [string]$titleMainColour = if (${Custom}?.Colours?.Title) {
    $Custom.Colours.Title;
  }
  else {
    'darkYellow';
  }

  [string]$titleLoColour = 'black';
  [string]$titleBackColour = 'bg' + $titleMainColour;

  [PSCustomObject]$tableOptions = [PSCustomObject]@{
    Select   = $Select;

    Chrome   = [PSCustomObject]@{
      Indent         = 3;
      Underline      = '=';
      TitleUnderline = '-<>-';
      Inter          = 1;
    }

    Colours  = [PSCustomObject]@{
      Header    = 'blue';
      Cell      = 'white';
      Underline = 'yellow';
      HiLight   = 'green';
      Title     = $titleMainColour;
      TitleLo   = $titleLoColour;
    }

    Values   = [PSCustomObject]@{
      True  = $trueValue;
      False = $falseValue;
    }

    Align    = [PSCustomObject]@{
      Header = 'right';
      Cell   = 'left';
    }

    Snippets = [PSCustomObject]@{
      Reset          = $($Scribbler.Snippets('Reset'));
      Ln             = $($Scribbler.Snippets('Ln'));
      Title          = $($Scribbler.Snippets(@($titleLoColour, $titleBackColour)));
      TitleUnderline = $($Scribbler.Snippets($titleMainColour));
    }

    Custom   = $Custom;
  }

  return $tableOptions;
}

function Show-AsTable {
  <#
  .NAME
    Show-AsTable
 
  .SYNOPSIS
    Shows the provided data in a coloured table form.
 
  .DESCRIPTION
    Requires table meta data, headers and values and renders the content according
  to the options provided. The clint can override the default cell rendering behaviour
  by providing a render function.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Headers
    Hashtable instance that represents the headers displayed for the table. Maps the
  raw column title to the actual text used to display it. In practice, this is a
  space padded version of the raw title determined from the meta data.
 
  .PARAMETER MetaData
    Hashtable instance which maps column titles to a PSCustomObject instance that
  contains display information pertaining to that column. The object must contain
 
  - FieldName: the name of the column
  - Max: the size of the largest value found in the table data for that column
  - Type: the type of data represented by that column
   
  .PARAMETER Options
    The table display options (See command Get-TableDisplayOptions)
 
  .PARAMETER Render
    A script-block allowing client defined cell rendering logic. The Render script-block
  contains the following parameters:
  - Column: spaced padded column title, indicating which column this cell is in.
  - Value: the current value of the cell being rendered.
  - row: a PSCustomObject containing all the field values for the current row. The whole
  row is presented to the cell render function so that cross field functionality can be
  defined.
  - Options: The table display options
  - Scribbler: The Krayola scribbler instance
  - counter: the row number
 
  .PARAMETER Scribbler
    The Krayola scribbler instance used to manage rendering to console.
 
  .PARAMETER Table
    Hashtable containing the table data. Currently, the data row is indexed by the
  'Name' property and as such, the Name in in row must be unique (actually acts
  like its the primary key for the table; this will be changed in future so that
  an alternative ID field is used instead of Name.)
 
  .PARAMETER Title
    If provided, this will be shown as the title for this table.
 
  .PARAMETER TitleFormat
    A table title format string which must contain a {0} place holder for the Title
  to be inserted into.
  #>

  param(
    [Parameter()]
    [hashtable]$MetaData,

    [Parameter()]
    [hashtable]$Headers,

    [Parameter()]
    [hashtable]$Table,

    [Parameter()]
    [string]$Title,

    [Parameter()]
    [string]$TitleFormat = "--- [ {0} ] ---",
  
    [Parameter()]
    [Scribbler]$Scribbler,

    [Parameter()]
    [scriptblock]$Render = $([scriptblock] {
        [OutputType([boolean])]
        param(
          [string]$column,
          [string]$Value,
          [PSCustomObject]$row,
          [PSCustomObject]$Options,
          [Scribbler]$Scribbler,
          [boolean]$counter
        )
        return $false;
      }),

    [Parameter()]
    [PSCustomObject]$Options
  )
  # TODO: The client should be able to define a render method on a per column basis.
  # Currently there is just a single render callback supported. And ideally, we should be
  # able to present the entire row, not just the current cell. This will enable cross
  # field functionality to be defined.
  #
  [string]$indentation = [string]::new(' ', $Options.Chrome.Indent);
  [string]$inter = [string]::new(' ', $Options.Chrome.Inter);
  [string]$headerSnippet = $($Options.Custom.Snippets.Header);
  [string]$underlineSnippet = $($Options.Custom.Snippets.Underline);
  [string]$resetSnippet = $($Options.Snippets.Reset);
  [string]$lnSnippet = $($Options.Snippets.Ln);
  
  $Scribbler.Scribble("$($resetSnippet)$($lnSnippet)");

  if (($MetaData.PSBase.Count -gt 0) -and ($Table.PSBase.Count -gt 0)) {
    if ($PSBoundParameters.ContainsKey('Title') -and -not([string]::IsNullOrEmpty($Title))) {
      [string]$titleSnippet = $($Options.Snippets.Title);
      [string]$titleUnderlineSnippet = $($Options.Snippets.TitleUnderline);
      [string]$adornedTitle = $TitleFormat -f $Title;
      [int]$ulLength = $Options.Chrome.TitleUnderline.Length;

      [string]$underline = $Options.Chrome.TitleUnderline * $(($adornedTitle.Length / $ulLength) + 1);

      if ($underline.Length -gt $adornedTitle.Length) {
        $underline = $underline.Substring(0, $adornedTitle.Length);
      }

      [string]$titleFragment = $(
        "$($lnSnippet)" +
        "$($indentation)$($titleSnippet)$($adornedTitle)$($resetSnippet)" +
        "$($lnSnippet)" +
        "$($indentation)$($titleUnderlineSnippet)$($underline)$($resetSnippet)" +
        "$($resetSnippet)$($lnSnippet)$($lnSnippet)"
      );
      $Scribbler.Scribble($titleFragment);
    }

    # Establish field selection
    #
    [string[]]$selection = Get-PsObjectField -Object $Options -Field 'Select';

    if (-not($selection)) {
      $selection = $Headers.PSBase.Keys;
    }

    # Display column titles
    #
    $Scribbler.Scribble($indentation);

    foreach ($col in $selection) {
      [string]$paddedValue = $Headers[$col.Trim()];
      $Scribbler.Scribble("$($headerSnippet)$($paddedValue)$($resetSnippet)$($inter)");
    }
    $Scribbler.Scribble("$($lnSnippet)$($resetSnippet)");

    # Display column underlines
    #
    $Scribbler.Scribble($indentation);
    foreach ($col in $selection) {
      $underline = [string]::new($Options.Chrome.Underline, $MetaData[$col].Max);
      $Scribbler.Scribble("$($underlineSnippet)$($underline)$($inter)$($resetSnippet)");
    }
    $Scribbler.Scribble($lnSnippet);

    # Display field values
    #
    [int]$counter = 1;
    $Table.GetEnumerator() | Sort-Object Name | ForEach-Object { # Name here should be custom ID field which should probably default to 'ID'
      $Scribbler.Scribble($indentation);

      foreach ($col in $selection) {
        if (-not($Render.InvokeReturnAsIs(
          $col, $_.Value.$col, $_.Value, $Options, $Scribbler, $counter))
        ) {
          $Scribbler.Scribble("$($resetSnippet)$($_.Value.$col)");
        }
        $Scribbler.Scribble($inter);
      }

      $Scribbler.Scribble($lnSnippet);
      $counter++;
    }
  }
}

function Show-Header {
  <#
  .NAME
    Show-Header
 
  .SYNOPSIS
    Function to display header as part of an iteration batch.
 
  .DESCRIPTION
    Behaviour can be customised by the following entries in the Exchange:
  * 'LOOPZ.SCRIBBLER' (mandatory): the Krayola Scribbler writer object.
  * 'LOOPZ.HEADER-BLOCK.MESSAGE': The custom message to be displayed as
  part of the header.
  * 'LOOPZ.HEADER.PROPERTIES': A Krayon [line] instance contain a collection
  of Krayola [couplet]s. When present, the header displayed will be a static
  line, the collection of these properties then another static line.
  * 'LOOPZ.HEADER-BLOCK.LINE': The static line text. The length of this line controls
  how everything else is aligned (ie the flex part and the message if present).
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Exchange
    The exchange hashtable object.
 
  #>

  param(
    [Parameter()]
    [hashtable]$Exchange
  )
  [Scribbler]$scribbler = $Exchange['LOOPZ.SCRIBBLER'];
  if (-not($scribbler)) {
    throw [System.Management.Automation.MethodInvocationException]::new(
      "Show-Header: Scribbler missing from Exchange under key 'LOOPZ.SCRIBBLER'");
  }

  [string]$resetSnippet = $scribbler.Snippets(@('Reset'));
  [string]$lnSnippet = $scribbler.Snippets(@('Ln'));
  [string]$metaSnippet = $scribbler.WithArgSnippet('ThemeColour', 'meta');

  $scribbler.Scribble("$($resetSnippet)");

  [string]$message = $Exchange.ContainsKey(
    'LOOPZ.HEADER-BLOCK.MESSAGE') ? $Exchange['LOOPZ.HEADER-BLOCK.MESSAGE'] : [string]::Empty;

  # get the properties from Exchange ('LOOPZ.HEADER.PROPERTIES')
  # properties should not be a line, because line implies all these properties are
  # written on the same line. Rather it is better described as array of Krayola pairs,
  # which is does not share the same semantics as line. However, since line is just a
  # collection of pairs, the client can use the line abstraction, but not the line
  # method on the writer, unless they want it to actually represent a line.
  #
  [line]$properties = $Exchange.ContainsKey(
    'LOOPZ.HEADER.PROPERTIES') ? $Exchange['LOOPZ.HEADER.PROPERTIES'] : [line]::new();

  if ($properties.Line.Length -gt 0) {
    # First line
    #
    [string]$line = $Exchange.ContainsKey('LOOPZ.HEADER-BLOCK.LINE') `
      ? $Exchange['LOOPZ.HEADER-BLOCK.LINE'] : ([string]::new('_', 80));

    [string]$structuredLine = $metaSnippet + $line;
    $scribbler.Scribble("$($structuredLine)$($lnSnippet)");

    # Inner detail
    #
    if (-not([string]::IsNullOrEmpty($message))) {
      [string]$messageSnippet = $scribbler.WithArgSnippet('Message', $message);
      $scribbler.Scribble("$($messageSnippet)");
    }

    [string]$structuredProps = ($properties.Line | ForEach-Object {
        "$($_.Key),$($_.Value),$($_.Affirm)"
      }) -join ';'

    [string]$lineSnippet = $scribbler.WithArgSnippet(
      'Line', $structuredProps
    )
    $scribbler.Scribble("$($lineSnippet)");
          
    # Second line
    #
    $scribbler.Scribble("$($structuredLine)$($lnSnippet)");
  }
  else {
    # Alternative line
    #
    [string]$lineKey = 'LOOPZ.HEADER-BLOCK.LINE';
    [string]$crumbKey = 'LOOPZ.HEADER-BLOCK.CRUMB-SIGNAL';
    [string]$messageKey = 'LOOPZ.HEADER-BLOCK.MESSAGE';

    [string]$structuredLine = Format-StructuredLine -Exchange $exchange `
      -LineKey $LineKey -CrumbKey $CrumbKey -MessageKey $messageKey -Truncate;

    $scribbler.Scribble("$($structuredLine)");
  }
}

function Show-Summary {
  <#
  .NAME
    Show-Header
 
  .SYNOPSIS
    Function to display summary as part of an iteration batch.
 
  .DESCRIPTION
    Behaviour can be customised by the following entries in the Exchange:
  * 'LOOPZ.SCRIBBLER' (mandatory): the Krayola Scribbler writer object.
  * 'LOOPZ.SUMMARY-BLOCK.MESSAGE': The custom message to be displayed as
  part of the summary.
  * 'LOOPZ.SUMMARY.PROPERTIES': A Krayon [line] instance contain a collection
  of Krayola [couplet]s. The first line of summary properties shows the values of
  $Count, $Skipped and $Triggered. The properties, if present are appended to this line.
  * 'LOOPZ.SUMMARY-BLOCK.LINE': The static line text. The length of this line controls
  how everything else is aligned (ie the flex part and the message if present).
  * 'LOOPZ.SUMMARY-BLOCK.WIDE-ITEMS': The collection (an array of Krayola [lines]s)
  containing 'wide' items and therefore should be on their own separate line.
  * 'LOOPZ.SUMMARY-BLOCK.GROUP-WIDE-ITEMS': Perhaps the wide items are not so wide after
  all, so if this entry is set (a boolean value), the all wide items appear on their
  own line.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Count
    The number items processed, this is the number of items in the pipeline which match
  the $Pattern specified and therefore are allocated an index.
 
  .PARAMETER Errors
    The number of errors that occurred during the batch.
 
  .PARAMETER Exchange
    The exchange hashtable object.
 
  .PARAMETER Skipped
    The number of pipeline items skipped. An item is skipped for the following reasons:
  * Item name does not match the $Include expression
  * Item name satisfies the $Exclude expression. ($Exclude overrides $Include)
  * Iteration is terminated early by the invoked function/script-block returning a
  PSCustomObject with a Break property set to $true.
  * FileSystem item is not of the request type. Eg, if File is specified, then all
  directory items will be skipped.
  * An item fails to satisfy the $Condition predicate.
  * Number of items processed breaches Top.
 
  .PARAMETER Triggered
    Indicates whether any of the processed pipeline items were actioned in a modifying
  batch; ie if no items were mutated, then Triggered would be $false.
 
  #>

  param(
    [Parameter()]
    [int]$Count,

    [Parameter()]
    [int]$Skipped,

    [Parameter()]
    [int]$Errors,

    [Parameter()]
    [boolean]$Triggered,

    [Parameter()]
    [hashtable]$Exchange = @{}
  )

  [Scribbler]$scribbler = $Exchange['LOOPZ.SCRIBBLER'];
  if (-not($scribbler)) {
    throw [System.Management.Automation.MethodInvocationException]::new(
      "Show-Summary: Scribbler missing from Exchange under key 'LOOPZ.SCRIBBLER'");
  }

  [string]$resetSnippet = $scribbler.Snippets(@('Reset'));
  [string]$lnSnippet = $scribbler.Snippets(@('Ln'));
  [string]$metaSnippet = $scribbler.WithArgSnippet('ThemeColour', 'meta');

  $scribbler.Scribble("$($resetSnippet)");

  # First line
  #
  if ($Exchange.ContainsKey('LOOPZ.SUMMARY-BLOCK.LINE')) {
    [string]$line = $Exchange['LOOPZ.SUMMARY-BLOCK.LINE'];
    [string]$structuredBorderLine = $metaSnippet + $line;

    $scribbler.Scribble("$($structuredBorderLine)$($lnSnippet)");
  }
  else {
    $structuredBorderLine = [string]::Empty;
  }

  # Inner detail
  #

  [string]$message = $Exchange.ContainsKey('LOOPZ.SUMMARY-BLOCK.MESSAGE') `
    ? $Exchange['LOOPZ.SUMMARY-BLOCK.MESSAGE'] : 'Summary';

  [string]$structuredPropsWithMessage = $(
    "$message;Count,$Count;Skipped,$Skipped;Errors,$Errors;Triggered,$Triggered"
  );

  [string]$structuredPropsWithMessage = if ($Triggered -and `
      $Exchange.ContainsKey('LOOPZ.FOREACH.TRIGGER-COUNT')) {

    [int]$triggerCount = $Exchange['LOOPZ.FOREACH.TRIGGER-COUNT'];
    $(
      "$message;Count,$Count;Skipped,$Skipped;Errors,$Errors;Triggered,$triggerCount"
    );
  }
  else {
    $(
      "$message;Count,$Count;Skipped,$Skipped;Errors,$Errors;Triggered,$Triggered"
    );
  }

  [string]$lineSnippet = $scribbler.WithArgSnippet(
    'Line', $structuredPropsWithMessage
  )
  $scribbler.Scribble("$($lineSnippet)");

  [string]$blank = [string]::new(' ', $message.Length);

  # Custom properties
  #
  [line]$summaryProperties = $Exchange.ContainsKey(
    'LOOPZ.SUMMARY.PROPERTIES') ? $Exchange['LOOPZ.SUMMARY.PROPERTIES'] : [line]::new(@());

  if ($summaryProperties.Line.Length -gt 0) {
    $scribbler.Line($blank, $summaryProperties).End();
  }

  # Wide items
  #
  if ($Exchange.ContainsKey('LOOPZ.SUMMARY-BLOCK.WIDE-ITEMS')) {
    [line]$wideItems = $Exchange['LOOPZ.SUMMARY-BLOCK.WIDE-ITEMS'];

    [boolean]$group = ($Exchange.ContainsKey('LOOPZ.SUMMARY-BLOCK.GROUP-WIDE-ITEMS') -and
      $Exchange['LOOPZ.SUMMARY-BLOCK.GROUP-WIDE-ITEMS']);

    if ($group) {
      $scribbler.Line($blank, $wideItems).End();
    }
    else {
      foreach ($couplet in $wideItems.Line) {
        [line]$syntheticLine = New-Line($couplet);

        $scribbler.Line($blank, $syntheticLine).End();
      }
    }
  }

  # Second line
  #
  if (-not([string]::IsNullOrEmpty($structuredBorderLine))) {
    $scribbler.Scribble("$($structuredBorderLine)$($lnSnippet)");
  }
}
function Write-HostFeItemDecorator {
  <#
  .NAME
    Write-HostFeItemDecorator
 
  .SYNOPSIS
    Wraps a function or script-block as a decorator writing appropriate user interface
    info to the host for each entry in the pipeline.
 
  .DESCRIPTION
      The script-block/function (invokee) being decorated may or may not Support ShouldProcess. If it does,
    then the client should add 'WHAT-IF' to the pass through, set to the current
    value of WhatIf; or more accurately the existence of 'WhatIf' in PSBoundParameters. Or another
    way of putting it is, the presence of WHAT-IF indicates SupportsShouldProcess, and the value of
    'WHAT-IF' dictates the value of WhatIf. This way, we only need a single
    value in the Exchange, rather than having to represent SupportShouldProcess explicitly with
    another value.
      The Exchange must contain either a 'LOOPZ.WH-FOREACH-DECORATOR.FUNCTION-NAME' entry meaning
    a named function is being decorated or 'LOOPZ.WH-FOREACH-DECORATOR.BLOCK' meaning a script
    block is being decorated, but not both.
      By default, Write-HostFeItemDecorator will display an item no for each object in the pipeline
    and a property representing the Product. The Product is a property that the invokee can set on the
    PSCustomObject it returns. However, additional properties can be displayed. This can be achieved by
    the invokee populating another property Pairs, which is an array of string based key/value pairs. All
    properties found in Pairs will be written out by Write-HostFeItemDecorator.
      By default, to render the value displayed (ie the 'Product' property item on the PSCustomObject
    returned by the invokee), ToString() is called. However, the 'Product' property may not have a
    ToString() method, in this case (you will see an error indicating ToString method not being
    available), the user should provide a custom script-block to determine how the value is
    constructed. This can be done by assigning a custom script-block to the
    'LOOPZ.WH-FOREACH-DECORATOR.GET-RESULT' entry in Exchange. eg:
 
      [scriptblock]$customGetResult = {
        param($result)
        $result.SomeCustomPropertyOfRelevanceThatIsAString;
      }
      $Exchange['LOOPZ.WH-FOREACH-DECORATOR.GET-RESULT'] = $customGetResult;
      ...
 
      Note also, the user can provide a custom 'GET-RESULT' in order to control what is displayed
    by Write-HostFeItemDecorator.
 
      This function is designed to be used with Invoke-ForeachFsItem and as such, it's signature
    needs to match that required by Invoke-ForeachFsItem. Any additional parameters can be
    passed in via the Exchange.
      The rationale behind Write-HostFeItemDecorator is to maintain separation of concerns
    that allows development of functions that could be used with Invoke-ForeachFsItem which do
    not contain any UI related code. This strategy also helps for the development of different
    commands that produce output to the terminal in a consistent manner.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Exchange
    A hash table containing miscellaneous information gathered internally
    throughout the iteration batch. This can be of use to the user, because it is the way
    the user can perform bi-directional communication between the invoked custom script block
    and client side logic.
 
  .PARAMETER Index
    The 0 based index representing current item in the pipeline.
 
  .PARAMETER Trigger
      A boolean value, useful for state changing idempotent operations. At the end
    of the batch, the state of the trigger indicates whether any of the items were actioned.
    When the script block is invoked, the trigger should indicate if the trigger was pulled for
    any of the items so far processed in the batch. This is the responsibility of the
    client's block implementation.
 
  .PARAMETER Underscore
    The current pipeline object.
 
  .RETURNS
    The result of invoking the decorated script-block.
 
  .EXAMPLE 1
 
  function Test-FN {
    param(
      [System.IO.DirectoryInfo]$Underscore,
      [int]$Index,
      [hashtable]$Exchange,
      [boolean]$Trigger,
    )
 
    $format = $Exchange['CLIENT.FORMAT'];
    @{ Product = $format -f $Underscore.Name, $Underscore.Exists }
    ...
  }
 
  [Systems.Collection.Hashtable]$exchange = @{
    'LOOPZ.WH-FOREACH-DECORATOR.FUNCTION-NAME' = 'Test-FN';
    'CLIENT.FORMAT' = '=== [{0}] -- [{1}] ==='
  }
 
  Get-ChildItem ... | Invoke-ForeachFsItem -Path <path> -Exchange $exchange
    -Functee 'Write-HostFeItemDecorator'
 
    So, Test-FN is not concerned about writing any output to the console, it simply does
  what it does silently and Write-HostFeItemDecorator handles generation of output. It
  invokes the function defined in 'LOOPZ.WH-FOREACH-DECORATOR.FUNCTION-NAME' and generates
  corresponding output. It happens to use the console colouring facility provided by a
  a dependency Elizium.Krayola to create colourful output in a predefined format via the
  Krayola Theme.
 
  Note, Write-HostFeItemDecorator does not forward additional parameters to the decorated
  function (Test-FN), but this can be circumvented via the Exchange as illustrated by
  the 'CLIENT.FORMAT' parameter in this example.
 
  #>


  [OutputType([PSCustomObject])]
  [CmdletBinding()]
  [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "")]
  [Alias('wife', 'Decorate-Foreach')]
  param (
    [Parameter(
      Mandatory = $true
    )]
    $Underscore,

    [Parameter(
      Mandatory = $true
    )]
    [int]$Index,

    [Parameter(
      Mandatory = $true
    )]
    [ValidateScript( {
        return ($_.ContainsKey('LOOPZ.WH-FOREACH-DECORATOR.FUNCTION-NAME') -xor
          $_.ContainsKey('LOOPZ.WH-FOREACH-DECORATOR.BLOCK'))
      })]
    [hashtable]
    $Exchange,

    [Parameter()]
    [boolean]$Trigger
  )
  [Scribbler]$scribbler = $Exchange['LOOPZ.SCRIBBLER'];
  [scriptblock]$defaultGetResult = {
    param($result)
    $result.ToString();
  }

  [scriptblock]$decorator = {
    param ($_underscore, $_index, $_exchange, $_trigger)

    if ($_exchange.Contains('LOOPZ.WH-FOREACH-DECORATOR.FUNCTION-NAME')) {
      [string]$functee = $_exchange['LOOPZ.WH-FOREACH-DECORATOR.FUNCTION-NAME'];

      [hashtable]$parameters = @{
        'Underscore' = $_underscore;
        'Index'      = $_index;
        'Exchange'   = $_exchange;
        'Trigger'    = $_trigger;
      }
      if ($_exchange.Contains('WHAT-IF')) {
        $parameters['WhatIf'] = $_exchange['WHAT-IF'];
      }

      return & $functee @parameters;
    }
    elseif ($_exchange.Contains('LOOPZ.WH-FOREACH-DECORATOR.BLOCK')) {
      [scriptblock]$block = $_exchange['LOOPZ.WH-FOREACH-DECORATOR.BLOCK'];

      return $block.InvokeReturnAsIs($_underscore, $_index, $_exchange, $_trigger);
    }
  }

  $invokeResult = $decorator.InvokeReturnAsIs($Underscore, $Index, $Exchange, $Trigger);

  [string]$message = $Exchange['LOOPZ.WH-FOREACH-DECORATOR.MESSAGE'];
  [string]$productValue = [string]::Empty;
  [boolean]$ifTriggered = $Exchange.ContainsKey('LOOPZ.WH-FOREACH-DECORATOR.IF-TRIGGERED');
  [boolean]$resultIsTriggered = $invokeResult.psobject.properties.match('Trigger') -and $invokeResult.Trigger;

  # Suppress the write if client has set IF-TRIGGERED and the result is not triggered.
  # This makes re-runs of a state changing operation less verbose if that's required.
  #
  if (-not($ifTriggered) -or ($resultIsTriggered)) {
    $getResult = $Exchange.Contains('LOOPZ.WH-FOREACH-DECORATOR.GET-RESULT') `
      ? $Exchange['LOOPZ.WH-FOREACH-DECORATOR.GET-RESULT'] : $defaultGetResult;

    [line]$themedPairs = $( New-Line( $(New-Pair('No', $("{0,3}" -f ($Index + 1)))) ) );

    # Get Product if it exists
    #
    [string]$productLabel = [string]::Empty;
    if ($invokeResult -and $invokeResult.psobject.properties.match('Product') -and $invokeResult.Product) {
      [boolean]$affirm = $invokeResult.psobject.properties.match('Affirm') -and $invokeResult.Affirm;
      $productValue = $getResult.InvokeReturnAsIs($invokeResult.Product);
      $productLabel = $Exchange.ContainsKey('LOOPZ.WH-FOREACH-DECORATOR.PRODUCT-LABEL') `
        ? $Exchange['LOOPZ.WH-FOREACH-DECORATOR.PRODUCT-LABEL'] : 'Product';

      if (-not([string]::IsNullOrWhiteSpace($productLabel))) {
        $themedPairs.append($(New-Pair(@($productLabel, $productValue, $affirm))));
      }
    }

    # Get Key/Value Pairs
    #
    if ($invokeResult -and $invokeResult.psobject.properties.match('Pairs') -and
      $invokeResult.Pairs -and ($invokeResult.Pairs -is [line]) -and ($invokeResult.Pairs.Line.Count -gt 0)) {
      $themedPairs.append($invokeResult.Pairs);
    }

    # Write the primary line
    #
    if (-not([string]::IsNullOrEmpty($message))) {
      [string]$messageSnippet = $scribbler.WithArgSnippet('Message', $message);
      $scribbler.Scribble("$($messageSnippet)");
    }
    $scribbler.Line($themedPairs).End();

    [int]$indent = $($Exchange.ContainsKey('LOOPZ.WH-FOREACH-DECORATOR.INDENT') `
        ? $Exchange['LOOPZ.WH-FOREACH-DECORATOR.INDENT'] : 3);
    [string]$blank = [string]::new(' ', $indent);

    [System.Collections.Generic.List[line]]$additionalLines = @();

    if ($invokeResult -and $invokeResult.psobject.properties.match('Lines') -and $invokeResult.Lines) {
      $invokeResult.Lines.foreach( { $additionalLines.Add($_) });
    }

    foreach ($line in $additionalLines) {
      $scribbler.NakedLine($blank, $line).End();
    }
  }

  return $invokeResult;
} # Write-HostFeItemDecorator

function Edit-RemoveSingleSubString {
  <#
.NAME
  edit-RemoveSingleSubString
 
.SYNOPSIS
  Removes a sub-string from the target string provided.
 
.DESCRIPTION
  Either the first or the last occurrence of a single substring can be removed
  depending on whether the Last flag has been set.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
.PARAMETER Last
  Flag to indicate whether the last occurrence of a sub string is to be removed from the
  Target.
 
.PARAMETER Subtract
  The sub string to subtract from the Target.
 
.PARAMETER Target
  The string from which the subtraction is to occur.
 
.PARAMETER Insensitive
  Flag to indicate if the search is case sensitive or not. By default, search is case
  sensitive.
 
.EXAMPLE 1
  $result = edit-RemoveSingleSubString -Target "Twilight and Willow's excellent adventure" -Subtract "excellent ";
 
  Returns "Twilight and Willow's adventure"
#>

  [CmdletBinding(DefaultParameterSetName = 'Single')]
  [OutputType([string])]
  param
  (
    [Parameter(ParameterSetName = 'Single')]
    [String]$Target,

    [Parameter(ParameterSetName = 'Single')]
    [String]$Subtract,

    [Parameter(ParameterSetName = 'Single')]
    [switch]$Insensitive,

    [Parameter(ParameterSetName = 'Single')]
    [Parameter(ParameterSetName = 'LastOnly')]
    [switch]$Last
  )

  [StringComparison]$comparison = $Insensitive.ToBool() ? `
    [StringComparison]::OrdinalIgnoreCase : [StringComparison]::Ordinal;

  $result = $Target;

  # https://docs.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings
  #
  if (($Subtract.Length -gt 0) -and ($Target.Contains($Subtract, $comparison))) {
    $slen = $Subtract.Length;

    $foundAt = $Last.ToBool() ? $Target.LastIndexOf($Subtract, $comparison) : `
      $Target.IndexOf($Subtract, $comparison);

    if ($foundAt -eq 0) {
      $result = $Target.Substring($slen);
    }
    elseif ($foundAt -gt 0) {
      $result = $Target.Substring(0, $foundAt);
      $result += $Target.Substring($foundAt + $slen);
    }
  }

  $result;
}

function Get-FieldMetaData {
  <#
  .NAME
    Get-FieldMetaData
 
  .SYNOPSIS
    Derives the meta data from the table data provided.
 
  .DESCRIPTION
    The source table data is just an array of PSCustomObjects where each object
  represents a row in the table. The meta data is required to format the table
  cells correctly so that each cell is properly aligned.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Data
    Hashtable containing the table data.
  #>

  param(
    [Parameter()]
    [ValidateScript( { $_ -and $_.Count -gt 0 })]
    [PSCustomObject[]]$Data
  )
  [hashtable]$fieldMetaData = @{}

  # Just look at the first row, so we can see each field
  #
  foreach ($field in $Data[0].psobject.properties.name) {

    try { 
      $fieldMetaData[$field] = [PSCustomObject]@{
        FieldName = $field;
        # !array compound statement: => .$field
        # Note, we also add the field name to the collection, because the field name
        # might be larger than any of the field values
        #
        Max       = Get-LargestLength $($Data.$field + $field);
        Type      = $Data[0].$field.GetType();
      }
    }
    catch {
      Write-Debug "Get-FieldMetaData, ERR: (field: '$field')";
      Write-Debug "Get-FieldMetaData, ERR: (field length: '$($field.Length)')";
      Write-Debug "Get-FieldMetaData, ERR: (fieldMetaData defined?: $($null -ne $fieldMetaData))";
      Write-Debug "Get-FieldMetaData, ERR: (type: '$($field.GetType())')";
      Write-Debug "Get-FieldMetaData, ERR: ($($_.Exception.Message))";
      Write-Debug "..."
      # TODO: find out why this is happening
      # Strange error sometimes occurs with Get-LargestLength on boolean fields
      #
      $fieldMetaData[$field] = [PSCustomObject]@{
        FieldName = $field;
        Max       = [Math]::max($field.Length, "false".Length);
        Type      = $field.GetType();
      }
    }
  }

  return $fieldMetaData;
}

function Get-InverseSubString {
  <#
  .NAME
    Get-InverseSubString
 
  .SYNOPSIS
    Performs the opposite of [string]::Substring.
 
  .DESCRIPTION
    Returns the remainder of that part of the substring denoted by the $StartIndex
  $Length.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Length
    The number of characters in the sub-string.
 
  .PARAMETER Marker
    A character used to mark the position of the sub-string. If the client specifies
  a marker, then this marker is inserted between the head and the tail.
 
  .PARAMETER Source
    The source string
 
  .PARAMETER Split
    When getting the inverse sub-string there are two elements that are returned,
  the head (prior to sub-string) and the tail, what comes after the sub-string.
    This switch indicates whether the function returns the head and tail as separate
  entities in an array, or should simply return the tail appended to the head.
 
  .PARAMETER StartIndex
    The index of sub-string.
 
  #>

  param(
    [Parameter(Position = 0, Mandatory)]
    [string]$Source,

    [Parameter()]
    [ValidateScript( { $_ -lt $Source.Length })]
    [int]$StartIndex = 0,

    [Parameter()]
    [ValidateScript( { $_ -le ($Source.Length - $StartIndex ) })]
    [int]$Length = 0,

    [Parameter()]
    [switch]$Split,

    [Parameter()]
    [char]$Marker
  )

  $result = if ($StartIndex -eq 0) {
    $PSBoundParameters.ContainsKey('Marker') `
      ? $($Marker + $Source.SubString($Length)) : $Source.SubString($Length);
  }
  else {
    [string]$head = $Source.SubString(0, $StartIndex);

    if ($PSBoundParameters.ContainsKey('Marker')) {
      $head += $Marker;
    }

    [string]$tail = $Source.SubString($StartIndex + $Length);
    ($Split.ToBool()) ? ($head, $tail) : ($head + $tail);
  }
  $result;
}

function Get-IsLocked {
  <#
  .NAME
    Get-IsLocked
 
  .SYNOPSIS
    Utility function to determine whether the environment variable specified
  denotes that it is set to $true to indicate the associated function is in a locked
  state.
 
  .DESCRIPTION
    Returns a boolean indicating the 'locked' status of the associated functionality.
  Eg, for the Rename-Many command, a user can only use it for real when it has been
  unlocked by setting it's associated environment variable 'LOOPZ_REMY_LOCKED' to $false.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Variable
    The environment variable to check.
 
  #>

  [OutputType([boolean])]
  param(
   [Parameter(Mandatory)]
   [string]$Variable
  )

  [string]$lockedEnv = Get-EnvironmentVariable $Variable;
  [boolean]$locked = ([string]::IsNullOrEmpty($lockedEnv) -or
    (-not([string]::IsNullOrEmpty($lockedEnv)) -and
      ($lockedEnv -eq [boolean]::TrueString)));

  return $locked;
}

function Get-LargestLength {
  <#
  .NAME
    Get-LargestLength
 
  .SYNOPSIS
    Get the size of the largest string item in the collection.
 
  .DESCRIPTION
    Get the size of the largest string item in the collection.
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Data
    Hashtable containing the table data.
 
  .PARAMETER items
    The source collection to get largest length of.
  #>

  param(
    [string[]]$items
  )
  [int]$largest = 0;
  if ($items -and $items.Count -gt 0) {
    foreach ($i in $items) {
      if (-not([string]::IsNullOrEmpty($i)) -and $($i.Length -gt $largest)) {
        $largest = $i.Length;
      }
    }
  }

  return $largest;
}

function Get-PartitionedPcoHash {
  <#
  .NAME
    Get-PartitionedPcoHash
 
  .SYNOPSIS
    Partitions a hash of PSCustomObject (Pco)s by a specified field name.
 
  .DESCRIPTION
    Given a hashtable whose values are PSCustomObjects, will return a hashtable of
  hashtables, keyed by the field specified. This effectively re-groups the hashtable
  entries based on a custom field. The first level hash in the result is keyed,
  by the field specified. The second level has is the original hash key. So
  given the original hash [ORIGINAL-KEY]=>[PSCustomObject], after partitioning,
  the same PSCustomObject can be accessed, via 2 steps $outputHash[$Field][ORIGINAL-KEY].
 
  .LINK
    https://eliziumnet.github.io/Loopz/
 
  .PARAMETER Field
    The name of the field to partition by
 
  .PARAMETER Hash
    The input hashtable to partition
  #>

  param(
    [Parameter(Mandatory)]
    [hashtable]$Hash,

    [Parameter(Mandatory)]
    [string]$Field
  )

  [Hashtable]$partitioned = @{}

  $Hash.GetEnumerator() | ForEach-Object {

    if ($_.Value -is [PSCustomObject]) {
      [string]$partitionKey = (($_.Value.$Field) -is [string]) ? ($_.Value.$Field).Trim() : ($_.Value.$Field);

      if (-not([string]::IsNullOrEmpty($partitionKey))) {
        [hashtable]$partition = if ($partitioned.ContainsKey($partitionKey)) {
          $partitioned[$partitionKey];
        }
        else {
          @{}
        }
        $partition[$_.Key] = $_.Value;
        $partitioned[$partitionKey] = $partition;
      }
      else {
        Write-Debug "WARNING: Get-PartitionedPcoHash field: '$Field' not present on object for key '$($_.Key)'";
      }
    }
    else {
      throw [System.Management.Automation.MethodInvocationE