#!/usr/local/bin/wish8.0 -f
#$Id: xfrom,v 1.2 1998/01/25 20:11:36 deniz Exp $

# xfrom: A mail notification tool.             (c) Deniz Yuret, 1998
#
# I do not like xbiff.  It shows you there is mail, but does not tell
# you from whom.  Is it your advisor, or is it one of your students?
# Of course you can use the from command.  But that does not tell you
# who the mail was sent to: personally to you or to one of the stupid
# mailing groups you are a member of?  As a result none of these tools
# tell you how urgent this message is and whether you should stop
# coding and start reading your mail.  So I wrote xfrom.  It displays
# who your messages are from and who they were sent to.  You can also
# click on any of the messages to get a preview.  Just make sure that
# the MAILBOX_DIRECTORY is correct for your system.

set MAILBOX_DIRECTORY /var/mail

# Format of the mail file is simple.  Each message contains a header
# and a body.  There is a blank line before and after the header.  The
# header starts with a line that matches "^From " following a blank
# line.  Any line within the body that matches this is protected by
# substituting ">From" for "From".

proc checkMail args {
    global mailfile mailtime poslist

    set newtime [file mtime $mailfile]
    if { $args != "" } { after 60000 { checkMail again }}
    if { $newtime == $mailtime } { return 0 }
    set mailtime $newtime
    set poslist {}
    set f [open $mailfile r]
    set region body
    set pline ""
    .xfrom delete 0 end

    while {[gets $f line] >= 0} {
	if { ($region == "body") && ($pline == "") } {
	    if [regexp {^From ([^@]+)@} $line tmp from] {
		set region header
		set to ""
		lappend poslist [expr [tell $f] - [string length $line] - 1]
	    }
	} elseif { $region == "header" } {
	    if { $line == "" } {
		set region body
	    } elseif { $to == "" } {
		if [regexp {^To:[^@]* [<"']*([^@]+)@} $line tmp to] {
		    .xfrom insert end [format "%s to %s" $from $to]
		}
	    }
	}
	set pline $line
    }
    lappend poslist [tell $f]
    close $f
    return 1
}

proc printMail m {
    global poslist mailfile topname
    if { [checkMail]==1 } return
    set topname [expr $topname + 1]
    toplevel .$topname
    wm title .$topname "xfrom [.xfrom get $m]"
    text .$topname.text -yscrollcommand ".$topname.scroll set"
    scrollbar .$topname.scroll -command ".$topname.text yview"
    set f [open $mailfile r]
    set pos1 [lindex $poslist $m]
    seek $f $pos1
    set pos2 [lindex $poslist [expr $m+1]]
    .$topname.text insert end [read $f [expr $pos2-$pos1]]
    close $f
    pack .$topname.scroll -side right -fill y
    pack .$topname.text -side left
}

set logname $env(USER)
set mailfile $MAILBOX_DIRECTORY/$logname
set mailtime 0
set topname 0
listbox .xfrom -font 5x7 -selectmode single -height 0 -width 0 -exportselection false
pack .xfrom
bind .xfrom <ButtonRelease-1> { printMail [.xfrom curselection] }
checkMail forever

