#!/bin/sh
# the next line restarts using wish \
exec wish "$0" "$@"

# tcl/tk front-end for vgetty allows listening/recording of 
# messages through sound card.
#
# Maintained by: Peter Bruley
# email: pbruley@highstream.net
# The latest version of this script is available from:
# ftp://alpha.greenie.net/pub/mgetty/tools/

###########################################################################

set playPID ""
set tkVoice 1
set TKVREV "TKVOICE v1.3"
set TKVDATE "April 8, 2002"
set font {Helvetica 14}
set bgcolor "#eeeeee"
set FAX ""
set PAGET ""


wm title . "tkVOICE"


##############################################################################
proc startuperror {} {
  set WARNING0 "***********************************************"    
  set WARNING1 "*         Error starting tkvoice              *"    
  set WARNING2 "* Please change to the installation directory *"
  set WARNING3 "*         and try starting again              *"
  set WARNING4 "                                               "
  puts $WARNING4
  puts $WARNING0
  puts $WARNING1
  puts $WARNING2
  puts $WARNING3
  puts $WARNING0
  puts $WARNING4
  cd ~/.tkvoice
  exec rm tkvoicevoice.dat 
  exec rm tkvoiceplaywave.dat
  exec rm tkvoicerecwave.dat
}

##############################################################################
#   READ the user preferences into the program and
#   load in some defaults if the files are not found
proc startup {} {
# read in the VOICE paths information
global drawvoice tkvoicedir userhome
global voicecfg voicedir voicein voiceout greeting vindex vflag
  set USERPREF ""
  set STARTDIR [pwd]
  set tkvoicedir $STARTDIR
  set FILENAME tkvoicevoice.dat
  cd ~/
  if { [file isdirectory .tkvoice] == 0} {
       catch [exec mkdir .tkvoice] }
  cd ~/.tkvoice
  set userhome [exec pwd]
  if { [file writable $FILENAME] == 1} {
   catch {set file [open $FILENAME r+]}
     while {[gets $file string] >= 0} {
       append USERPREF $string
      }
    close $file } else {
   set USERPREF "1 $tkvoicedir /usr/local/etc/mgetty+sendfax"
  }
   set drawvoice  [lindex $USERPREF 0]
   set tkvoicedir [lindex $USERPREF 1]
   set voicecfg   [lindex $USERPREF 2]
   set FILENAME $voicecfg/voice.conf
   set greeting ""
   set voicedir ""
   set voicein ""
   set voiceout ""
   set vindex ""
   set vflag ""
   set VGLOBALS ""
if { $drawvoice == "1" } {
   if { [file exists $FILENAME] == 1 } {
      if { [file readable $FILENAME] == 1} {
      catch {set file [open $FILENAME r]}
        while {[gets $file LINE] >= 0} {
          set LINE [string trimleft $LINE]
          if { $LINE != "" } {
             if {[string range $LINE 0 0] != "#"} {
               append VGLOBALS "\{$LINE\} "
        } }  }
      close $file
      } else {
      set MSG "Can not read $FILENAME check permissions" 
      puts $MSG
      tk_messageBox -icon error -type ok -title "tkVoice Start-up ERROR" -message "Can not read $FILENAME check permissions"
      }
   } else {
   set MSG "No such file: $FILENAME"
   puts $MSG
      tk_messageBox -icon error -type ok -title "tkVoice Start-up ERROR" -message "No such file: $FILENAME"
   }
 
# Fish for directories in the voice.conf file:
   foreach i $VGLOBALS { 
      if {[string range $i 0 9] == "voice_dir "} {
      set voicedir [string range $i 10 end]
      set voicedir [string trim $voicedir]
      }
      if {[string range $i 0 11] == "receive_dir "} {
      set voicein [string range $i 12 end]
      set voicein [string trim $voicein]
      }
      if {[string range $i 0 11] == "message_dir "} {
      set voiceout [string range $i 12 end]
      set voiceout [string trim $voiceout]
      }
      if {[string range $i 0 12] == "message_list "} {
      set vindex [string range $i 13 end]
      set vindex [string trim $vindex]
      }
      if {[string range $i 0 17] == "message_flag_file "} {
      set vflag [string range $i 18 end]
      set vflag [string trim $vflag]
      }
      if {[string range $i 0 14] == "backup_message "} {
      set greeting [string range $i 15 end]
      set greeting [string trim $greeting]
      }
   }
# Make sure vars have something in them:
      if { $voicedir == "" } {
        set MSG "Can not read BASE voice-spool directory"
       	puts $MSG
        set MSG "Defaulting to: /var/spool/voice"
       	puts $MSG
	tk_messageBox -icon error -type ok -title "tkVoice Start-up ERROR" -message "Can not read BASE voice-spool directory. Defaulting to:\n/var/spool/voice"
        set voicedir "/var/spool/voice" }

      if { $voicein == "" } {
        set MSG "Can not read INCOMING voice-spool directory"
	puts $MSG
        set MSG "Defaulting to: $voicedir/incoming"
	puts $MSG
	tk_messageBox -icon error -type ok -title "tkVoice Start-up ERROR" -message "Can not read INCOMING voice-spool directory. Defaulting to:\n$voicedir/incoming"
 	set voicein "incoming" }

      if { $voiceout == "" } {
        set MSG "Can not read MESSAGES voice-spool directory"
	puts $MSG
        set MSG "Defaulting to: $voicedir/messages"
	puts $MSG
	tk_messageBox -icon error -type ok -title "tkVoice Start-up ERROR" -message "Can not read MESSAGES voice-spool directory. Defaulting to:\n$voicedir/messages"
	set voiceout "messages" }

       if { $vindex == "" } {
        set MSG "Can not read INDEX file"
	puts $MSG
        set MSG "Defaulting to: $voicedir/$voiceout/Index"
	puts $MSG
	tk_messageBox -icon error -type ok -title "tkVoice Start-up ERROR" -message "Can not read INDEX file. Defaulting to:\n$voicedir/$voiceout/Index"
	set vindex "Index" }

      if { $vflag == "" } {
        set MSG "Can not read FLAG file"
	puts $MSG
        set MSG "Defaulting to: $voicedir/.flag"
	puts $MSG
	tk_messageBox -icon error -type ok -title "tkVoice Start-up ERROR" -message "Can not read FLAG file. Defaulting to:\n$voicedir/.flag"
	set vflag ".flag"
      } elseif { [file exists $voicedir/$vflag] != 1} {
        catch [ exec touch $voicedir/$vflag ]
        catch [ exec chmod 666 $voicedir/$vflag ]
      }

      if { [file readable $voicedir/$voiceout/$vindex] == 1} {
         catch {set file [open $voicedir/$voiceout/$vindex r]}
         while {[gets $file string] >= 0} { set greeting $string }
         close $file
      }

        if { $greeting == "" } {
        set MSG "Can not read GREETING Name"
	puts $MSG
        set MSG "Defaulting to: $voicedir/$voiceout/greeting"
	puts $MSG
	tk_messageBox -icon error -type ok -title "tkVoice Start-up ERROR" -message "Can not read GREETING Name. Defaulting to:\n$voicedir/$voiceout/greeting"
	set greeting "greeting" }


}
##############################################################
# tkvoice directory checking START
#
# TEST for executable:
   if { [file executable $tkvoicedir/tkvoice] == 0} {
         set tkvoicedir $STARTDIR
         if { [file executable $tkvoicedir/tkvoice] == 1} {
            savevoice
            } else {
            startuperror
            }
      } else {
# TEST for the tkvoice.gif
      set test ""
      catch { exec ls $tkvoicedir/image/tkvoice.gif } test
      if { $test != "$tkvoicedir/image/tkvoice.gif" } {
         set tkvoicedir $STARTDIR
         set test ""
         catch { exec ls $tkvoicedir/image/tkvoice.gif } test
         if { $test == "$tkvoicedir/image/tkvoice.gif"} {
            savevoice
            } else {
            startuperror
            }
         }
      }
# tkvoice directory checking END
##############################################################

# read in the modem information
global MODEMTYPE MODEMCOMP pvfsamples
  set USERPREF ""
  set FILENAME tkvoicemodem.dat
   set datinfo [catch {set file [open $FILENAME r+]}]
   if {$datinfo == 0} {
     while {[gets $file string] >= 0} {
       append USERPREF $string
      }
    close $file} else {
   set USERPREF "US_Robotics 1 8000"
    }
   set MODEMTYPE [lindex $USERPREF 0]
   set MODEMCOMP [lindex $USERPREF 1]
   set pvfsamples [lindex $USERPREF 2]

# read in the audio information
global PCMDT playwave PBAMP audioDEV audioOST RCMDT recordwave
  set USERPREF ""
  set FILENAME tkvoiceaudio.dat
   set datinfo [catch {set file [open $FILENAME r+]}]
   if {$datinfo == 0} {
     while {[gets $file string] >= 0} {
       append USERPREF $string
      }
    close $file} else {
   set USERPREF "{wavplay} {} {1.0} {dsp} {ossdsp} {wavrec} {}"
    }
   set PCMDT [lindex $USERPREF 0]
   set playwave [lindex $USERPREF 1]
   set PBAMP [lindex $USERPREF 2]
   set audioDEV [lindex $USERPREF 3]
   set audioOST [lindex $USERPREF 4]
   set RCMDT [lindex $USERPREF 5]
   set recordwave [lindex $USERPREF 6]

# read in the FAX paths information
global drawfax faxdir faxin faxout faxdpi printcmd printsel
  set USERPREF ""
  set FILENAME tkvoicefax.dat
  cd ~/
  if { [file isdirectory .tkvoice] == 0} {
       catch [exec mkdir .tkvoice] }
  cd ~/.tkvoice
  if { [file writable $FILENAME] == 1} {
   catch {set file [open $FILENAME r+]}
     while {[gets $file string] >= 0} {
       append USERPREF $string
      }
    close $file} else {
   set USERPREF "1 /var/spool/fax /incoming /outgoing 206 {lpr -P} {}"
    }
   set drawfax  [lindex $USERPREF 0]
   set faxdir   [lindex $USERPREF 1]
   set faxin    [lindex $USERPREF 2]
   set faxout   [lindex $USERPREF 3]
   set faxdpi   [lindex $USERPREF 4]
   set printcmd [lindex $USERPREF 5]
   set printsel [lindex $USERPREF 6]
}
################ END proc startup ##################################

#   Process to save the paths preferences
proc savevoice {} {
global drawvoice tkvoicedir voicecfg
  set USERPREF ""
  set SAVENAME "tkvoicevoice.dat"
  cd ~/
  if { [file isdirectory .tkvoice] == 0} {
       catch [exec mkdir .tkvoice] }
  cd ~/.tkvoice
  if { [file isfile $SAVENAME] == 1} {
       catch [exec rm $SAVENAME] }
  catch [exec touch $SAVENAME]
  set file [open "$SAVENAME" r+]
  foreach x "$drawvoice $tkvoicedir $voicecfg" {
    append USERPREF "$x\ "
  }
  puts $file $USERPREF
  close $file
}

####################################################################
# now run the startup proc or the rest of the script will bomb
startup
####################################################################

#   Process to save the Modem preferences
proc savemodem {} {
global MODEMTYPE MODEMCOMP pvfsamples
  set USERPREF ""
  set SAVENAME "tkvoicemodem.dat"
  cd ~/
  if { [file isdirectory .tkvoice] == 0} {
       catch [exec mkdir .tkvoice] }
  cd ~/.tkvoice
  if { [file isfile $SAVENAME] == 1} {
       catch [exec rm $SAVENAME] }
  catch [exec touch $SAVENAME]
  set file [open "$SAVENAME" r+]
  foreach x "$MODEMTYPE $MODEMCOMP $pvfsamples" {
    append USERPREF "$x\ "
  }
  puts $file $USERPREF
  close $file
}

#   Process to save the audio command and arguments
# save the playwave command and arguements
proc saveaudio {} {
global PCMDT playwave PBAMP audioDEV audioOST RCMDT recordwave
  set USERPREF ""
  set SAVENAME "tkvoiceaudio.dat"
  cd ~/
  if { [file isdirectory .tkvoice] == 0} {
       catch [exec mkdir .tkvoice] }
  cd ~/.tkvoice
  if { [file isfile $SAVENAME] == 1} {
       catch [exec rm $SAVENAME] }
  catch [exec touch $SAVENAME]
  set file [open "$SAVENAME" r+]
    append USERPREF "{$PCMDT}\ {$playwave}\ {$PBAMP}\  {$audioDEV}\  {$audioOST}\  {$RCMDT}\  {$recordwave}"
  puts $file $USERPREF
  close $file
}
#   Process to save the FAX preferences
proc savefax {} {
global drawfax faxdir faxin faxout faxdpi printcmd printsel
  set USERPREF ""
  set SAVENAME "tkvoicefax.dat"
  cd ~/
  if { [file isdirectory .tkvoice] == 0} {
       catch [exec mkdir .tkvoice] }
  cd ~/.tkvoice
  if { [file isfile $SAVENAME] == 1} {
       catch [exec rm $SAVENAME] }
  catch [exec touch $SAVENAME]
  set file [open "$SAVENAME" r+]
append USERPREF "{$drawfax}\ {$faxdir}\ {$faxin}\ {$faxout}\ {$faxdpi}\ {$printcmd}\ {$printsel}"
  puts $file $USERPREF
  close $file
}

################# END proc savevoice ##############################

proc play_audio {} {
global fnlist PCMDT tkvoicedir pvfsamples playwave voicedir voicein playPID
global userhome PBAMP audioDEV audioOST

  foreach i [.v.voice.list curselection] {
    set MESSAGE [lindex $fnlist $i]
    exec cat $MESSAGE | rmdtopvf | pvfamp -A $PBAMP | pvftowav > \
         $userhome/tkvoice.tmp 2>/dev/null
    if {$PCMDT == "wavplay"} {
      set playcmd "$tkvoicedir/bin/wavplay -M -d /dev/$audioDEV"
      set playPID [eval exec $playcmd $userhome/tkvoice.tmp > /dev/null 2>&1 &]
    } elseif {$PCMDT == "sox"} {
    set playPID [eval exec sox -t wav $userhome/tkvoice.tmp -t $audioOST /dev/$audioDEV > /dev/null 2>&1 &]
    } elseif { $playwave != ""} {
      set playPID [eval exec $playwave $userhome/tkvoice.tmp > /dev/null 2>&1 &]
    } else { tk_messageBox -icon error -type ok -title "tkVoice Play Audio" -message "An Error has occured while\nplaying Message!\nYou need to set a WAV play command:\nOptions -> Voice -> Audio"
  }
    exec touch $MESSAGE.played
    exec chmod 666 $MESSAGE.played
    set z [.v.voice.list get $i]
    set l [string length $z]
    if {$l>19} {
      set z [string range $z 2 $l ]
      set y "\x3E\x20"
      append t $y $z
      .v.voice.list delete $i
      .v.voice.list insert $i $t
    }
  }
}
######################## END proc play_audio ######################

proc stop_audio {} {
global playPID

if { $playPID != "" } {
    catch [exec kill -9 $playPID >/dev/null 2>&1]
    set playPID ""
   }
}
######################## END proc stop_audio ######################

proc record_g {} {
global recordwave recPID pvfsamples voicedir voiceout greeting RCMDT \
       tkvoicedir userhome recACT audioDEV audioOST

  if {$RCMDT == "wavrec"} {
    # artsd and wavrec do not work together so lets kill artsd:
    catch [exec ps -ef | grep artsd | grep -v grep | awk {{print $2}} \
           | xargs kill -9 ]
    # set recordcmd "$tkvoicedir/bin/wavrec -M -s $pvfsamples -t $rectime"
    # set recordcmd "$tkvoicedir/bin/wavrec -M -t $rectime"
    set recordcmd "$tkvoicedir/bin/wavrec -M -d /dev/$audioDEV"
    set recPID [eval exec $recordcmd $voicedir/$voiceout/$greeting.wav > /dev/null 2>&1 &]
    set recACT 1
  } elseif {$RCMDT == "sox"} {
    set recordcmd "sox -t $audioOST /dev/$audioDEV"
    set recPID [eval exec $recordcmd $voicedir/$voiceout/$greeting.wav > /dev/null 2>&1 &]
    set recACT 1
  } elseif { $recordwave != ""} {
    catch [eval exec $recordwave ]
  } else {tk_messageBox -icon error -type ok -title "tkVoice Record Greeting" -message "An Error has occured while recording Greeting!\nYou need to set a WAV record command:\nOptions -> Voice -> Audio"
  }
}
######################## END proc record_g ########################

proc record_gstop {} {
global recPID recACT

if { $recPID != "" } {
   # wait 2 second before actually stopping the recording
    after 2000
    catch [exec kill $recPID >/dev/null 2>&1]
    catch [exec kill -KILL $recPID >/dev/null 2>&1]
    set recACT 0
    set recPID ""
   }
}
######################## END proc stop_audio ######################

proc listen_g {} {
global playwave tkvoicedir voicedir voiceout greeting PCMDT audioOST audioDEV
if {$PCMDT == "wavplay"} {
    set playcmd "$tkvoicedir/bin/wavplay -d /dev/$audioDEV"
    catch [eval exec $playcmd $voicedir/$voiceout/$greeting.wav ]
     } elseif {$PCMDT == "sox"} {
    catch [eval exec sox -t wav $voicedir/$voiceout/$greeting.wav -t $audioOST /dev/$audioDEV > /dev/null 2>&1 &]
   } else {
    catch [eval exec $playwave $voicedir/$voiceout/$greeting.wav ]
   }
}
######################## END proc listen_g ########################

proc convert_g {} {
global MODEMTYPE MODEMCOMP pvfsamples userhome voicedir voiceout greeting vindex
   catch [exec cat $voicedir/$voiceout/$greeting.wav | wavtopvf \
              | pvfspeed -s $pvfsamples | pvftormd $MODEMTYPE $MODEMCOMP  \
              > $voicedir/$voiceout/$greeting ]
set zerotest ""
set zerotest [exec ls -l $voicedir/$voiceout/$greeting | awk {{print $5}}]
    if {$zerotest == 0} {
     tk_messageBox -icon error -type ok -title "tkVoice Convert Greeting" -message "An Error has occured while\nconverting WAV to RMD!"
    } else {
    if { [file isfile $voicedir/$voiceout/$vindex] == 0} {
       catch [exec touch $voicedir/$voiceout/$vindex]
       catch [exec chmod 666 $voicedir/$voiceout/$vindex]
       }	
    exec echo $greeting > $voicedir/$voiceout/$vindex
#    set indextest ""
#    catch {set file [open $voicedir/$voiceout/$vindex r+]}
#     while {[gets $file string] >= 0} {
#       append indextest "$string\ "
#      }
#     close $file
#     if {$indextest == ""} {
#        exec echo $greeting >> $voicedir/$voiceout/$vindex
#        } else {
#        set indexinsert 1
#          foreach x $indextest {
#          if {$x == $greeting} {
#             set indexinsert 0 }
#          }
#        if {$indexinsert == 1} {
#           exec echo $greeting >> $voicedir/$voiceout/$vindex } 
#        }
    }
}
######################## END proc convert_g #######################

proc delete_it {} {
global fnlist
  foreach i [lsort -integer -decreasing [.v.voice.list curselection]] {
    set MESSAGE [lindex $fnlist $i]
    exec rm -f $MESSAGE $MESSAGE.played
    set fnlist [lreplace $fnlist $i $i]
    .v.voice.list delete $i
  }
}
######################## END proc delete_it #######################

proc select_fax {} {
global tkvoicedir faxdir faxin faxdpi printcmd printsel fnlistfax
global userhome FAX PAGE PAGET tkVoice

foreach i [.f.fax.list curselection] {
    set tmp [lindex $fnlistfax $i]
# fax prefix char count
    set fpc [expr [string length $tmp]-4]
    set FAX [string range $tmp 0 $fpc]
    set a [eval exec ls [glob -nocomplain $FAX.??] | wc ]
    set b [string trim $a ]
    set c [string range $b 0 1]
     if {$c < 10} {
      set PAGET "0"
      append PAGET $c
      } else {
      set PAGET $c
      }
    set PAGE 01
 }
}
######################## END proc select_fax  #######################
proc delete_fax {} {
global fnlistfax
  foreach i [lsort -integer -decreasing [.f.fax.list curselection]] {
    set tmp [lindex $fnlistfax $i]
    set fpc [expr [string length $tmp]-4]
    set FAX [string range $tmp 0 $fpc]
    set DEL [eval exec ls [glob -nocomplain $FAX.??]]
  foreach x $DEL {
    exec rm -f $x
  }
    exec rm -f $FAX.01.viewed
    set fnlistfax [lreplace $fnlistfax $i $i]
    .f.fax.list delete $i
  }
}
######################## END proc delete_fax #######################


proc view_fax {} {
global tkvoicedir faxdir faxin faxdpi printcmd printsel fnlistfax
global userhome FAX PAGE PAGET tkVoice

select_fax

if {$FAX != "" } {
exec touch $FAX.$PAGE.viewed
exec chmod 666 $FAX.$PAGE.viewed

    foreach i [.f.fax.list curselection] {
    set z [.f.fax.list get $i]
    set l [string length $z]
        if {$l>19} {
        set z [string range $z 2 $l ]
        set y "\x3E\x20"
        append t $y $z
        .f.fax.list delete $i
        .f.fax.list insert $i $t
        }
    }
uplevel [list source [file join $tkvoicedir/TCL/tkviewfax.tcl]]
 }
}
######################## END proc view_fax  #######################

proc print_fax {} {
global tkvoicedir faxdir faxin faxdpi printcmd printsel fnlistfax
global userhome FAX PAGE PAGET tkVoice

select_fax
if {$FAX != "" } {
uplevel [list source [file join $tkvoicedir/TCL/tkvprintfax.tcl]]
 }
}
######################## END proc print_fax  #######################

proc get_files {} {
global voicedir voicein fnlist
  
# Each time get_files is run need to document the time:
 catch [ exec touch $voicedir/$voicein/.timestamp ]
 catch [ exec chmod 666 $voicedir/$voicein/.timestamp ]

 # clear the contents of listbox
 .v.voice.list delete 0 end
  set fnlist {}

 set vdlength [expr [string length $voicedir]-1]
 set test [eval exec ls -t [glob -nocomplain $voicedir/$voicein/*.rmd]]
    if {[string range $test 0 $vdlength] == $voicedir} {
 foreach n $test {
    set zerotest [exec ls -l $n | awk {{print $5}}]
    if {$zerotest == 0} {
    exec rm $n
    } else {
    set f [exec ls -l --full-time $n | awk {{print $6, $7, $8, $9, $10}}]
    set h [exec date -d $f "+* %a %b %e, %Y %l:%M%p  "]
    set g [exec ls $n | awk -F "-" {{print $4}} | awk -F "." {{print $1}}]
    if [string match O $g ] {
        set g "Not Available"
       } elseif [string match "" $g ] {
        set g "Not Available"
       } else {
	set acode [string range $g 0 2]
        set prefx [string range $g 3 5]
        set tailn [string range $g 6 9]
        set g "($acode)$prefx-$tailn"
       }
    set t ""
    append t $h $g
    lappend fnlist $n
    if { [file isfile $n.played] == 0} {
       append t " NEW"
    }
      .v.voice.list insert end $t
   }
  }
 }
}
######################## END proc get_files #######################
proc get_faxfiles {} {
global faxdir faxin fnlistfax
   
# Each time get_faxfiles is run need to document the time:
 catch [ exec touch $faxdir/$faxin/.timestamp ]
 catch [ exec chmod 666 $faxdir/$faxin/.timestamp ]

# clear the contents of listbox
 .f.fax.list delete 0 end
 set fnlistfax {}
 set vdlength [expr [string length $faxdir]-1]
 set test [eval exec ls -t [glob -nocomplain $faxdir/$faxin/*.01]]
    if {[string range $test 0 $vdlength] == $faxdir} {
 foreach n $test {
    set f [exec ls -l --full-time $n | awk {{print $6, $7, $8, $9, $10}}]
    set h [exec date -d $f "+* %a %b %e, %Y %l:%M%p  "]
#
# Grab the fax station id: length of $faxdir $faxin plus 12 chars
# 1 for slash and 12 char for fax mgetty naming convention:
#
# The file name format is somewhat tricky (reason behind it is that I have to
# create something unique without using mktemp(), because that would make
# it impossible to find out which pages belong to which fax). It is:
# 
# f<res><seq><line>[-<remote id>].<pagenr>
# 
# <res> is n or f, depending on the resolution of the fax. 
# <seq> is a sequence number, 7 digits wide, related to the reception time. 
# <line> are the last two letters of the tty device, e.g. `S1'.
# If the sending side specified a fax station id, it comes next, after a 
# leading dash (all blanks are replaced by dashes).
# Finally, after a dot, you'll see the page number.
    set ids [expr [string length $faxdir]+[string length $faxin]+13]
# Stn ID end point
# knock the: .<pagenr> off the end (minus 4chars)
# end point is 3chars plus 1 due to counting starts at 0
    set ide [expr [string length $n]-4]
    set g [string range $n $ids $ide]
    if [string match O $g ] {
        set g "Not Available"
       } elseif [string match "" $g ] {
        set g "Not Available"
       }
    set t ""
    append t $h $g
    lappend fnlistfax $n
    if { [file isfile $n.viewed] == 0} {
       append t " NEW"
    }
      .f.fax.list insert end $t
  }
 }
}
######################## END proc get_faxfiles #######################

proc refresh {} {
global drawvoice voicedir voicein vflag
global drawfax faxdir faxin

############ VOICE REFRESH ##################
 if {$drawvoice == 1} {
# Need to do this check or tkvoice will not start up.
  if {[winfo exists .v.voice.list]} {
  # .flag is touched each time a new message arrives
  set vdlength [expr [string length $voicedir]-1]
  set test [eval exec ls -t [glob -nocomplain $voicedir/$vflag]]
  if {[string range $test 0 $vdlength] == $voicedir} {
     if {[file exists $voicedir/$vflag] == 0} {
     set MSG "An Error has occured reading $voicedir/$vflag"
     puts $MSG
     } else {
#     set lastvmesg [file atime $voicedir/$vflag]
# Above line fails to update as the tcl "atime" only grabs access time
# I had to use the GNU extension %s in conjuction with ls --full-time
# as ls --full-time catches modification time
     set f [exec ls -l --full-time $test | awk {{print $6, $7, $8, $9, $10}}]
     set lastvmesg [exec date -d $f "+%s"]
     }
  }
  # .timestamp is touched each time the voice list is refreshed
  set lastvfresh [file atime $voicedir/$voicein/.timestamp]

  if {$lastvmesg >= $lastvfresh} {
     # Refresh the voice list
     get_files
     }
  }
 }
############ FAX REFRESH ##################
 if {$drawfax == 1} {
  # .timestamp is touched each time the voice list is refreshed
  if { [file exists $faxdir/$faxin/.timestamp] != 1} {
        catch [ exec touch $faxdir/$faxin/.timestamp ]
        catch [ exec chmod 666 $faxdir/$faxin/.timestamp ]
     }
  set lastffresh [file atime $faxdir/$faxin/.timestamp]

  set fdlength [expr [string length $faxdir]-1]
  set test [eval exec ls -t [glob -nocomplain $faxdir/$faxin/*.01]]
    if {[string range $test 0 $fdlength] == $faxdir} {
      foreach n $test {
        set f [exec ls -l --full-time $n | awk {{print $6, $7, $8, $9, $10}}]
        set lastfmesg [exec date -d $f "+%s"]
        if {$lastfmesg >= $lastffresh} {
           # Refresh the voice list
           get_faxfiles
        }
      }
    }
 }
  # Reschedule ourselves 10 seconds in the future
  after 10000 refresh
}
# now start refresh proc (kind of puts itself in background)
refresh 

######################## END proc updatefiles #####################

##############################################
# Under Greeting
##############################################
# Play Greeting
proc play_g {} {
global playwave tkvoicedir voicedir voiceout greeting playPID PCMDT
global userhome audioOST audioDEV

set zerotest ""
set zerotest [exec ls -l $voicedir/$voiceout/$greeting | awk {{print $5}}]
  if {$zerotest == 0} {
     tk_messageBox -icon error -type ok -title "tkVoice Play Greeting" -message "An Error has occured while\nplaying Greeting!\nFile is empty!"
  } else {

  exec rmdtopvf $voicedir/$voiceout/$greeting | pvftowav \
         > $userhome/tkvoice.tmp 2>/dev/null

    if {$PCMDT == "wavplay"} {
    set playcmd "$tkvoicedir/bin/wavplay -M -d /dev/$audioDEV"
    set playPID [eval exec $playcmd $userhome/tkvoice.tmp > /dev/null 2>&1 &]
     } elseif {$PCMDT == "sox"} {
    set playPID [eval exec sox -t wav $userhome/tkvoice.tmp -t $audioOST /dev/$audioDEV > /dev/null 2>&1 &]
     } else {
    set playPID [eval exec $playwave $userhome/tkvoice.tmp > /dev/null 2>&1 &]
     }
  tk_messageBox -icon info -type ok -title "tkVoice Out-Going Greeting" -message "Now listening to your:\n\nOUT-GOING GREETING"
  }
}
######################## END proc play_g ##########################

#---------------------------------------------
# Record Greeting
proc record {} {
global tkVoice tkvoicedir voicedir voiceout greeting MODEMTYPE MODEMCOMP \
       recordwave rectime
  uplevel [list source [file join $tkvoicedir/TCL/tkvrecord.tcl]]
}
######################## END proc record ##########################


##############################################
# Under Options
##############################################
# Path setup
proc voicesetup {} {
global tkVoice tkvoicedir voicedir greeting
 uplevel [list source [file join $tkvoicedir/TCL/tkvsetupvoice.tcl]]
}
######################## END proc  ###########################
#---------------------------------------------
# Modem setup
proc modem {} {
global tkVoice tkvoicedir MODEMTYPE MODEMCOMP pvfsamples custpvfs
if { $pvfsamples == 7200 } {
     set custpvfs 0
   } elseif { $pvfsamples == 8000 } {
     set custpvfs 0
   } elseif { $pvfsamples == 9600 } {
     set custpvfs 0
   } else {
     set custpvfs 1
}
 uplevel [list source [file join $tkvoicedir/TCL/tkvmodem.tcl]]
}
######################## END proc modem ###########################
#---------------------------------------------
# Audio setup
proc audio {} {
global tkVoice tkvoicedir playwave recordwave PCMDT RCMDT audioDEV audioOST
 uplevel [list source [file join $tkvoicedir/TCL/tkvaudio.tcl]]
}
######################## END proc audio ###########################
# FAX setup
proc faxsetup {} {
global tkVoice tkvoicedir drawfax faxdir faxin faxout faxdpi printcmd printsel
 uplevel [list source [file join $tkvoicedir/TCL/tkvsetupfax.tcl]]
}
######################## END proc  ###########################
# setup printer
proc printsetup {} {
global tkVoice tkvoicedir drawfax faxdir faxin faxout faxdpi printcmd printsel
 uplevel [list source [file join $tkvoicedir/TCL/tkvsetupprint.tcl]]
}
######################## END proc  ###########################
#---------------------------------------------
#---------------------------------------------

##############################################
# Under Help
proc faq {} {
global tkVoice tkvoicedir
  uplevel [list source [file join $tkvoicedir/TCL/tkvfaq.tcl]]
}

proc readme {} {
global tkVoice tkvoicedir
  uplevel [list source [file join $tkvoicedir/TCL/tkvreadme.tcl]]
}

proc aboutBox {} {
global TKVREV TKVDATE tkVoice tkvoicedir
  uplevel [list source [file join $tkvoicedir/TCL/tkvabout.tcl]]
}
######################## END proc aboutBox ########################

# positionWindow --
# Arguments:
# w -           The name of the window to position.
 
proc positionWindow w {
    wm geometry $w +300+300
}
##############################################
##### End of subs
##############################################
##### Start of Frames
##############################################

# Create the menu bar at the top of the window.
 
frame .menu -relief raised -borderwidth 2 
pack .menu -side top -fill x
 
# Under the File button
 
menubutton .menu.file -text File -menu .menu.file.m -underline 0
menu .menu.file.m -tearoff 0
.menu.file.m add command -label "Delete Selected" -underline 0 \
        -command "delete_it"
.menu.file.m add command -label "Refresh List" -underline 0 \
        -command "get_files"
.menu.file.m add command -label "Stop Audio" -underline 0 \
        -command "stop_audio"
.menu.file.m add command -label "Play Selected" -underline 0 \
        -command "play_audio"
.menu.file.m add separator
.menu.file.m add command -label "Exit" -underline 1 \
        -command "destroy ."

# Under the GREETING button
 
menubutton .menu.greeting -text Greeting -menu .menu.greeting.m -underline 0
menu .menu.greeting.m -tearoff 0
.menu.greeting.m add command -label "Listen to Greeting" -underline 0 \
        -command {play_g}
.menu.greeting.m add command -label "Record Greeting" -underline 0 \
        -command {record}

# Under the Option button
 
menubutton .menu.option -text Options -menu .menu.option.m -underline 0
menu .menu.option.m
.menu.option.m add cascade -label "VOICE" \
	-menu .menu.option.voice -underline 0
.menu.option.m add cascade -label "FAX" \
	-menu .menu.option.fax -underline 0

menu .menu.option.voice -tearoff 0
.menu.option.voice add command -label "Setup Voice" -underline 2 \
        -command {voicesetup}
.menu.option.voice add command -label "Setup Modem" -underline 2 \
        -command {modem}
.menu.option.voice add command -label "Setup Audio" -underline 2 \
        -command {audio}

menu .menu.option.fax -tearoff 0
.menu.option.fax add command -label "Setup FAX" -underline 2 \
        -command {faxsetup}
.menu.option.fax add command -label "Setup PRINTER" -underline 2 \
        -command {printsetup}

# Under the Help button
 
menubutton .menu.help -text Help -menu .menu.help.m -underline 0
menu .menu.help.m -tearoff 0
.menu.help.m add command -label "FAQ" -underline 0 \
        -command {faq}
.menu.help.m add command -label "README" -underline 0 \
        -command {readme}
.menu.help.m add command -label "About tkVOICE" -underline 0 \
        -command {aboutBox}
 
pack .menu.file .menu.greeting .menu.option -side left
pack .menu.help -side right
 
# GIF frame on left of list
frame .gif -relief raised -borderwidth 2
pack .gif -side top -fill x

# tkvoice image
catch {image delete tkvoice}
image create photo tkvoice -file [file join $tkvoicedir/image/tkvoice.gif]
label .gif.tkvoice -image tkvoice -bd 1 -relief sunken

catch {image delete linux}
image create photo linux -file [file join $tkvoicedir/image/linux.gif]
label .gif.linux -image linux -bd 1 -relief sunken

catch {image delete phone}
image create photo phone -file [file join $tkvoicedir/image/phone.gif]
label .gif.phone -image phone -bd 1 -relief sunken

catch {image delete penguin}
image create photo penguin -file [file join $tkvoicedir/image/penguin.gif]
label .gif.penguin -image penguin -bd 1 -relief sunken

pack .gif.phone -side left 
pack .gif.tkvoice -side left -expand 1 -fill x
pack .gif.linux -side right 
pack .gif.penguin -side right

######### MAIN VOICE FRAME STARTS HERE ##############
frame .v 
frame .v.voice
label .v.voice.msg -font {times 18} -justify center -text "VOICE Messages"
listbox .v.voice.list -relief sunken -font {fixed 14} -width 46 -height 5 \
	        -yscrollcommand ".v.voice.scroll set" -background $bgcolor
scrollbar .v.voice.scroll -command ".v.voice.list yview"

frame .v.button
image create photo exit -file [file join $tkvoicedir/image/exit.gif]
button .v.button.quit  -image exit -anchor center -command "destroy ."
image create photo play -file [file join $tkvoicedir/image/play.gif]
button .v.button.playa -text "Play" -image play -anchor center -command play_audio
image create photo stop -file [file join $tkvoicedir/image/stop.gif]
button .v.button.stop -text "Stop" -image stop -anchor center -command stop_audio
image create photo reload -file [file join $tkvoicedir/image/reload.gif]
button .v.button.reload -text "Refresh" -image reload -anchor center -command "get_files"
image create photo del -file [file join $tkvoicedir/image/del.gif]
button .v.button.del   -image del -anchor center -command delete_it
######### MAIN VOICE FRAME ENDS HERE ##############

######### MAIN FAX FRAME STARTS HERE ##############
frame .f
frame .f.fax
label .f.fax.msg -font {times 18} -justify center -text "FAX Messages"
#                -background gray90 -relief sunken
listbox .f.fax.list -relief sunken -font {fixed 14} -width 46 -height 5 \
               -yscrollcommand ".f.fax.scroll set" -background $bgcolor
scrollbar .f.fax.scroll -command ".f.fax.list yview"

frame .f.button
button .f.button.quit -width 7  -text "Quit" -anchor center -command "destroy ."
button .f.button.view   -width 7 -text "View" -anchor center -command "view_fax"
button .f.button.print  -width 7 -text "Print" -anchor center -command "print_fax"
button .f.button.reload -width 7 -text "Refresh" -anchor center -command "get_faxfiles"
button .f.button.del    -width 7 -text "Delete"  -anchor center -command "delete_fax"
######### MAIN FAX FRAME ENDS HERE ##############

if {$drawvoice == 1} {
  pack .v -padx 3 -pady 3
  pack .v.voice.msg -side top
  pack .v.voice -side top
  pack .v.voice.list -side left 
  pack .v.voice.scroll -side left -fill y -expand 1
  pack .v.button -side top -fill x
  pack .v.button.quit  -side right -expand 1 -fill x -padx 3 -pady 3
  pack .v.button.playa -side right -expand 1 -fill x -padx 3 -pady 3
  pack .v.button.stop -side right -expand 1 -fill x -padx 3 -pady 3
  pack .v.button.reload   -side right -expand 1 -fill x -padx 3 -pady 3
  pack .v.button.del   -side right -expand 1 -fill x -padx 3 -pady 3
  get_files
  bind .v.voice.list <Double-Button-1> play_audio
}

if {$drawfax == 1} {
  pack .f -padx 3 -pady 3
  pack .f.fax.msg -side top
  pack .f.fax -side top
  pack .f.fax.list -side left
  pack .f.fax.scroll -side left -fill y -expand 1
  pack .f.button -side bottom -fill x
  pack .f.button.quit  -side right -expand 1 -fill x -padx 3 -pady 3
  pack .f.button.view -side right -expand 1 -fill x -padx 3 -pady 3
  pack .f.button.print -side right -expand 1 -fill x -padx 3 -pady 3
  pack .f.button.reload   -side right -expand 1 -fill x -padx 3 -pady 3
  pack .f.button.del   -side right -expand 1 -fill x -padx 3 -pady 3
  get_faxfiles
  bind .f.fax.list <Double-Button-1> view_fax
}


wm protocol . WM_DELETE_WINDOW "destroy ."
wm iconbitmap . @$tkvoicedir/image/icon

tkwait window .
