#!/usr/bin/ksh93
# wotd - generates random WOTD (Words of the Day) list from the system
#        dictionary file; provides refresh and/or definition lookups.
#

DICT="/usr/share/dict/words"
HISTFILE="/tmp/wotd$$"
touch $HISTFILE
# make # of suggestions +1:
HISTSIZE=4
set -o emacs

header() {
 printf '\n Welcome to the KornShell Vocabulary Builder! \n'
}

suggestions() {
 WRD="$1"
 set -A SUGGEST ${WRD%%?(s|\'s|y|ly|ed|ing|ness)} ${WRD##?(un|re|non|in)} ${WRD%%?(er|ish|ine|iest)}
 for WRD in {2..0} ;do
   echo "${SUGGEST[$WRD]}" |read -s
 done
}

# need either dict(1) or lynx(1) installed for dictionary lookups:
lookup() {
 WORD="$1"
 while : ;do
   clear
   if [[ "$(which dict)" ]] ;then
     dict "$WORD" |less -ReX
   elif [[ "$(which lynx)" ]] ;then
     WWWdict="http://www.dict.org/bin/Dict?Form=Dict2&Database=*&Query=$WORD"
     TERM=linux lynx -dump -nolist -cookies "$WWWdict" |tail +18 |more
   else
     printf '\n\n sorry, neither dict(1) nor lynx(1) was found - ask your sysadmin to fix it.\n'
     sleep 3 ;return 1
   fi
     printf '\n  . . . . . \n\n'
     read -n1 REPLY?' type "e" to edit word; any other key to continue: '
     printf '\n\n'
     case "${REPLY}" in
       e)  suggestions $WORD
           read -r -s WORD?' revise word - use up|down arrows for suggestions: '
           continue ;;
       *)  return 0 ;;
     esac
 done
}

word() {
 grep -m8000 "^$1[a-z]*[a-z][a-z]$" $DICT |shuf -n1 -
}

makelist() {
 unset allwords
 typeset -A allwords
 for LTR in {a..z} ;do
   allwords[$LTR]="$(word $LTR)"
 done
 export allwords
}

printlist() {
 clear
 header
 printf '\n Words of the Day \n ---------------- \n\n'
 for LTR in {a..z} ;do
   printf ' %s)  %s\n' $LTR ${allwords[$LTR]}
 done
 printf '\n ---------------- \n\n'
}

selectword() {
 read -r -n1 REPLY?' type [a-z] for definitions; R to refresh, Q to quit: '
   printf '\b\n'
   case "${REPLY:-'Q'}" in
     [a-z])  lookup "${allwords[$REPLY]}" ;;
         R)  makelist ;;
       *|Q)  rm $HISTFILE ;exit 0 ;;
   esac
}

main() {
 makelist
 while : ;do
   printlist
   selectword
 done
}

# run
main