
set LogFile [file join $env(HOME) "gosh.log"]

proc ViewLogFile {} {
    global LogFile Log LogView LogText LogXScroll LogYScroll LogStream
    
    set Log .log
    destroy $Log
    toplevel $Log -height 5
    wm title $Log "GOBLIN Log File (gosh.log)"
     
    set LogButtons $Log.buttons
    frame $LogButtons
        button $LogButtons.reload -text Reload -command {
            LoadLogFile $LogText $LogFile
            $LogText see end
        }

        button $LogButtons.done -text Done -command DestroyLogFile

        pack $LogButtons.done $LogButtons.reload \
            -side right -fill x -padx 3m -pady 1m
    
    pack $LogButtons -side bottom -padx 3m -pady 2m
    
    set LogView $Log.view
    frame $LogView
    pack $LogView -side top -fill both -expand yes -padx 1m -pady 1m

    set LogText $LogView.text
    set LogXScroll $LogView.xscroll
    set LogYScroll $LogView.yscroll
    text $LogText -bg ivory \
        -font -*-courier-medium-r-normal--*-120-*-*-p-*-*-* \
	    -relief sunken -borderwidth 2 \
	    -xscrollcommand "$LogXScroll set" \
	    -yscrollcommand "$LogYScroll set"

    scrollbar $LogXScroll -orient horiz -command "$LogText xview" -width 3.5m
    scrollbar $LogYScroll -command "$LogText yview" -width 3.5m

    grid $LogText -in $LogView \
        -row 0 -column 0 -rowspan 1 -columnspan 1 -sticky news
    grid $LogXScroll \
        -row 1 -column 0 -rowspan 1 -columnspan 1 -sticky news
    grid $LogYScroll \
        -row 0 -column 1 -rowspan 1 -columnspan 1 -sticky news
    grid rowconfig    $LogView 0 -weight 1 -minsize 0
    grid columnconfig $LogView 0 -weight 1 -minsize 0
    
    LoadLogFile $LogText $LogFile

    wm protocol $Log WM_DELETE_WINDOW DestroyLogFile
}

proc DestroyLogFile {} {
    global LogStream Log
    fileevent $LogStream readable {}
    close $LogStream
    destroy $Log
}

proc LoadLogFile {text textFile} {
    global LogStream LogText
    $text delete 1.0 end
    set LogStream [open "| cat < $textFile"]
    while {![eof $LogStream] && ![fblocked $LogStream]} {
        $LogText insert end [read $LogStream 1000]
    }

    fconfigure $LogStream -blocking 0
    # fileevent $LogStream readable LoadLogEntries
}

proc LoadLogEntries {} {
    global LogStream LogText
    if {![fblocked $LogStream]} {
        $LogText insert end [read $LogStream 1000]
        $LogText see end
    }
}

ViewLogFile
