#!/afs/ece/usr/tcl/bin/wish -f
# The next line is executed by most shells, but not Tcl \
wish $0 $*

#
# Mail waiting program...waits for new mail, then brings it up when it
# arrives.

# Mail file
set newmail "/usr/spool/mail/$env(USER)"

# Time we last accessed this file. (generally shortly after startup time)
catch {set atime [file mtime $newmail]}

# Time to sleep between mail checks (in ms)
set sleep_time 10000

# First new message red
set firstnew ""

# Proc to read mail.

proc wait_for_mail {} {
  global sleep_time newmail atime
  while {1} {
    global wake_up
    set wake_up 0
    after $sleep_time {set wake_up 1} ; tkwait variable wake_up
    if {([catch {wm state .bith}])} {return}
    if {([file mtime $newmail] != $atime)} {
      setup_new_mail
}}}

proc setup_new_mail {} {
  global atime newmail firstnew
  if {([catch {set text [exec inc]}])} {return}
  bell ; bell
  set newmsg [string range $text [expr "[string first "\n\n" $text]+2"] \
          end]
  if {($firstnew == "")} {scan $newmsg " %d+ " firstnew}
  set atime [file mtime $newmail]
  .bith.m insert end "$newmsg\n"
  .bith.m yview "[.bith.m index @0,0] +1 lines"
  wm deiconify .bith
}

proc read_new_mail {} {
  global firstnew TH
  if {($firstnew == "")} {bell} else {
    set TH(File,Browse,Dir) ""
    .syme1.t_fm.next configure -state normal
    .syme1.t_fm.last configure -state normal
    .bith.m delete 2.0 end-1c
    .bith.m yview moveto 0.0
    set firstnew ""
}}

proc show_bith_window {} {
  toplevel .bith
  wm title .bith "Bith"
  wm iconname .bith "Bith"
  wm iconify .bith
  text .bith.m -height 3
  .bith.m insert 1.0 "Mail to be read:\n"
  button .bith.new -text "New Mail" -command read_new_mail
  pack .bith.new -fill x
  pack .bith.m -expand yes -fill both
  bindtags .bith {.bith Text . All}
  bind .bith <Enter> {break} ; bind .bith <Leave> {break}
}

set cwd [pwd]
if {([string match /* [info script]])} {
  set bethmail_dir [file dirname [info script]]
} else {set bethmail_dir [file dirname $cwd/[info script]]}
cd $bethmail_dir

# Source bread, to show last message.
source $bethmail_dir/bread

show_bith_window
setup_new_mail
wait_for_mail
