#! /usr/bin/perl

# check_all_links.pl
# Matti Katila
# 2002-08-24T09:47:22
#
# This simple utility tries to figure out broken links on uml-html files.
#
# Usage: 
# cd "to doc/uml"
# execute 'check_all_link.pl *' 


use strict;


my @html_files = @ARGV;

foreach (@html_files) {
    my $file = $_;

    # check file
    next if ($file !~ /.html$/ );

    # open file
    if ( -e $file ) {
        local *FILE;
        open(FILE, "$file");

        my @lines=();
        while(<FILE>) {
            chop;
            push(@lines, $_);
        }

        # print if errors found in links
        my @errors = check_lines(@lines);
        if (@errors != 0) {
            print "file \'$file\' has broken links:\n";
            foreach (@errors) {
                print"   link $_\n";
            }
        }


        close FILE;
    } else { print "Error: file $file not found.\n"; }
}


sub check_lines {
    my (@lines) = @_;

    # parse off spaces/tabs from the beginning
    foreach(@lines) {
        s/^[^<]*//;
    }

    # remove !'<A '
    for (my $i=0; $i<@lines; $i++) {
        if ( "$lines[$i]" !~ /^<A / ) {
            splice(@lines, $i, 1);
            $i--;
        }
    }

    my @link_errors=();

    my ($tmp, $link, $rest);
    $rest = "@lines";
    while ($rest ne '') {
        ($tmp, $link) = split /href=\"/, $rest, 2;
        ($link, $rest) = split /\"/, $link,2;
#        print"l \'$link\'\n";

        # some links has #-character
        ($link, $tmp) = split /#/, $link, 2;
        
        if ( $link eq '' || -e $link) { ; } 
        else { push(@link_errors, $link); }        
    }

#    foreach(@lines) {
#        print "rivi $_\n";
#    }

    return @link_errors;
}
