#!@@PERL@@ -ns
#
#	This script is part of rtfdtohtml.
#	Copyright (c) 1996  Elmar Ludwig - Universitaet Osnabrueck
#
#	Handle NeXT-extensions to RTF: Graphics and Links.
#	New: Local hypertext Links will be tested for Validity.
#
#	Options:	-rtfd	for RTFD files (default is -rtf)
#			-href	select alternate link style (see man page)
#			-png	create links to *.png files (default is -gif)

unless (defined $prefix)
{
    $prefix = $rtfd ? '../' : '';
    $type = $png ? 'png' : 'gif';
    $dir = $ENV{'FILENAME'};
    if ($dir =~ /^(.*)\//)
    {
	chdir $1 || die "chdir failed for $1: $!";
	$dir = $';
    }
    $dir .= '/';
}

s/({\\fonttbl\W.*) $ENV{'QUOTE_FONT'};/$1 Quote_Font;/o;

if (/{\\NeXTGraphic[0-9]* ([^;]+) \\width([0-9]+) \\height([0-9]+) *}$/)
{
    $a = $`;
    $name = $1;
    $width = int($2 / 20);
    $height = int($3 / 20);
    $suffix = $name =~ /\.([^.]*)$/ ? $1 : '';

    print STDERR "Warning: invalid reference to `$name'\n" unless -e $dir.$name;

    if ($suffix eq 'eps' || $suffix eq 'ai' || $suffix eq 'tiff')
    {
	print "$a\\v1\\shad1<IMG src=\"$name.$type\" width=$width ",
	      "height=$height>\\shad0\\v0\n";
    }
    elsif ($suffix eq 'gif' || $suffix eq 'jpeg' || $suffix eq 'jpg' ||
	   $suffix eq 'xbm' || $suffix eq 'xpm'  || $suffix eq 'png')
    {
	print "$a\\v1\\shad1<IMG src=\"$name\" width=$width height=$height",
	      ">\\shad0\\v0\n";
    }
    else
    {
	print "$a\\v1\\shad1<A href=\"$name\"><IMG src=\"$name.tiff.$type\" ",
	      "width=48 height=48></A>\\shad0\\v0\n";
    }
}
elsif (/{\\NeXTHelpMarker[0-9]* \\markername ([^;]*); *}$/)
{
    if ($href && $inside)
    {
	print "$`\\v1\\shad1</A>\\shad0\\v0\n";
	$inside = '';
    }
    else	# extend mark to end of line?
    {
	print "$`\\v1\\shad1<A name=\"$1\"></A>\\shad0\\v0\n";
    }
}
elsif (/{\\NeXTHelpLink[0-9]* \\markername ([^;]*);\\linkFilename ([^;]*);\\( *)linkMarkername ([^;]*); *}$/)
{
    $a = $`;
    $name = $1 ? " name=\"$1\"" : '';
    $mark = $4 ? "#$4" : '';
    $link = "<IMG src=\".!link.$type\" alt=\"*\" " .
	    'width=10 height=10 border=0></A>';

    if ($3 && $href)
    {
	$link = '';
	$inside = 'YES';
    }

    if ($2)
    {
	$_ = $2;
	unless (m%^[A-Za-z]+://% || m%^//% || /^mailto:/ || /^news:/)
	{
	    print STDERR "Warning: invalid hypertext link to `$_'\n" unless -e;
	    $_ = $prefix . $_ unless /^\//;
	    $_ .= '/index.html' if /\.rtfd\/*$/;
	    $_ .= '.html' if /\.rtf$/ || ($mark && !/\.html$/);
	}
	print "$a\\v1\\shad1<A$name href=\"$_$mark\">$link\\shad0\\v0\n";
    }
    else
    {
	$mark = 'index.html' unless $4;
	print "$a\\v1\\shad1<A$name href=\"$mark\">$link\\shad0\\v0\n";
    }
}
else
{
    print;
}
