#!/bin/sh 
#! perl 
eval 'exec perl -x $0 ${1+"$@"}'
        if 0;

# Converts a Tiers topology to an adjacency list format.
# Usage:
# tiers2adj <tiers_input_topology_file> 
# The output is written to stdout.
#
# The adjacency file has the following format:
# The first line contains the number of nodes and the number of links
# in the topology.  Each remaining line represents a link given as two 
# strings, which are the names of the nodes that the link connects 
# and an additional number (always 1), which represents the hop 
# distance. 
#
# Graham Phillips <graham@isi.edu>
# April 1999, Los Angeles.

$data_file = $ARGV[0];
$error = 0;	
$line_num = 0;

sub Usage {
	print "Usage: tiers2adj <tiers_topology_file>\
   Converts a Tiers topology to an adjacency list format.  The output adjacency\
   list is written to stdout.\
   See http://www.isi.edu/~graham/contrib/index.html for more\
   information.\n";
   exit;
}

sub readLine {
	do {
		$_ = <FILE>;
		$line_num++;
	} while (/^#/);
	$return = $_;
}


sub readLineUntilEdges {
	do {
		$_ = <FILE>;
		$line_num++;
	} while (/^#/ && !/EDGE/);
	$return = $_;
}

$num_links = 0;

for ($pass=1; $pass <= 2; $pass++) {

	open(FILE, $data_file) || Usage();

	while (!eof(FILE) && !$error ) {
		$done = 0;
		while (!eof(FILE) && !$done && !$error ) {
			$_ = &readLineUntilEdges; 
			if (/EDGES/) {
				$done = 1;
			} else {
				if (s/([0-9]+).*/\1/) {
					chomp;
					$last_vertex = $_; 
				} else {
					$error = 1;	
					print "# line $line_num is \"$_\"\n";
				}
			}
		}
		$num_vertices = $last_vertex + 1; 
		if ($pass == 2) {
			print "$num_vertices $num_links\n";
		}

		while (!eof(FILE) && !$error ) {
			$_ = &readLine; 
			if (s/([0-9]+)\s+([0-9]+).*/\1 \2/) {
				if ($pass == 1) {
					$num_links++;
				} 
				if ($pass == 2) {
					chomp;
					print "$_ 1\n"; 
				}
			} else {
				$error = 1;	
				print "# line $line_num is \"$_\"\n";
			}
		}
	}
	die "detected error\n" if ($error); 
	close FILE;
}

