#!/usr/athena/bin/perl

require '/afs/athena/user/m/k/mkgray/perl/chat2.pl';

sub listen {
        local($secs) = @_;
        local($return,$tmp) = "";
        while (length($tmp = &chat'expect($secs, '(.|\n)+', '$&'))) {
                print $tmp if $trace;
                $return .= $tmp;
        }
        $return;
}

if ($#ARGV > 2) { &usage(); }

&chat'open_port('news.mit.edu', 119) || die "No news!";
if($ARGV[0] eq "-h"){shift(@ARGV);$headtoo = 1;}
$group = $ARGV[0];
if($ARGV[1]=~/last/)
{
	$ARGV[1]=~s/last//;
	$last = 1;
	$n = int($ARGV[1]);
}
else
{
	$n= int($ARGV[1]);
}

while(!/ready/) {
	$_=&listen(2);
}

&chat'print("group $group\n");
while(!$newsline) {
$newsline = &listen(10);
 }
@vals = split(/ +/, $newsline);
if(int($vals[0]) > 400)
{
	print(STDERR "No good!\n");
	exit(1);
}
if($last)
{
	$lnum = int($vals[3]);
	$anum = $lnum - $n + 1;
	foreach $art ($anum..$lnum)
	{
	if($headtoo){
		&chat'print("head $art\n");
		$foo = &listen(6);
		print($foo);
		print("\n\n---\n\n");
		}
		&chat'print("body $art\n");
		$foo = &listen(3);
		$foo .= "\n";
		$foo=~s/.*body follows.//g;
		$foo=~s/\n\W*\n/\n/g;
		print($foo);
		print("\n\n---\n\n");
	}
}
else
{
	if($headtoo){
		&chat'print("head $art\n");
		$foo = &listen(6);
		print($foo);
		print("\n\n---\n\n");
		}
	&chat'print("body $n\n");
	$foo = &listen(3);
	$foo=~s/\n\.//g;
	print($foo);
}
&chat'print("quit\n");


