
# This code is shared by all the ICEM CFD GUI's.
#
# Copyright (c) 1993 - 1995 Pacific Marketing and Consulting, Inc,
#       and ICEM Systems, GmbH.  All rights reserved.
# Author:  Wayne A. Christopher, wayne@icemcfd.com

# Call this routine to set up the file handler.

catch {unset tail_pending_ids}
catch {unset tail_rundown_ids}

proc tail_dashf {fp cmd} {
    global tail_pending_ids tail_rundown_ids
    
    set tail_pending_ids($fp) ""
    set tail_rundown_ids($fp) 0
    
    fileevent $fp readable [list tail_dashf_proc $fp $cmd]
}

proc tail_dashf_proc {fp cmd} {
    global tail_pending_ids tail_rundown_ids
    
    # don't allow a fileevent that is running down to do anything
    
    if $tail_rundown_ids($fp) { return }
    
    # Reset the error flag on the file.
    seek $fp 0 current

    if {[catch {gets $fp} line] || [catch {eof $fp}]} {
	
	# need to cancel both the potential after command along with
	# the fileevent.
	
	tail_dashf_cancel $fp	
	return
    }
    
    # no after pending at this point
    
    set tail_pending_ids($fp) ""
    
    # Will reenable it later
    fileevent $fp readable ""
    
    # read all the lines and execute them right away
    set n_lines 0
    while {![eof $fp]} {
	incr n_lines
	catch {uplevel \#0 $cmd [list $line]}
	if {[catch {gets $fp} line] || [catch {eof $fp}]} {
	    tail_dashf_cancel $fp	
	    return
	}
    }
   
    if {  $n_lines == 0 } {
	set line "<empty line>"
	catch {uplevel \#0 $cmd [list $line]}
    }
    set tail_pending_ids($fp) \
	[after 100 [list catch [list fileevent $fp readable [list tail_dashf_proc $fp $cmd]]]]
}

proc tail_dashf_cancel {fp} {
    global tail_rundown_ids tail_pending_ids
    
    # Not quite correct -- Need a semaphore mechanism.  This next statement
    # should be in a critical section
    
    set tail_rundown_ids($fp) 1
    
    # cancel any file event
    
    catch {fileevent $fp readable ""} ;# could be already closed ...
    
    # cancel any pending "after" command
    
    if {$tail_pending_ids($fp) != ""} {
	after cancel $tail_pending_ids($fp)
	set tail_pending_ids($fp) ""
    }
}
