#!/bin/bash

# Define a function named 'expanse'.
expanse() {
        i=1
        var=".*$2"
        # Loop to concatenate a regex pattern for each character repetition.
        until [[ $i = "$1" ]]; do
                var="$var.*$2"
                ((i++))
        done
        # Echo the generated grep command that searches for words containing the character pattern.
        echo " grep '${var}.*' "
}

# Main loop to process each argument passed to the script.
for i in "$@"; do
        n=1
        init="[$1]"  # Initialize a regex pattern to match the first character of the input word.
        until [[ $n = "${#1}" ]]; do
                init="$init[$1]"  # Build a regex pattern to match all characters in the word, respecting order.
                ((n++))
        done

        echo "$1:"  # Print the current word being processed.
        {
            # Use grep to find exact matches of the input word in /usr/share/dict/words.
            eval "grep '^$init$' /usr/share/dict/words |\
                # Process each unique character in the word with its frequency.
                $(while read -ru 9 line; do
                        expanse ${line}  # Call the 'expanse' function to generate a grep command for each character.
                done 9< <(echo "$1" | grep -o . | sort | uniq -c) |\
                # Concatenate the generated grep commands into a single pipeline.
                tr '\n' '|' | sed 's|.$||')" || echo -no match-  # Handle the case where no match is found.
        } | sed 's|^|  |'  # Indent the results for readability.
        echo --  # Print a separator.

        shift  # Shift the positional parameters to process the next argument.
done | sed '$d'  # Remove the last separator to clean up the output.