#!/usr/bin/perl -w

# Modify generated HTML so that a name of another program in comments
# will result in a link

# This file is part of CLC-INTERCAL

# Copyright (c) 2023 Claudio Calvelli, all rights reserved.

# CLC-INTERCAL is copyrighted software. However, permission to use, modify,
# and distribute it is granted provided that the conditions set out in the
# licence agreement are met. See files README and COPYING in the distribution.

use vars qw($VERSION $PERVERSION);
($VERSION) = ($PERVERSION = "CLC-INTERCAL/Docs aux/getlink 1.-94.-2.4") =~ /\s(\S+)$/;

undef $/;
for my $file (@ARGV) {
    open(FILE, '<', $file);
    my $text = <FILE>;
    close FILE;
    my $change;
    my $new = '';
    while ($text =~ s/^(.*?)(<em\s+class="comment">)//is) {
	$new .= $1;
	my $com = $2;
	$text =~ s/^(.*?<\/em>)//si or die "Invalid comment in $file\n";
	$com .= $1;
	$com =~ s/\b([^"'<>\s]+)\.(\w*i)\b/<a href=\"$1.html\">$1.$2<\/a>/gsi
	    and $change = 1;
	$new .= $com;
    }
    $change or next;
    $new .= $text;
    eval {
	open(TMP, '>', "$file.tmp") or die "$file.tmp: $!\n";
	print TMP $new or die "$file.tmp: $!\n";
	close TMP or die "$file.tmp: $!\n";
	rename("$file.tmp", $file) or die "rename($file.tmp, $file): $!\n";
	1
    } and next;
    unlink "$file.tmp";
    die $@;
}

