#!/usr/bin/perl -w


#
#  old_hitlists_update_with_intermediate_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 Fsdb::IO::Reader;
use Fsdb::IO::Writer;

#my $input_stream = new Fsdb::IO::Reader(-fh => \*STDIN, -fscode => 't');

# my $length = 8; # The history length

my $output_stream = new Fsdb::IO::Writer(-fh => \*STDOUT, -fscode => 't', -cols => [qw(prefix hex_ip score ip)]);
my $current_ip;
my $current_history = '0';
my $prefix_print;
my $cuthis;
my $score;
my $str_ip = '0';
my $c_prefix_mask = ~(2**8 - 1);

my $power_sum_8 = 2.7178571423;
my $power_sum_16 = 3.380729;
my $activehislength = 16;
my $activepowersum = $power_sum_16;
#use Bit::Vector;
#use Bit::Vector::String;

sub hexiptoip{
	my ($hexip) = @_;
	my $ip1 = hex(substr($hexip, 0, 2));
	my $ip2 = hex(substr($hexip, 2, 2));
	my $ip3 = hex(substr($hexip, 4, 2));
	my $ip4 = hex(substr($hexip, 6, 2));
	return "$ip1.$ip2.$ip3.$ip4";
}

sub power{
	my ($para) = @_;
        my $sum = 0;
	my $length = $activehislength;
        for (my $i=$length-1; $i>=0; $i--)
	{
		$sum += ((hex($para) >> $i) & 1) * (1/($i+1));
	}
	my $ratio = $sum/$activepowersum*100;
	$ratio = int($ratio);
	return $ratio;
}

sub cuthistory{
	my ($his) = @_;
	my $his_tail;
	if (length($his) > 8)
	{       $his_tail = substr($his, length($his)-8, 8);}
	else
	{       $his_tail = $his;}
	return $his_tail;
}

while(<>){
	my($ip, $history) = split;
	last if (!defined($ip)); # EOF
	if (!defined($current_ip)){
		$current_ip = $ip;
		$current_history = $history; # in hex format
	}else{
		if($current_ip eq $ip){
			# get prefix
			my $prefix = hex($ip) & $c_prefix_mask;
			$prefix_print = sprintf("%08x", $prefix);

			# get ip string
			#$str_ip = hexiptoip($ip);

			if ($history ne "l"){
				# cut history
				$cuthis = cuthistory($history);
				# calculate the score
				$score = power($cuthis);
				if ($score == 0) {$score = -1;}
				$output_stream->write_row($prefix_print, $current_ip, $score, $str_ip);
			}
			else{
				$cuthis = cuthistory($current_history);
				$score = power($cuthis);
				if ($score == 0) {$score = -1;}
				$output_stream->write_row($prefix_print, $current_ip, $score, $str_ip);
			}
		}else{
			$current_ip = $ip;
			$current_history = $history;
		}
	}
}


