#!/usr/bin/perl -w

use strict;
use utf8;
use Encode;

my $opt_text = (@ARGV and $ARGV[0] eq '-t');
shift @ARGV if $opt_text;

binmode(STDIN, ':utf8');
use POSIX qw(LC_CTYPE setlocale);
#binmode(STDOUT, ':utf8');

my $locale = 'bg_BG.UTF-8';

setlocale(LC_CTYPE, $locale);

setlocale(LC_CTYPE) eq $locale
    or die "Unable to set locale to $locale";

use locale;

my $state = 'start';
my $entry = '';

my %dict;

sub output_entry()
{
    my $word;
    $entry =~ s/\.$//;

    if( $entry =~ s/^([^а-я]+)\s(n|adj|v|abbr|attr)\s(?=\d+\.)/($2)\n/i )
    {
        $word = $1;

        $entry =~ s/~/$word/g;
    }
    elsif( $entry =~ s/^([^а-я]+)\s(n|adj|v|abbr|attr)\s/($2)\n/i )
    {
        $word = $1;

        $entry =~ s/~/$word/g;
    }
    elsif( $entry =~ s/([^а-я]+)\s(?=[а-я])//i  )
    {
        $word = $1;

        $entry =~ s/~/$word/g;
    }
    elsif( $entry =~ s/^(.+) = (?=.+$)/вж. / )
    {
        $word = $1;
    }
    else
    {
        die "Can't parse the word out of entry: $entry";
    }

    $entry =~ s/;\s(?=\d+\.\s+)/\n/g;
    $entry =~ s/;\s(n|adj|v|abbr|attr)\s+(?=\d+\.)/\n($1)\n/g;
    $entry =~ s/;\s(n|adj|v|abbr|attr)(?=\s+)/\n($1)/g;
    #$entry =~ s/(?<=\s)1\.(?=\s)//;

    if( $word !~ /^\d/ )
    {
        my $key = lc($word);
        $key =~ s/\W+//g;

        $dict{$key} = "$word\n$entry";
    }

    $entry = '';
}

sub process(@)
{
    my($prev, $curr, $next) = @_;

    while(1) 
    {
        #warn $curr, '--', $state, '--', $next;
        if( $state eq 'start' )
        {
            if( $curr =~ /^------$/ and $prev =~ /^Речник$/ )
            {
                $state = 'wait-dict-data';
            }
            last;
        }

        if( $state eq 'wait-dict-data' )
        {
            last if( $curr eq '' );

            # new letter index
            last if $next eq '=' x length($curr);
            last if $curr eq '=' x length($prev);

            # there are letter indices without the "=" underline
            last if $curr =~ /^[A-Z]$/ and ($next =~ /=/ or $next eq '');

            # Започва с текст на латиница и съдържа кирилица
            if( $next !~ /^=+$/ and $curr =~ /^[a-z0-9]/i and $curr =~ /[a-я]/i )
            {
                $state = 'dict-data';
                $entry = $curr;
                last;
            }

            die "Unrecognized data: '$curr'";
        }

        if( $state eq 'dict-data' )
        {
            if( $curr eq '' )
            {
                output_entry();
                $state = 'wait-dict-data';
            }
            else
            {
                $entry .= ' ' . $curr;
            }

            last;
        }
    };
}

my @window = ('', '', '');
while(<>)
{
    chomp;
    s/^\s+//;

    s/sеrvlet/servlet/g;    # First `e' is in cyrillics

    shift @window;
    push @window, $_;

    process(@window);
}

my @tmp = @window;
while( @window )
{
    shift @tmp;
    shift @window;
    push @tmp, '';

    process(@tmp);
}

foreach(sort( keys %dict ) )
{
    my $out = $dict{$_};

    print "\000" unless $opt_text;

    while( $out ne '' )
    {
        my $encoded_out = Encode::encode('cp1251', $out, Encode::FB_QUIET);

        print $encoded_out;

        $out =~ s/^./?/;
    }

    print "\n\n" if $opt_text;
}

print "\000" unless $opt_text;
