use utf8;

open(IN,"nexus.html")|| die "no file named \"nexus.html\" found in this directory\n";
open(OUT,"> nexus.gdf")|| die "could not open output file, make sure you have write permissions\n";;

while($line=<IN>) {
	chomp;
	if ($line =~ /^totalFriends=(\d+)/) {
		$totalFriends = $1;
		print "number of friends = $totalFriends\n";
	}
	if ($line =~ /^linkCount=(\d+)/) {
		$linkCount = $1;
		print "number of connections between friends = $linkCount\n";
	}
	if ($line =~ /^linksTo=/) {
		$line =~ s/:\d+}};$//;
		$line =~ s/:\d+//g;
		@ar = split(/},/,$line);
		for $are (@ar) {
			$are =~ s/linksTo={//;
			($from,$tolist) = split(/:{/,$are);
			@tos = split(/,/,$tolist);
			for $to (@tos) {
				chomp($to);
				$link{$from}{$to} = 1;
			}
		}
	}
	if ($line =~ /^nodeData=/) {
		$line =~ s/:\d+]};$//;
		@ar = split(/],/,$line);
		for $are (@ar) {
			$are =~ s/nodeData={//;
			if ($are =~ /^(\d+):/) {$id = $1;} else {print "error\n";}
			if ($are =~ /\"([^"]+)/) {
				$name{$id} = $1;
				$name{$id} =~ s/["']//g;
				$name{$id} =~ s/\\u\d+/X/g;
#				$name{$id} =~ s/\s(\w)\S+/ $1/g;
				$name{$id} =~ s/\W/_/g;
			}
			$isnode{$id} = 1;
		}
	}
}

print OUT "nodedef>name\n";
for $node (sort keys %isnode) {
	if (!defined($name{$node})) {$name{$node} = "n$node";}
	print OUT "$name{$node}\n";
}

print OUT "edgedef>node1,node2,directed DEFAULT false\n";
for $from (keys %link) {
	for $to (keys %{$link{$from}}) {
		next if ($printed{$to}{$from} == 1);
		if (!defined($name{$from})) {$name{$from} = "n$from";}
		if (!defined($name{$to})) {$name{$to} = "n$to";}
		print OUT "$name{$from},$name{$to},false\n";
		$printed{$from}{$to} = 1;
		print "*$from*  *$to*\n";
	}
}
	