#!/usr/bin/perl

# Generates Hunspell affix rules from jspell affix rules for Portuguese (pt_PT)
# GenerateHunspellAffixFile: Jspell Aff -> Hunspell Aff

# Rui Vilela, 2007

use strict;
use warnings;
use locale;

our ($section, $flag_letter, @ter, @qua, @qui, $i, $flg, @morf);

print header();




while(<>){
    # skip non relevant parts
    next if /^(\s*$|\#|wordchars|defstringtype|allaffixes|boundarychars)/;

    # strip Comments
    s/\#.*$//;

    # cleanup backslashed hifen
    s/\\-/-/g;

    # Automata. Decide current section.
    if (/^prefixes\s*$/) {
        $section = 'PFX';
        next;
    }

    if (/^suffixes\s*$/) {
        printRegra();
        $section='SFX';
        undef $flag_letter;
        next;
    }

    if (/^flag\s+([\*\+])(\w)/) {    #
	my ($tmp, $tmp2) = ($2, $1); # save vars temporarily
	printRegra() if defined($flag_letter);
	$flag_letter = $tmp;
	$flg = $tmp2;
	next;
    }

    # match rule line
    # É S         >   -ÉS,ESES ; "N=p"         # és -> eses   ex. revés,reveses
    # $1 -> termination
    # $2 -> deletion part
    # $3 -> addition part
    # $4 -> Morphology changes
    /^(.+) > \s+ (?:([\-\w]+) ,)? ([\-\w]+) \s* ; \s* " ([^"]+) " /x or die;

    push @qui, $1;
    my ($del_part, $add_part, $morf) = ($2, $3, $4);

    die "Ooops!" unless $section && $section =~ /^(SFX|PFX)$/;

    push @morf, ($section eq 'SFX' ? "+$morf" : "$morf+");

    if (!length($del_part)) {
	push @ter, '0';
	push @qua, $add_part;
    }else{
	push @ter, $del_part;
	push @qua, $add_part;
    }
    $ter[-1]=~s/-//;       ## remove hífen from deletion part
    $qui[-1]=~s/\s//g;     ## remove spaces from termination match
    $qua[-1]=~s/^-$/0/;    ## substitute the empty add by a zero
}

printRegra();


sub printRegra {

    # PFX A Y 20
    # PFX A Del-part Add-part Match-part Morf-part

    printf "\n%s %s %s %d\n",
      $section,
        $flag_letter,
          ($flg=~/[\*\+]/ ? 'Y' : 'N'),
            scalar(@ter); ##number of items at the end

    for ($i = 0; $i < @qui; $i++) {
	printf "%s %s   %-15s %-15s %-15s %s\n",
          $section,
            $flag_letter,
              lc($ter[$i]),
                lc($qua[$i]),
                  lc($qui[$i]),
                    $morf[$i];
    }
    @ter=();
    @qua=();
    @qui=();
    @morf=();
}


sub header {
    # third line is generated by ordenaFreqPrimeiraLetra.pl
    # (stream of letters sorted by the number of ocurrences, although only one run is required...)
    return <<EOH
SET UTF-8
LANG pt_PT
TRY aerisontcdmlupvgbfzáhçqjíxãóéêâúõACMPSBTELGRIFVDkHJONôywUKXZWQÁYÍÉàÓèÂÚ
KEY qwertyuiop|asdfghjkl|zxcvbnm
WORDCHARS -

EOH
# newline above is required
}
