#!/usr/bin/perl -w

#Generates Aspell affix rules for Portuguese from Ispell affix rules format
#Rui Vilela, 2007

use strict;
use locale;

my ($pri, $seg, @ter, @qua, @qui, $i, $tmp, $tmp2, $flg);

print "SET ISO8859-1\n";
#next line is generated by conta.pl (stream of letters sorted by frequency)
print "TRY aerisontcdmlupvgbfzáhçqjíxãóéêâúõACMPSBTELGRIFVDkHJONôywUKXZWQÁYÍÉàÓèÂÚ\n\n";

sub printRegra {
    printf "\n%s %s %s %d\n",
      $pri, $seg, $flg=~/[\*\+]/ ? 'Y' : 'N', $#ter+1;

    for ( $i = 0; $i < @qui; $i++) {
	printf "%s %s   %-15s %-15s %-15s\n",
          $pri, $seg, lc($ter[$i]), lc($qua[$i]), lc($qui[$i]);
    }
    @ter=();  #clean buffer from previous flag
    @qua=();
    @qui=();
}

while(<>){
    next if /^(\s+$|\#|wordchars|allaffixes|defstringtype|boundary)/;
    s/\#.*//;   #Strip Comments
    next unless /\S/;

    if (/^prefixes$/) {
        $pri = 'PFX';
        next;
    }
    if (/^suffixes$/){
	printRegra();
	$pri='SFX';
	undef $seg;
	next;
    }
    if (/^flag ([\*\+]?)(\w)/) {    ##Flag data
	($tmp,$tmp2)=($2,$1);
	printRegra() if defined($seg);
	$seg=$tmp;
	$flg=$tmp2;
	next;
    }

    s/\\-/-/g;
    /^ (.+) \s* > \s+ (?:([\-\w]+) ,)? ([\-\w]+) \s* ;  /x or die "Strange rule not matching";   ##Takeoff data
    push @qui, $1;
    $tmp2=$2;
    $tmp=$3;
    if (!length($tmp2)) {
	push @ter, '0';
	push @qua, $tmp;
    } else {
	push @ter, $tmp2;
	push @qua, $tmp;
    }
    $ter[-1]=~s/\-//;       ##Cleaning
    $qui[-1]=~s/\s//g;
    $qua[-1]=~s/^\-$/0/;
}

printRegra();
