#!/usr/local/bin/perl
#
#NAME
#  Show - produce an email message
#
#SYNOPSIS
#  Show [+folder] [index]
#
#REQUIRES
#
	$LNAM = $ENV{'LOGNAME'} || $ENV{'USER'};
	$HOME = $ENV{'HOME'} || "/home/$LNAM";
	@INC = ($HOME, "$HOME/mh","$HOME/sh",@INC);
	require 'jcmh.pm';
	use MIME::Base64 ();	# Base-64 decoding routine
	use MIME::QuotedPrint;	# Decode quoted-printable text (do we need this?)
#
#DESCRIPTION
#  This lists the current message from  an  mh-style  directory.   If
#  there is no current message, we start at 1. If the current message
#  doesn't exist, we act as Next, and hunt for the next message.
#
#OPTIONS
#
#EXAMPLES
#
#FILES
#
#BUGS
#
#SEE ALSO
#   Inc, List, Prev, Next, ...
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu>

$| = 1;
$HR = '================================================================================';

for $a (@ARGV) {
	print "$0: Arg \"$a\"\n" if $V>2;
	if ($a =~ /^\+(\w+)$/) {
		$FLDR = $1;
		print "Folder \"$FLDR\" from command line.\n" if $V>2;
	} elsif ($a =~ /^\d+$/) {
		$ndx = $a;
	} else {
		print STDERR "$P: Unrecognized arg \"$a\" ignored.\n";
	}
}
print "Folder \"$FLDR\"\n" if $V>1;

unless ($ndx) {
	$ndx = &getindex($MDIR,$FLDR,1);
	print "Current index in \"$FLDR\" is $ndx.\n" if $V>1;
}
$hdrs = "^(Subj|From|To|Repl|Date|Cc|Content|X-|[-A-Za-z]*-Warning)";
if (open(MSG,"$FDIR/$ndx")) {
	print "--- $FDIR/$ndx\n" if $V>0;
	print "--- $HR\n" if $V>2;
	&setindex($MDIR,$FLDR,$ndx);
line:
	while ($l = <MSG>) {
		$l =~ s/[\s\r]+$//;	# Trim away white stuff
		if ($l eq '') {
			print "\n";
			last line;
		} elsif ($l =~ /$hdrs/i) {
			print "$l\n";
			if ($l =~ m/^Subject: (=\?UTF-8\?B\?(.+)=\?=)/) {	# Is the subject Base64-encoded?
				print "## B64Subj: \"$2\"\n" if $V>1;
				$l = MIME::Base64::decode($2);
				print "## Decoded: \"$l\"\n" if $V>1;
				print "Subject: $l\n";
			}
		}
	}
	while ($l = <MSG>) {print $l}
	print "$HR\n" if $V>2;
	exit 0;
}

# The current/selected message doesn't exist, so we search for the next one.
$imax = &maxindex($MDIR,$FLDR);
print "Highest index in $FLDR is $imax.\n" if $V>2;

file:
	for ($ndx++; $ndx <= $imax; $ndx++) {
		unless (open(MSG,"$FDIR/$ndx")) {
			printf "$FDIR/%d doesn't exist.\n",$ndx if $V>2;
			next file;
		}
		&setindex($MDIR,$FLDR,$ndx);
		print "--- $FDIR/$ndx\n" if $V>0;
		print "$HR\n" if $V>2;
		$from = $subj = $date = '';
line:	while ($l = <MSG>) {
			$l =~ s/[\s\r]+$//;	# Trim away white stuff
			if ($l eq '') {		# Null line ends headers
				print "\n";
				last line;
			} elsif ($l =~ /$hdrs/i) {
				print "$l\n";
			}
		}
		while ($l = <MSG>) {print $l}
		print "--- $HR\n" if $V>2;
		exit 0;
	}
print STDERR "No next message found.\n" if $V>1;

exit 1;
