#!/usr/bin/perl

open($file_in, "geolocation.ip");

my $ip_first = 0;
newfile(0);

LINE: while(<$file_in>) {
	next LINE if /^#/;
	chomp;
	@elements = split(' ', $_);
	line2file(@elements[0], @elements[1], @elements[2]);
}

close $file_in;
close $file_out;

sub line2file
{
	@ip1_elements = split('\.', $_[0]);
	@ip2_elements = split('\.', $_[1]);

	if(@ip1_elements[0] eq $ip_first) {
		newline($_[0] . " " . $_[1] . " " . $_[2] . "\n");

		if(@ip2_elements[0] ne $ip_first) {
			for($i = $ip_first+1; $i <= @ip2_elements[0]; $i++) {
				$ip_first = $i;
				newfile(1);
				newline($_[0] . " " . $_[1] . " " . $_[2] . "\n");
			}
		}
	}
	else {
		$ip_first++;

		for($i = $ip_first; $i < @ip1_elements[0]; $i++) {
			newfile(1);
			newline($ip_first . ".0.0.0 " . $ip_first . ".255.255.255 ZZ\n");
			$ip_first++;
		}

		newfile(1);
		newline($_[0] . " " . $_[1] . " " . $_[2] . "\n");

		if(@ip2_elements[0] ne $ip_first) {
			for($i = $ip_first+1; $i <= @ip2_elements[0]; $i++) {
				$ip_first = $i;
				newfile(1);
				newline($_[0] . " " . $_[1] . " " . $_[2] . "\n");
			}
		}
	}
}

sub newfile
{
	if($_[0] == 1) { close $file_out; }
	open($file_out, ">geolocation." . ipstretch($ip_first));
}

sub newline
{
	print $file_out @_;
}

sub ipstretch
{
	if($_[0] > 99) {
		$_[0];
	}
	else {
		if($_[0] > 9) {
			"0" . $_[0];
		}
		else {
			"00" . $_[0];
		}
	}
}
