#!/usr/athena/bin/perl

#########################################################################
#	scanp
#		- Jesse Hong <jesse@mit.edu>,Fri Feb 23 20:10:16 EST 1996
#
#	Wrapper for /usr/athena/bin/scan so that it can support an
#	argument similar to tail -- the number of the most recent
#	messages to see the headers for.
#
#	Usage:
#		scanp [-##] [usual arguments to scan]
#
#	Where ## is the number of messages to show headers for from
#	the last message.  Defaults to DEFNUM if no ## is given.
#
#########################################################################


#########################################################################
#		Set some constants which are used.
#
$DEFNUM = 10 ;
$HOME = $ENV{'HOME'} ;

#########################################################################
#		Get the current folder info from the 
#		MH context file
#
$context = "$HOME/Mail/context" ;
open(CONTEXT, $context) ;
for (<CONTEXT>) {
    if (/^Current-Folder:\s(\w*)/) {
	$folder = $1 ;
    }
}
close(CONTEXT) ;

#########################################################################
#		Check the arguments for the -## to see
#		how many of the most recent messages to show.
#		If there are no arguments at all, use DEFNUM.
#		Also check if there is a folder argument
#
$argnum = -1 ;
$tailnum = -1 ;
$newfold = '0' ;
if ($#ARGV == -1) { $tailnum = $DEFNUM ; }
for ($i = 0 ; $i <= $#ARGV ; $i++) {
    if ($ARGV[$i] =~ /-(\d*)/) {
	$argnum = $i ;
	$tailnum = $1 ;
    }
    elsif ($ARGV[$i] =~ /\+(\S*)/) {
	$newfold = $1 ;
	if ($tailnum == -1) { $tailnum = $DEFNUM ; }
    }
}

# take -## and -a out of @ARGV
if ($argnum != -1) { splice(@ARGV,$argnum,$argnum+1) ; }

#########################################################################
#		Pack the mail folders and then check
#		the number of messages in the current folder
#
# slowed things down - not totally necessary
#system("/usr/athena/bin/folder -all -pack > /dev/null") ;

if ($newfold eq '0') { open(FOLDER,"/usr/athena/bin/folder -pack |") ; }
else { open(FOLDER,"/usr/athena/bin/folder +$newfold -pack |") ; }
for (<FOLDER>) {
    if (/message\w*\s*\(\s*\d*-\s*(\d*)\)\W\scur=\s(\d*)/) {
	$last = $1 ; $cur = $2 ;
    } elsif (/message\w*\s*\(\s*\d*-\s*(\d*)\)/) {
	$last = $1 ; $cur = -1 ;
    }
}
close(FOLDER) ;

#########################################################################
#		Run scan with all the arguments and with
#		the message list appropriate for -##
#
if ($tailnum > 0) {
    $start = $last - $tailnum + 1 ;
    if ($start < 1) { $start = 1 ; } ;
    exec("/usr/athena/bin/scan @ARGV $start-$last") ;
} else {
    exec("/usr/athena/bin/scan @ARGV") ;
}
