#! /bin/sh

#================================================================
# estspellen
# help estsearch.cgi to show alternative words
#================================================================


# set variables
LANG=C ; export LANG
LC_ALL=C ; export LC_ALL


# check input
if [ -z "$ESTPHRASE" ]
then
  exit 0
elif printf '%s\n' "$ESTPHRASE" | grep '[^a-zA-Z0-9_ -]' > /dev/null
then
  exit 0
fi


# output alternative words
printf '%s\n' "$ESTPHRASE" |
tr -s ' ' | tr '\t' ' ' | tr ' ' '\n' |
while read word
do
  printf '%s\t' "$word"
  printf '%s' "$word" | aspell -a | egrep -v '(^@)|(^$)' | head -n 1
done |
awk -F '\t' -v query="$QUERY_STRING" '
{
  if(match($2, /^&/)){
    sub(/[^:]*: */, "", $2)
    gsub(/,/, "", $2)
    sub(/ .*/, "", $2)
    word[FNR] = tolower($2)
  } else if(match($2, /^\\*/)){
    word[FNR] = tolower($1)
  }
}
END {
  printf("<div style=\"margin: 1em 1em 0em 1em;\">Alternation: ")
  printf("<a href=\"?phrase=")
  for(i = 1; i <= FNR; i++){
    if(i > 1) printf("%20");
    printf("%s", word[i])
  }
  printf("&amp;%s\">", query)
  for(i = 1; i <= FNR; i++){
    if(i > 1) printf(" ");
    printf("%s", word[i])
  }
  printf("</a>")
  printf("</div>\n")
}
'


# exit normally
exit 0



# END OF FILE
