#!/usr/local/bin/perl -w

=head1 NAME

mkdicdb - Juman ե Berkeley DB Ѵ

=head1 SYNOPSIS

mkdicdb [OPTIONS] FILE...

=head1 DESCRIPTION

Juman °Ƥ뼭L<Juman::Dictionary> 黲ȤǤ
Ѵ륹ץȡ

=head1 OPTIONS

=over 4

=item -o [DBFILE]

=item --output [DBFILE]

Ϥ database Υե̾ꤹ롥꤬ά줿ϡ
C<JUMAN.dic.db> ˽Ϥ롥

=item -d

=item --debug

ǥХåϤ롥

=head1 DB FORMAT

ǡ١ηϡʲ̤ꡥ

ġηǤξϡTAB ǶڤƤ롥

     ::= \tɤ\tʻ\tʬ\tѷ\ṭ

ǤϲԤǶڤ졤Фޤɤߤ key Ȥƥϥå˳Ǽ
Ƥ롥

    ɤ => 1\n2\n...\nn
     => 1\n2\n...\nn

=cut

use lib "./lib";
use strict;
use Getopt::Long;
use IO::File;
use Juman::DB_File;
use Juman::Sexp qw/ parse /;

my $DBFILE = "JUMAN.dic.db";
my $DEBUG;

&GetOptions( 'debug|d+'   => \$DEBUG,
	     'output|o=s' => \$DBFILE );

my %HASH;
die "$DBFILE already exists" if -f $DBFILE;
tie( %HASH, 'Juman::DB_File', $DBFILE, &O_CREAT ) or die "Can't create $DBFILE: $!\n";

for my $file ( @ARGV ){
    print STDERR "Reading $file...\n";
    for my $sexp ( &parse( file => $file, debug => $DEBUG ) ){
	&add( $sexp );
    }
}

sub add {
    my( $sexp ) = @_;
    my $hinsi = shift @{$sexp};
    return if $hinsi eq "Ϣ";
    for( @{$sexp} ){
	my( $bunrui, @mrph ) = @{$_};
	if( ref $bunrui eq "ARRAY" ){ # ʬλ꤬ʤ
	    $bunrui = "";
	    @mrph = ( $_ );
	}
	for my $mrph ( @mrph ){
	    my $yomi;
	    my @midasi;
	    my $katuyou = "";
	    my $imi = "";
	    for( @{$mrph} ){
		my( $key, @parameter ) = @{$_};
		if( $key eq "Ф" ){
		    push( @midasi, map( { ref $_ ? $_->[0] : $_ } @parameter ) );
		}
		elsif( $key eq "ɤ" ){
		    $yomi = $parameter[0];
		}
		elsif( $key eq "ѷ" ){
		    $katuyou = $parameter[0];
		}
		elsif( $key eq "̣" ){
		    $imi = $parameter[0];
		}
	    }
	    for my $midasi ( @midasi ){
		my $desc = join( "\t", $midasi, $yomi, $hinsi, $bunrui, $katuyou, $imi );
		for my $key ( ( $midasi eq $yomi ) ? $midasi : ( $midasi, $yomi ) ){
		    print STDERR "ADD: $key => $midasi:$yomi:$hinsi:$bunrui\n" if $DEBUG;
		    if( my $val = $HASH{$key} ){
			if( index( $val, $desc ) < 0 ){
			    $HASH{$key} = $val."\n".$desc;
			}
		    } else {
			$HASH{$key} = $desc;
		    }
		}
	    }
	}
    }
}
