#! /usr/bin/perl -w

use Socket;

$group = shift || "control";
$header = shift || "From";

$remote = shift || "news";
$port = shift || "nntp";
if ($port =~ /\D/) { $port = getservbyname ($port, "tcp"); }
die "unknown port" unless $port;
$iaddr = inet_aton ($remote)
    or die "unknown host: $remote";
$paddr = sockaddr_in ($port, $iaddr);
$proto = getprotobyname("tcp");

socket (SOCK, PF_INET, SOCK_STREAM, $proto)
    or die "socket: $!";

connect (SOCK, $paddr)
    or die "connect: $!";

select SOCK;  $|=1;  # STUPID PERL

$greeting = <SOCK>;
die "$greeting"
    unless ( $greeting =~ /^2[0-9][0-9]/ );

print SOCK "group $group\r\n";
$groupstat = <SOCK>;
die "$groupstat"
    unless ( $groupstat =~ /^211/ );

die "bad format"
    unless ( $groupstat =~ /^2[0-9][0-9] [0-9]* ([0-9]*) ([0-9]*)/ );
$first=$1;  $last=$2;
if ( $first>$last ) {
    $tmp=$first;
    $first=$last;
    $last=$tmp;
}

print SOCK "xhdr $header $first-$last\r\n";
$reply = <SOCK>;
die "$reply"
    unless ( $reply =~ /^221/ );

while ( ! ( ($hline=<SOCK>) =~ /^\./) ) {
    die "bad format: $hline"
	unless ( $hline =~ /^([0-9]*) (.*)$/ );
    $headers{$1} = $2;
}

print SOCK "xhdr Lines $first-$last\r\n";
$reply = <SOCK>;
die "$reply"
    unless ( $reply =~ /^221/ );

while ( ! ( ($hline=<SOCK>) =~ /^\./) ) {
    die "bad format: $hline"
	unless ( $hline =~ /^([0-9]*) (.*)$/ );
    $lines{$1} = $2;
}

foreach $number (keys %headers) {
    $header=$headers{$number};
    $stats{$header}+=$lines{$number};
}

print SOCK "quit\r\n";

select STDOUT;  # STUPID PERL

sub byfreq { $stats{$a} <=> $stats{$b}; }

foreach $header (sort byfreq (keys %stats)) {
    print "$stats{$header}\t$header\n";
}
