#!/usr/local/bin/perl -w
# --------------------------------------------------------------------------------- 
# Author: Dean Stringer (Webteam/ITS/University of Waikato)
#         James Brunskill (Library/University of Waikato) - brunskil@waikato.ac.nz 
# Original Release Date: 17/02/2006
# Last Updated : 05/03/2007
#
# Description/Purpose:
#	uses Text::Aspell to process text using the command-line apsell
#	utility and return spelling corrections to the user.
#
# --------------------------------------------------------------------------------- 
use strict;
use CGI;
use Text::Aspell;

my $q=new CGI;

# grab all the params we're expecting
my $words = $q->param('words') || '';
my @words = split(' ',$words);

# create and setup the Aspell object
my $speller = Text::Aspell->new;
die "" unless $speller;
my $lang = 'en_ALL';

$speller->set_option('home-dir', '/m1/voyager/shared/aspell/');

$speller->set_option('lang',$lang);	# default in our local install at UOW
$speller->set_option('sug-mode','fast');
$speller->set_option('extra-dicts','maoriwords.local');
$speller->set_option('ignore-case','true');

# globals that will contain the misspelt words and suggestions for them
my $spellingOK = 1;
my $outputText = $words;# used for holding the corrected words.


# ---------------------------------------------------------------------------------------
# step thru each word, check its spelling, and produce the text to output for suggestions
# ---------------------------------------------------------------------------------------

WORDS: foreach my $word (@words) {
     next WORDS if ($word =~ /\W/);	# dont want non-word chars or alpha/numerical mixed strings
     next WORDS if ($word =~ /\d/);
     unless ($speller->check( $word )) {
	 
	 my @suggestionResults = $speller->suggest("$word");
	 my $wordReplace = $suggestionResults[0];
	 $outputText =~ s/$word/$wordReplace/xig;

	 $spellingOK = 0;
     }
 }


# ---------------------------------------------------------------------------------------
# we've now got our list of broken words and the suggestions for them, all we need
# to do is output the suggestions
# ---------------------------------------------------------------------------------------


print $q->header();

if($spellingOK == 0)
{
    print $outputText; #The 'corrected' version of the input string
}
else
{
    print "-spellingcorrect-"; #Tell the javascript the words are correctly spelt...
}
