#!/usr/bin/perl
# This reads the passed .hlp files, and generates a nice graphviz graph on
# stdout. Use it like:
#   find dir -name \*.hlp | graphhelp | dot

print "digraph helptopics {\n";

my %objs;
my %topics;

# Autogenerated.
$topics{missing}='avatar';
$topics{index}='avatar';

while (<>) {
	chomp;
	open (IN, "<$_") || die "open $_: $!";
	my ($obj, $topic) = $_ =~ /^.*\/([^\/]+)\/([^\/]+)\.hlp$/;
	$topics{$topic}=$obj;
	# Only display each link once in a given topic, even if it
	# links several times. Makes the graph less cluttered.
	my %seen;
	while (<IN>) {
		while (/=([-_0-9a-zA-Z]+)=/g) {
			push @{$objs{$obj}}, [$topic, $1] unless $seen{$1};
			$seen{$1}=1;
		}
	}
	close IN;
}

my $c=0;
foreach my $obj (sort keys %objs) {
	print "\tsubgraph cluster_".$c++." {\n";
	print "\t\tlabel = \"$obj\";\n";
	print "\t\tstyle = filled;\n";
	print "\t\tcolor = lightgrey;\n";
	foreach my $topic (keys %topics) {
		next unless $topics{$topic} eq $obj;
		print "\t\t\"$topic\";\n";
	}
	print "\t}\n\n";
}

foreach my $obj (sort keys %objs) {
	foreach my $link (@{$objs{$obj}}) {
		print "\t\"".$link->[0]."\" -> \"".$link->[1]."\"";
		if (! $topics{$link->[1]}) {
			# Missing help topic.
			print " [ color = red ];\n";
			print "\t\"".$link->[1]."\" [ color = red ];\n";
		}
		else {
			print ";\n";
		}
	}
}

print "}\n";
