#!/usr/bin/env bash
function parseResults() {
    oIFS=$IFS
    IFS=":"
    declare -a fields=($1)
    export QUERYTERM=$(echo "${fields[0]}"|awk '{print $1}');
    export LISTCOUNT=$(echo "${fields[0]}"|awk '{print $2}');
    export WORDLIST=$(echo "${fields[1]}"|sed 's/^\s*\|\s*$//g');
    IFS=$oIFS
    unset oIFS
}
searchterm=$(zenity --entry --text="Enter search term:" --title="Speller" --width=300 --height=40 2> /dev/null);
if [ -z "${searchterm}" ] | [ "${searchterm}" == " " ]; then
    zenity --info --text="ERROR No search term provided!"\
        --icon-name=error \
        --window-icon="${HOME}/.local/bin/img/xmark.png" 2> /dev/null
    exit 1;
fi
if [[ "${searchterm}" =~ ^[0-9]+$ ]]; then
    zenity --info --text="ERROR only words, please!"\
        --icon-name=error \
        --window-icon="${HOME}/.local/bin/img/xmark.png" 2> /dev/null
    exit 1;
fi
export RESULT=$(echo "$searchterm"|aspell -a|sed "1 d"); # Deletes the header line
export FIXED="${RESULT/& }" # Removes ampersand causing parsing errors.
if [[ "${FIXED}" == *"*"* ]]; then
    zenity --info --text="CORRECT! " \
        --icon-name=info \
        --window-icon="${HOME}/.local/bin/img/check-mark-11-16.png" 2> /dev/null
else
    parseResults "${FIXED}"
    message="There are ${LISTCOUNT} suggested corrections for '${QUERYTERM}': ${WORDLIST}" 
    zenity --info --text="${message}"\
        --icon-name=warning \
        --window-icon="${HOME}/.local/bin/img/caution-48.png" 2> /dev/null
fi