#!/usr/bin/perl -w

#
#  hitlists_red
#  Copyright (C) 2010 by USC/ISI
#  $Id$
#  
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License,
#  version 2, as published by the Free Software Foundation.
#  
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  
#  You should have received a copy of the GNU General Public License along
#  with this program; if not, write to the Free Software Foundation, Inc.,
#  59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
#  
#  
#  This code was originally written by Xun Fan <xunfan@isi.edu>.
#

# 

use strict;
use warnings;
use Digest::MD5 qw(md5_hex);
use Fsdb::IO::Writer;

my $output_stream = new Fsdb::IO::Writer(-fh => \*STDOUT, -fscode => 't', 
					 -cols => [qw(prefix hex_ip score ip)]);
my $current_prefix="";
# the winner in $current_prefix so far
my $best_score = 0;
my $best_hex_ip;
my $best_str_ip;

#compare two md5 substring hashes (legacy, do not change)
sub cmp_ips {
    my ($ip1, $ip2) = @_;
    return (substr(md5_hex($ip1), 0, 6) cmp substr(md5_hex($ip2), 0, 6));
}

sub dump_prefix {
    return 
	if $current_prefix eq "";
    $best_score = -1
	if $best_score == 0;
    $output_stream->write_row($current_prefix, $best_hex_ip, $best_score, $best_str_ip);
}

while (<>) {
    chomp;
    my($hex_prefix, $hex_ip, $str_ip, $hex_history, $score) = split;
    if ($current_prefix ne $hex_prefix) {
	dump_prefix();
	$current_prefix = $hex_prefix;
	$best_score = $score;
	$best_hex_ip = $hex_ip;
	$best_str_ip = $str_ip;
    } else {
	if ($score > $best_score ||
	    ($score == $best_score && 
	     #xxx legacy, not sure why give preference to non .0 only if score==0
	     (($best_score == 0 && substr($best_hex_ip, 6, 2) eq "00") 
	      || cmp_ips($hex_ip, $best_hex_ip) > 0))) {
	    $best_score = $score;
	    $best_hex_ip = $hex_ip;
	    $best_str_ip = $str_ip;
	}
    }
}
dump_prefix();

