#!/usr/bin/env perl
#
# hc - w3m եݽ
#
# $Id: hc,v 1.1 2005/06/05 14:31:46 ta Exp $

use strict;

my @all;  #  URL и˳Ǽ
my %dup;  # @all γ URL => Ǹ˽иźʣ
my (@re, @limits, @sort);  # ݽ롼ɽĤĿ󤹤뤫ݤ
my %counts;  # ݽ롼 URL ζ => Ĥ URL  @all ź

my $conf = $ENV{'HC'} || "$ENV{'HOME'}/.hc";
open(IN, $conf) || die "$conf: $!\n";
while (<IN>) {
    if (/\s*(-?)(\d+)\s+(\S+)/) {
        push @re, eval 'qr/$3/o';
        push @limits, $2;
        push @sort, $1;
    }
}
close(IN);

# ݽ롼ɤ߹߷
#print "$sort[$_] $limits[$_] $re[$_]\n" foreach (0..$#re);
#exit;

while (my $s = <>) {
    chomp $s;
    push @all, $s;
    undef $all[$dup{$s}] if defined $dup{$s};
    $dup{$s} = $#all;
    foreach my $i (0..$#re) {
        if ($s =~ $re[$i]) {
            if ($limits[$i] == 0) {
                undef $all[$#all];
            } else {
                my $cnt = \@{$counts{defined $1 ? $1 : $&}};
                @$cnt = () if !defined($cnt);
                if (@$cnt < $limits[$i]) {
                    push @$cnt, $#all;
                } elsif ($sort[$i]) {
                    push @$cnt, $#all;
                    @$cnt = sort { $all[$a] cmp $all[$b] } @$cnt;
                    undef $all[shift @$cnt];
                } else {
                    undef $all[shift @$cnt];
                    push @$cnt, $#all;
                }
            }
            last;
        }
    }
}

# ݽ롼ŬѤ
#while (my ($k, $v) = each %counts) {
#    print "$k\n";
#    print "  $all[$_]\n" foreach (@$v);
#}
#exit;

foreach my $i (@all) {
    print "$i\n" if defined $i;
}
