# hash to keep filters in
my %filter;

sub filter_get ($) {
    my ($name) = @_;
    return $filter{$name};
}

sub filter_array_to_regexp ($) {
    my ($array) = @_;
    my @array = @$array;
    return join('|', @array);
}

sub filter_from_arrays ($$\@;\@\@$) {
    # Create a filter using a name, color, and 3 array refs and a string
    # array ref 1: classes (required)
    # array ref 2: instances of class message (optional)
    # array ref 3: instances of any class (optional)
    # string: append to filter (optional)
    
    my ($name, $color, $classes, 
        $msg_inst, $inst, $filter_string) = @_;
    my $filter = sprintf('class ^%s$ ', filter_array_to_regexp($classes)) 
        if @$classes;
    $filter .= ' or ' if $filter && @$msg_inst;
    $filter .= sprintf(' ( class ^MESSAGE$ and instance ^%s ) ',
                       filter_array_to_regexp($msg_inst))
        if @$msg_inst;
    $filter .= ' or ' if $filter && @$inst;
    # includes instance and instance.foo, this keeps substrings from matching
    # also include instance@foo for -c login messages
    $filter .= sprintf('instance ^(%s)([.@][.a-z]*)?$', filter_array_to_regexp($inst)) 
        if @$inst;
    $filter .= " or $filter_string" if $filter_string;
    filter_make($name, $color, "( $filter )");
}

sub filter_make ($$$) {
    my ($name, $color, $filter) = @_;
    my $c = "";
    $c = "-c $color" if $color;
    $filter{$name} = $filter;
    owl::command("filter $name $c $filter");
}

# get the names of all the filters created through filter_make()
sub filter_get_names () {
    return(keys %filter);
}

1;
