#!/usr/local/bin/perl

# SUFARY module Υѥ饤֥ꥵѥɲ
BEGIN{
    $SUFARY_LIB = "/tmp_mnt/home/tatuo-y/work/sufary/sufary/perl/SUFARY";
    unshift(@INC,
	    $SUFARY_LIB, "$SUFARY_LIB/blib/lib", "$SUFARY_LIB/blib/arch");
}

# 
use SUFARY;

$keyreg = shift;
$fname = shift;
# եΥץ
$x = SUFARY->new($fname);

$keystr = $keyreg;
$keystr =~ s/\\./ /g;
$keystr =~ s/\{[^\}]*\}/ /g;
$keystr =~ s/\[[^\}]*\]/ /g;
$keystr =~ s/[\\+*.?\^\$]/ /g;

@keys = sort {length($b) <=> length($a)} split(' ', $keystr);

if ($#keys < 0) {
    open(D, $fname);
    while(<D>) {
	print if (/$keyreg/);
    }
    exit;
}

undef %check;
# ܤΥ
$key = shift @keys;
$nx = $x->search($key);
exit if $nx == 0;
if ($nx > 2000) {
    for ($i = 0; $i < $nx; $i++) {
	$str = $x->line($i);
	if ($str =~ /$keyreg/) {print "$str\n";};
    }
    exit;
} else {
    $tmp = $x->get_all_lid();
    foreach $lid (@$tmp) {
	$check{$lid}++;
    }
}
# ܰʹߤΥ
$num = 1;
foreach $key (@keys) {
    $nx = $x->search($key);
    next if ($nx > 2000);
    last if ($nx < 0);
    $tmp = $x->get_all_lid();
    foreach $lid (@$tmp) {
	if (defined $check{$lid}) {
	    if ($check{$lid} < $num) {
		undef $check{$lid};
	    } else {
		$check{$lid}++;
	    }
	}
    }
    $num++;
}
undef @lids;
while (($lid,$val) = each %check) {
    if ($val == $num) {push(@lids,$lid);}
}
foreach $lid (@lids) {
    $str = $x->id2line($lid);
    if ($str =~ /$keyreg/) {
	print "$str\n";
    }
}
# եĤ
$x->close();
