#!/usr/bin/perl

opendir DIR, ".";
@files=();
while(defined($_=readdir DIR)) {
	if(/^(.*)\.txt$/) {
		push @files, $_;
	}
}
closedir DIR;

%edges=();

foreach $f (@files) {
	my %current_edges=();

	open FILE, "<".$f;
	$lineno=0;
	while(<FILE>) {
		$lineno++;
		my $backup=$_;
		while(/link:(.*?)\[(.*?)\](.*)$/) {
			$_=$3;
			# check consistency
			if($1 ne "$2.html" && !$1=~/:\/\//) {
				print "$f:$lineno: link target does not match name ($1 != $2)\n";
			}
			my $txt=$1;
			$txt=~s/\.html/.txt/;
			$current_edges{$txt}=1;
		}
		$_=$backup;
		while(/include::(.*?)\[.*?\](.*)$/) {
			$_=$2;
			$current_edges{$1}=1;
		}
	}
	close FILE;

	$edges{$f}=\%current_edges;
}

sub get_edge_length ($$) {
	my $tag=$_[0];
	my $tag2=$_[1];
	my $tag3;

	foreach $tag3 (keys %{$edges{$tag2}}) {
		my $diff=$edges{$tag}->{$tag2}+$edges{$tag2}->{$tag3};
		if(!defined($edges{$tag}->{$tag3})
		 || $edges{$tag}->{$tag3}>$diff) {
			$edges{$tag}->{$tag3}=$diff;
			get_edge_length($tag,$tag3);
		}
	}
}

$tag="git.txt";
foreach $tag2 (keys %{$edges{$tag}}) {
	get_edge_length($tag,$tag2);
}

%main_edges=%{$edges{$tag}};
foreach $f (@files) {
	if(!defined($main_edges{$f})) {
		print "$f is not reachable from $tag\n";
	}
}

