#!/afs/athena/contrib/perl/perl

$mode = $ARGV[1];
$style = $ARGV[2];
@post = (<STDIN>);
$post = join("\n", @post);

if($style ne "plain"){
    $post = '';
    $inheader = 1;
    for (@post){
	$line = '';
	if($insig){
	    $post .= $_;
	    next;
	}
	if(/Subject: (.+)/ && $inheader){
	    $title = $1;
	    $post = "<title>$title</title>\n".$post;
	}
	if(/Path:/ && $inheader){
	    $_ = '';
	}
	if(/.+ wr[io]te..?.?$/){
	    $line = "<dl>\n<dt>".$_."\n";
	}
	if(substr($_,0,1) eq ">"){
	    $line = "<dl>\n" unless $inquote;
	    $line .= "<dd>".$_."\n";
	    $inquote = 1;
	}
	elsif((substr($_,0,3) =~ ">") && (substr($_,0,2) !~ /[a-zA-Z]/)){
	    $line = "<dl>\n" unless $inquote;
	    $line .= "<dd>".$_."\n";
	    $inquote = 1;
	}
	else{
	    $post.="</dl>" if $inquote;
	    $inquote = 0;
	}
	if(/^\n$/){
	    $line = "<p>\n";
	    $inheader = 0;
	}
	if($inheader){
	    /([^:]+): (.+)/;
	    if($1 eq "From" || $1 eq "Subject"){
		s/([^:]+): (.+)/<strong>\1<\/strong>: <em>\2<\/em><br>/;
	    }
	    else{
		$_.="<br>" if $_;
	    }
	}
	if(substr($_,0,2) eq "--"){
	    $line = "<hr>\n";
	    $line .= substr($_,2) if (substr($_,2) =~ /[a-zA-Z]/);
	    $line .= "<pre>";
	    $insig = 1;
	}
	$line = $_ unless $line;
	$post .= $line;
    }
    if($insig){
	$post .= "</pre>";
    }
}
else{
    $post = "<title>NetNews post from $ARGV[0]</title><pre>$post</pre>";
}

$post=~s,([^="])(http://(\S+)),\1<a href="\2">\2</a>,g;
$post=~s,([^="])(ftp://(\S+)),\1<a href="\2">\2</a>,g;
$post=~s,([^="])(file://(\S+)),\1<a href="\2">\2</a>,g;
$post=~s,([^="])(gopher://(\S+)),\1<a href="\2">\2</a>,g;

open(ART, ">/tmp/article.html");
print(ART $post);
close(ART);


if($mode eq "lynx"){
    if($pid = fork()){
	wait;			# 
	unlink("/tmp/article.html");
    }
    else{
	system("lynx /tmp/article.html < /dev/tty");
    }
}
else{
    $ps = (-e '/usr/ucb/ps') ? '/usr/ucb/ps ax':'ps ax';
    $out = `$ps`;
    $out =~ /[ \t]*(\d+).+Mosaic.*/;
    $mospid = $1;

    open(TMP, ">/tmp/Mosaic.$mospid");
    print(TMP "goto\n");
    print(TMP "file://localhost/tmp/article.html\n");
    close(TMP);

    kill 'USR1', $mospid;
    exit;
}
