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

# agentsummary file
#
# This program reads a file containing performance metrics from a collection
# of agents involved in a build.  It combines the statistics from the
# different agents and prints out a summary.
#
# For example:
#   cmtool --cm $EMAKE_CM runAgentCmd "session performance 9" > 9.sessionperf
#   agentsummary < 9.sessionperf > 9.agentsum
#
# Copyright (c) 2008-2026 Electric Cloud, Inc.
# All rights reserved.

# The following global variables are used to collect data while the file
# is being read.  All arrays are indexed by node number.  Anything with the
# prefix "total" refers to a sum across nodes.

# Information from the "Build information" section:
set buildId {}
array set agentEntries {}
set startTime {}
set endTime {}
array set time {}
array set jobs {}
array set commands {}
array set agentTimes {}
array set userCPUSeconds {}
array set systemCPUSeconds {}
array set agentVersions {}
array set efsVersions {}

# Information from the "Network data compression" section:
array set compressSeconds {}
array set compressInputBytes {}
array set compressOutputBytes {}
array set decompressSeconds {}
array set decompressInputBytes {}
array set decompressOutputBytes {}

# Information from the "File data statistics" section:
array set cacheFiles {}
array set cacheMbytes {}
array set cacheRenamedFiles {}
array set cacheRenamedMbytes {}
array set cacheMigratedFiles {}
array set cacheMigratedMbytes {}
array set cacheMemoryReads {}
array set cacheMemoryMbytes {}
array set cacheBackingReads {}
array set cacheBackingMbytes {}
array set cacheAvgWorkingSetBuffers {}
array set cacheAvgWorkingSetMbytes {}
array set cacheMaxWorkingSetBuffers {}
array set cacheMaxWorkingSetMbytes {}
array set cacheMaxWorkingSetCommand {}

# Information from the "Caching" section:
array set lookupsToEfs {}
array set lookupsToEmake {}
array set readsToEfs {}
array set readsToEmake {}
array set writesToEfs {}
array set writesToEmake {}
array set scansToEfs {}
array set scansToEmake {}
array set efsPageAccesses {}
array set efsPageMisses {}
array set efsReaddirAccesses {}
array set efsReaddirMisses {}
array set groupFiles {}
array set groupMBytes {}
array set groupFlushes {}
array set efsNameTableAccesses {}
array set efsNameTableTests {}

# Information from the "Per-job statistics" section:
array set jobFileOpens {}
array set jobFailedLookups {}
array set jobEmakeRequests {}
array set jobBytesRead {}
array set jobDirectoryClears {}
array set jobBytesTotalRead {}
array set jobBytesTotalWrite {}

# Information from the "EFS buffer caching statistics" section:
array set jobRemoteMaps {}
array set jobPagesToAgent {}
array set jobPagesFromAgent {}
array set jobPageCacheHits {}
array set jobPageCacheMisses {}
array set jobPagesDiscarded {}

# Information from the "Agent-to-agent file transfers" section:
array set incomingA2ARequests {}
array set incomingA2ARejections {}
array set outgoingA2ARequests {}
array set outgoingA2ARejections {}
array set outgoingA2AAttempts {}
array set outgoingA2AResends {}

# Information from the "Windows EFS operations" section:
set gotWindowsEFSData 0

# Information from the "Idle intervals" section:
array set idleIntervalNames {}
array set idleIntervalCountBig {}
array set idleIntervalTimeBig {}
set bigLabel {}

#---------------------------------------------------------------------------
# max
#
#       Find the largest of a set of numerical values.
#
# Results:
#       The result is the largest value in the set, or zero if the set is
#       empty.
#
# Arguments:
#       names -         A list of values to compare.
#---------------------------------------------------------------------------

proc max {values} {
    set max 0
    foreach value $values {
        if { $value > $max } {
            set max $value
        }
    }
    return $max
}

#---------------------------------------------------------------------------
# maxLength
#
#       Find the length of the longest string in "names".
#
# Results:
#       The result is the length of the longest string, or 0 if the set is
#       empty.
#
# Arguments:
#       names -         A list of strings to compare.
#---------------------------------------------------------------------------

proc maxLength {names} {
    set max 0
    foreach name $names {
        set len [string length $name]
        if { $len > $max } {
            set max $len
        }
    }
    return $max
}

#---------------------------------------------------------------------------
# sumArray
#
#       Given an array of numeric values, this procedure computes the
#       total of all the values.
#
# Results:
#       The result is the sum of all of the values in array "name".
#       If the values are all integers than the sum is an integer; if
#       any values are floating-point, then the sum is floating-point.
#
# Side effects:
#       None.
#
# Arguments:
#       name -              Name of an array in the caller's scope.  Element
#                           names are arbitrary; values must be integers or
#                           floating-point numbers.
#---------------------------------------------------------------------------

proc sumArray {name {pattern *}} {
    upvar $name a
    set result 0
    foreach i [array names a $pattern] {
        set result [expr {$result + $a($i)}]
    }
    return $result
}

proc sumList {values} {
    set result 0
    foreach value $values {
        set result [expr {$result + $value}]
    }
    return $result
}

#---------------------------------------------------------------------------
# avgArray
#
#       Given an array of numeric values, this procedure computes the
#       average of all the values.
#
# Results:
#       The result is the average of all of the values in array "name",
#       in floating-point form.
#
# Side effects:
#       None.
#
# Arguments:
#       name -              Name of an array in the caller's scope.  Element
#                           names are arbitrary; values must be integers or
#                           floating-point numbers.
#---------------------------------------------------------------------------

proc avgArray {name} {
    upvar $name a
    set result 0.0
    foreach i [array names a] {
        set result [expr {$result + $a($i)}]
    }
    return [expr {$result/[array size a]}]
}

#---------------------------------------------------------------------------
# maxArray
#
#       Given an array of numeric values, this procedure returns the
#       largest value in the array.
#
# Results:
#       The result is the largest of the values in array "name".
#       The name of the largest element is also returned, if the
#       "element" argument is specified.
#
# Side effects:
#       None.
#
# Arguments:
#       name -              Name of an array in the caller's scope.  Element
#                           names are arbitrary; values must be integers or
#                           floating-point numbers.
#       element -           If nonempty, gives the name of a variable in the
#                           caller's scope.  This variable will be filled in
#                           with the name of the largest element (empty
#                           string if the array is empty)
#---------------------------------------------------------------------------

proc maxArray {name {element {}}} {
    upvar $name a
    set result {}
    set name {}
    foreach i [array names a] {
        if {($result == "") || ($result < $a($i))} {
            set result $a($i)
            set name $i
        }
    }
    if {$element != ""} {
        uplevel set $element $name
    }
    return $result
}

#---------------------------------------------------------------------------
# minArray
#
#       Given an array of numeric values, this procedure returns the
#       smallest value in the array.
#
# Results:
#       The result is the smallest of the values in array "name".
#
# Side effects:
#       None.
#
# Arguments:
#       name -              Name of an array in the caller's scope.  Element
#                           names are arbitrary; values must be integers or
#                           floating-point numbers.
#---------------------------------------------------------------------------

proc minArray {name} {
    upvar $name a
    set result {}
    foreach i [array names a] {
        if {($result == "") || ($result > $a($i))} {
            set result $a($i)
        }
    }
    return $result
}

#---------------------------------------------------------------------------
# findLine
#
#       Read from a file until a particular line is encountered
#
# Results:
#       None.
#
# Side effects:
#       Data is read from "f" until either the end of the file for a line
#       exactly matching "line".  The matching line is read and discarded.
#
# Arguments:
#       f -                 Open file from which to read.
#       desired -           Desired line.
#---------------------------------------------------------------------------

proc findLine {f desired} {
    while {[gets $f line] != -1} {
        if {[string compare $line $desired] == 0} {
            break
        }
    }
}

#---------------------------------------------------------------------------
# The procedures below are utilities that format the contents of an
# array in various ways (typically an overall number followed by
# an individual value for each agent).
#---------------------------------------------------------------------------

proc formatAverageAndValues {name format} {
    upvar $name a
    set result ""
    append result [format $format [avgArray a]] " ("
    set length [array size a]
    for {set i 0} {$i < $length} {incr i} {
        append result [format $format $a($i)]
    }
    if {$length > 0} {
        append result ")"
    }
    return $result
}

proc formatSumAndValues {name format} {
    upvar $name a
    set result ""
    append result [format $format [sumArray a]] " ("
    set length [array size a]
    for {set i 0} {$i < $length} {incr i} {
        append result [format $format $a($i)]
    }
    if {$length > 0} {
        append result ")"
    }
    return $result
}

proc formatPercents {numerators denominators} {
    upvar $numerators a
    upvar $denominators b
    set result ""
    set length [array size a]
    for {set i 0} {$i < $length} {incr i} {
        set percent [expr {100.0 * $a($i) / $b($i)}]
        append result [format "%5.1f" $percent]
    }
    return $result
}

#---------------------------------------------------------------------------
# The procedures below are utilities for handling division and percentage
# computation in the face of 0 denominators.  In each case, if the
# denominator is 0 then 0 is returned; otherwise a quotient or percentage
# is returned.
#---------------------------------------------------------------------------

proc divide {top bottom} {
    if {$bottom == 0} {
        return 0.0
    }
    return [expr {double($top)/$bottom}]
}

proc percent {top bottom} {
    if {$bottom == 0} {
        return 0.0
    }
    return [expr {100.0*$top/$bottom}]
}

#----------------------------------------------------------------------------
# update_overall_time_usage
#
#       Add data from the "Overall time usage" section.
#----------------------------------------------------------------------------

proc update_overall_time_usage {agentNum line} {
    if {![regexp {^ *([^:]*): *([^s]*)s.*\), *([0-9]+) intvls}\
              $line --> name seconds intervals]} {
        if {![regexp {^ *([^:]*): *([^s]*)s}\
                  $line --> name seconds]} {
            return false
        }
        set intervals 0
    }

    # Sanitize the name so we can use it easily as an array key.

    set cleanname [string tolower [string map {" " _} $name]]

    # If this is the first time we've seen this timer, record the human-readable
    # form of the name, and record the position of the timer relative to the other
    # timers.

    if { ![info exists ::overallTimerName($cleanname)] } {
        set ::overallTimerName($cleanname) $name
        lappend ::overallTimers $cleanname
    }

    # Save the seconds and intervals recorded by this agent for this timer.

    lappend ::overallTimer($cleanname) $seconds
    lappend ::overallTimerIntervals($cleanname) $intervals
    return false
}

#----------------------------------------------------------------------------
# summarize_overall_time_usage
#
#       Emit summary information for the "Overall time usage" section.
#----------------------------------------------------------------------------

proc summarize_overall_time_usage {} {
    puts "\nOverall time usage:"

    # Swizzle the timer name for "version updates" to be "VFS updates".

    set ::overallTimerName(ver_updates) "VFS updates"

    foreach timer $::overallTimers {
        set total [sumList $::overallTimer($timer)]
        set percent [percent $total $::totalTime]
        set intervals [sumList $::overallTimerIntervals($timer)]
        puts -nonewline [format {  %-20s %8.2fs (%4.1f%%)}\
                $::overallTimerName($timer): $total $percent]
        if {$intervals > 0} {
            puts [format {%9d intvls, avg %7.1fms} $intervals\
                    [expr {(1000.0*$total)/$intervals}]]
        } else {
            puts ""
        }
    }
}

#----------------------------------------------------------------------------
# update_emake_request_timers
#
#       Add data from the "Emake request timers" section.
#----------------------------------------------------------------------------

proc update_emake_request_timers {agentNum line} {
    global emakeRequestTimer emakeRequestTimers emakeRequestTimerIntervals

    if {[gets $::input line2] == -1} {
        return false
    }
    if {![regexp {^ *([^:]*): *([^s]*)s.*\), *([0-9]+) intvls}\
              $line$line2 --> name seconds intervals]} {
        return false
    }
    if { ![info exists emakeRequestTimer($name)] } {
        lappend emakeRequestTimers $name
    }
    lappend emakeRequestTimer($name) $seconds
    lappend emakeRequestTimerIntervals($name) $intervals
    return false
}

#----------------------------------------------------------------------------
# summarize_emake_request_timers
#
#       Emit summary information for the "Emake request timers" section.
#----------------------------------------------------------------------------

proc summarize_emake_request_timers {} {
    global emakeRequestTimer emakeRequestTimers emakeRequestTimerIntervals
    global totalTime
    
    puts "\nEmake request timers:"
    foreach timer $emakeRequestTimers {
        set total [sumList $emakeRequestTimer($timer)]
        set pct [percent $total $totalTime]
        set intervals [sumList $emakeRequestTimerIntervals($timer)]
        puts -nonewline [format {  %-40s %8.2fs (%4.1f%%)} $timer $total $pct]
        if { $intervals > 0 } {
            puts [format {%9d intvls} $intervals]
        } else {
            puts ""
        }
    }
}

#----------------------------------------------------------------------------
# update_registry
#
#       Add data from the "Registry" section.
#----------------------------------------------------------------------------

proc update_registry {agentNum line} {
    global registry
    if {[regexp {^ *([^:]*): *([0-9]*)} $line --> tag count]} {
        if {$tag == "User opens"} {
            lappend registry(opens) $count
        } elseif {$tag == "Remapped opens"} {
            lappend registry(remapped) $count
        } elseif {$tag == "Get key requests"} {
            lappend registry(request) $count
        }
    }
    return false
}

proc summarize_registry {} {
    global registry

    if { ![info exists registry] || [llength $registry(opens)] == 0 } {
        return
    }
    puts "\nRegistry:"
    set total [sumList $registry(opens)]
    puts [format {  User opens: %d} $total]
    set total [sumList $registry(remapped)]
    puts [format {  Remapped opens: %d} $total]
    set total2 [sumList $registry(request)]
    puts [format {  Get key requests: %d (%.1f%%)} $total2 \
              [percent $total2 $total]]
}

#----------------------------------------------------------------------------
# update_bandwidth
#
#       Add data from the "Bandwidth" section.
#----------------------------------------------------------------------------
    
proc update_bandwidth {agentNum line} {
    global bandwidth bandwidthActive bandwidthSubsection bandwidthTypes bandwidthLabel

    if {[regexp {^( *)([^:]*): *([^ ]*) MB, *([^ ]*) MB/s active,\
                     *([^ ]*) MB} $line --> level tag mbytes active overall]} {
        if { $level == "    " } {
            set tmptag "${bandwidthSubsection} $tag"
            set tag "  $tag"
        } else {
            set tmptag $tag
        }
        set cleantag [string tolower [string map {" " _} "$tmptag"]]
        if { ![info exists bandwidthLabel($cleantag)] } {
            set bandwidthLabel($cleantag) $tag
            lappend bandwidthTypes $cleantag
        }

        lappend bandwidth($cleantag) $mbytes
        lappend bandwidthActive($cleantag) [divide $mbytes $active]
    } elseif {[regexp {^ *EFS disk ([^ ]+)} $line --> direction]} {
        set bandwidthSubsection "EFS disk $direction"
        if { ![info exists bandwidthLabel($bandwidthSubsection)] } {
            set bandwidthLabel($bandwidthSubsection) $bandwidthSubsection
            lappend bandwidthTypes $bandwidthSubsection
        }
    }
    return false
}

proc summarize_bandwidth {} {
    global bandwidth bandwidthActive bandwidthLabel bandwidthTypes
    global elapsedTime

    puts "\nBandwidth:"
    foreach type $bandwidthTypes {
        if { ![info exists bandwidth($type)] } {
            puts "  $type"
            continue
        }
        

        set mBytes [sumList $bandwidth($type)]
        set activeTime [sumList $bandwidthActive($type)]
        puts [format {  %-20s %8.1f MB, %5.1f MB/s active, %5.1f MB/s overall} \
                  $bandwidthLabel($type): \
                  $mBytes [divide $mBytes $activeTime] \
                  [divide $mBytes $elapsedTime]]
    }   
}

proc summarize_active_agents {} {
    global bandwidthActive elapsedTime
    puts "\nAverage # active agents:"
    foreach {name label} {
        network_from_emake              "Receiving from emake:   "
        network_to_emake                "Sending to emake:       "
        network_from_agents             "Receiving from agents:  "
        network_to_agents               "Sending to agents:      "
        small_files                     "Receiving small files:  "
        medium_files                    "Receiving medium files: "
        large_files                     "Receiving large files:  "
    } {
        set activeTime [sumList $bandwidthActive($name)]
        puts "  $label [format {%4.1f} [divide $activeTime $elapsedTime]]"
    }
}

#----------------------------------------------------------------------------
# update_network_data_compression
#
#       Add data from the "Network data compression" section.
#----------------------------------------------------------------------------

proc update_network_data_compression {agentNum line} {
    if {[regexp {Compression time: *([0-9.]*)s} $line --> seconds]} {
        set ::compressSeconds($agentNum) $seconds
    }
    if {[regexp {Compression efficiency:[^\(]*\(([0-9.]*) MB =>\
                     ([0-9.]*) MB} $line --> in out]} {
        set ::compressInputBytes($agentNum) $in
        set ::compressOutputBytes($agentNum) $out
    }
    if {[regexp {Decompression time: *([0-9.]*)s} $line --> seconds]} {
        set ::decompressSeconds($agentNum) $seconds
    }
    if {[regexp {Decompression efficiency:[^\(]*\(([0-9.]*) MB =>\
                     ([0-9.]*) MB} $line --> in out]} {
        set ::decompressInputBytes($agentNum) $in
        set ::decompressOutputBytes($agentNum) $out
    }
    return false
}

proc summarize_network_data_compression {} {
    global totalTime

    puts "\nNetwork data compression:"
    set seconds [sumArray ::compressSeconds]
    set in [sumArray ::compressInputBytes]
    set out [sumArray ::compressOutputBytes]
    puts [format "  Compression time:         %.3fs (%.1f%%)" $seconds\
              [percent $seconds $totalTime]]
    puts [format "  Compression speed:        %.2f MB/s" [divide $in $seconds]]
    puts [format "  Compression efficiency:   %.1fx (%.1f MB => %.1f MB)" \
              [divide $in $out] $in $out]
    set seconds [sumArray ::decompressSeconds]
    set in [sumArray ::decompressInputBytes]
    set out [sumArray ::decompressOutputBytes]
    puts [format "  Decompression time:       %.3fs (%.1f%%)" $seconds\
              [percent $seconds $totalTime]]
    puts [format "  Decompression speed:      %.2f MB/s" \
              [divide $out $seconds]]
    puts [format "  Decompression efficiency: %.1fx (%.1f MB => %.1f MB)" \
              [divide $out $in] $in $out]
}

#----------------------------------------------------------------------------
# update_file_data_statistics
#
#       Add data from the "File data statistics" section.
#----------------------------------------------------------------------------

proc update_file_data_statistics {agentNum line} {
    if {[regexp {Disk cache size: *([0-9.]*) files,\
                     ([0-9.]*) MB} $line --> files mbytes]} {
        set ::cacheFiles($agentNum) $files
        set ::cacheMbytes($agentNum) $mbytes
    }
    if {[regexp {Backing files renamed: *([0-9.]*) files,\
                     ([0-9.]*) MB} $line --> files mbytes]} {
        set ::cacheRenamedFiles($agentNum) $files
        set ::cacheRenamedMbytes($agentNum) $mbytes
    }
    if {[regexp {Migrated to disk: *([0-9.]*) files,\
                     ([0-9.]*) MB} $line --> files mbytes]} {
        set ::cacheMigratedFiles($agentNum) $files
        set ::cacheMigratedMbytes($agentNum) $mbytes
    }
    if {[regexp {Reads from memory: *([0-9.]*) reads,\
                     ([0-9.]*) MB} $line --> ops mbytes]} {
        set ::cacheMemoryReads($agentNum) $ops
        set ::cacheMemoryMbytes($agentNum) $mbytes
    }
    if {[regexp {Reads from backing store: *([0-9.]*) reads,\
                     ([0-9.]*) MB} $line --> ops mbytes]} {
        set ::cacheBackingReads($agentNum) $ops
        set ::cacheBackingMbytes($agentNum) $mbytes
    }
    if {[regexp {Average working set: *([0-9.]*) buffers,\
                     ([0-9.]*) MB} $line --> buffers mbytes]} {
        set ::cacheAvgWorkingSetBuffers($agentNum) $buffers
        set ::cacheAvgWorkingSetMbytes($agentNum) $mbytes
    }
    if {[regexp {Maximum working set: *([0-9.]*) buffers,\
                     ([0-9.]*) MB} $line --> buffers mbytes]} {
        set ::cacheMaxWorkingSetBuffers($agentNum) $buffers
        set ::cacheMaxWorkingSetMbytes($agentNum) $mbytes
    }
    if {[regexp {Maximum working set command:} $line]} {
        gets $::input command
        set ::cacheMaxWorkingSetCommand($agentNum) $command
    }
    return false
}

proc summarize_file_data_statistics {} {
    puts "\nFile data statistics:"
    set files [format "%d-%d" [minArray ::cacheFiles]\
                   [maxArray ::cacheFiles]]
    set mbytes [format "%.1f-%.1f" [minArray ::cacheMbytes]\
                    [maxArray ::cacheMbytes]]
    puts [format "  Disk cache size:         %12s files,%13s MB (%6.1f KB/file)"\
              $files $mbytes [divide [expr {1000.0*[sumArray ::cacheMbytes]}]\
                                  [sumArray ::cacheFiles]]]
    set reads [sumArray ::cacheMemoryReads]
    set mbytes [sumArray ::cacheMemoryMbytes]
    puts [format "  Reads from memory:       %12d reads,%13.1f MB (%6.1f KB/read)"\
              $reads $mbytes [divide [expr {1000.0*$mbytes}] $reads]]
    set reads [sumArray ::cacheBackingReads]
    set mbytes [sumArray ::cacheBackingMbytes]
    puts [format "  Reads from backing store:%12d reads,%13.1f MB (%6.1f KB/read)"\
              $reads $mbytes [divide [expr {1000.0*$mbytes}] $reads]]
    set buffers [format "%.1f-%.1f" [minArray ::cacheAvgWorkingSetBuffers]\
                     [maxArray ::cacheAvgWorkingSetBuffers]]
    set mbytes [format "%.1f-%.1f" [minArray ::cacheAvgWorkingSetMbytes]\
                    [maxArray ::cacheAvgWorkingSetMbytes]]
    puts [format "  Average working set:     %12s buffers,%11s\
            MB backing files" $buffers $mbytes]
    set buffers [format "%d-%d" [minArray ::cacheMaxWorkingSetBuffers]\
                     [maxArray ::cacheMaxWorkingSetBuffers]]
    set mbytes [format "%.1f-%.1f" [minArray ::cacheMaxWorkingSetMbytes]\
                    [maxArray ::cacheMaxWorkingSetMbytes]]
    puts [format "  Maximum working set:     %12s buffers,%11s\
            MB backing files" $buffers $mbytes]
    maxArray ::cacheMaxWorkingSetBuffers largest
    puts [format "  Maximum working set command:\n%s" \
              $::cacheMaxWorkingSetCommand($largest)]
}

#----------------------------------------------------------------------------
# update_caching
#
#       Add data from the "Caching" section.
#----------------------------------------------------------------------------

proc update_caching {agentNum line} {
    if {[regexp {^ *([^:]*):[^\(]*\(([0-9.]*) [^E]*EFS,\
                     ([0-9.]*) [^e]*emake} $line --> tag toEfs toEmake]} {
        if {$tag == "Lookups"} {
            set ::lookupsToEfs($agentNum) $toEfs
            set ::lookupsToEmake($agentNum) $toEmake
        } elseif {$tag == "Read traffic"} {
            set ::readsToEfs($agentNum) $toEfs
            set ::readsToEmake($agentNum) $toEmake
        } elseif {$tag == "Write traffic"} {
            set ::writesToEfs($agentNum) $toEfs
            set ::writesToEmake($agentNum) $toEmake
        } elseif {$tag == "Directory scans"} {
            set ::scansToEfs($agentNum) $toEfs
            set ::scansToEmake($agentNum) $toEmake
        }
    }
    if {[regexp {EFS page cache:.*\(([0-9]*) accesses,\
                     ([0-9]*)} $line --> accesses misses]} {
        set ::efsPageAccesses($agentNum) $accesses
        set ::efsPageMisses($agentNum) $misses
    }
    if {[regexp {EFS readdir cache:.*\(([0-9]*) accesses,\
                     ([0-9]*)} $line --> accesses misses]} {
        set ::efsReaddirAccesses($agentNum) $accesses
        set ::efsReaddirMisses($agentNum) $misses
    }
    if {[regexp {^ *([^:]*):[ ]*([0-9]*) files loaded\
                     [ \(]*([0-9.]*) MB\), *([0-9]*) flushes}\
             $line --> tag files mbytes flushes]} {
        set group [lindex $tag end]
        set ::groupFiles($group,$agentNum) $files
        set ::groupMBytes($group,$agentNum) $mbytes
        set ::groupFlushes($group,$agentNum) $flushes
        set ::groupIds($group) 1
    }
    if {[regexp {EFS name table: *(-?[0-9]+) lookups,\
                     (-?[0-9]+) tests} $line --> lookups tests]} {
        set ::efsNameTableAccesses($agentNum) $lookups
        set ::efsNameTableTests($agentNum) $tests
    }
    return false
}

proc summarize_caching {} {
    global numJobs

    puts "\nCaching:"
    set toEfs [sumArray ::lookupsToEfs]
    set toEmake [sumArray ::lookupsToEmake]
    set percent [percent $toEmake $toEfs]
    puts [format {  Lookups:          %4.1f%% (%d to EFS, %d to emake)}\
              $percent $toEfs $toEmake]
    set toEfs [sumArray ::readsToEfs]
    set toEmake [sumArray ::readsToEmake]
    set percent [percent $toEmake $toEfs]
    puts [format {  Read traffic:     %4.1f%% (%.1f MB from EFS,\
                    %.1f MB from emake)} $percent $toEfs $toEmake]
    set toEfs [sumArray ::writesToEfs]
    set toEmake [sumArray ::writesToEmake]
    set percent [percent $toEmake $toEfs]
    puts [format {  Write traffic:    %4.1f%% (%.1f MB to EFS,\
                    %.1f MB to emake)} $percent $toEfs $toEmake]
    set toEfs [sumArray ::scansToEfs]
    set toEmake [sumArray ::scansToEmake]
    set percent [percent $toEmake $toEfs]
    puts [format {  Directory scans:  %4.1f%% (%d to EFS, %d to emake)}\
              $percent $toEfs $toEmake]
    set accesses [sumArray ::efsPageAccesses]
    set misses [sumArray ::efsPageMisses]
    set percent [percent $misses $accesses]
    set rate [expr {$misses/[sumList $::overallTimer(command)]}]
    puts [format {  EFS page cache:   %4.1f%% (%d accesses, %d misses,\
                                                   %5.1f miss/cmd-sec)} $percent $accesses $misses $rate]
    set accesses [sumArray ::efsNameTableAccesses]
    set tests [sumArray ::efsNameTableTests]
    puts [format {  EFS name table:  %d lookups, %d tests,\
                        %.1f tests/lookup} $accesses $tests [divide $tests $accesses]]
    if {[array size ::efsReaddirAccesses] > 0} {
        set accesses [sumArray ::efsReaddirAccesses]
        set misses [sumArray ::efsReaddirMisses]
        set percent [percent $misses $accesses]
        puts [format {  EFS readdir cache:%4.1f%% (%d accesses, %d misses)}\
                  $percent $accesses $misses]
    }
    foreach i [lsort -integer [array names ::groupIds]] {
        if {[llength [array names ::groupFiles $i,*]] == 0} {
            continue
        }
        set files [sumArray ::groupFiles $i,*]
        set mBytes [sumArray ::groupMBytes $i,*]
        set flushes [sumArray ::groupFlushes $i,*]
        set percent [percent $flushes $numJobs]
        puts [format {  Cache group %d:  %7d file loads (%6.1f MB),\
                            %4d flushes (%5.1f%% of jobs)}\
                  $i $files $mBytes $flushes $percent]
    }
}

#----------------------------------------------------------------------------
# update_per_job_statistics
#
#       Add data from the "Per-job statistics" section.
#----------------------------------------------------------------------------

proc update_per_job_statistics {agentNum line} {
    if {[regexp {^ *([^:]*):.*per job[\( ]*([0-9.]*) total\)}\
             $line --> tag count]} {
        if {$tag == "File opens"} {
            set ::jobFileOpens($agentNum) $count
        } elseif {$tag == "Failed lookups"} {
            set ::jobFailedLookups($agentNum) $count
        } elseif {$tag == "Emake requests"} {
            set ::jobEmakeRequests($agentNum) $count
        } elseif {[string match {File bytes read*} $tag]} {
            set ::jobBytesRead($agentNum) $count
        } elseif {[string match {Total file bytes read*} $tag]} {
            set ::jobBytesTotalRead($agentNum) $count
        } elseif {[string match {Total file bytes written*} $tag]} {
            set ::jobBytesTotalWrite($agentNum) $count
        } elseif {[string match {Clear got all dir*} $tag]} {
            set ::jobDirectoryClears($agentNum) $count
        }
    }
    return false
}

proc summarize_per_job_statistics {} {
    global numJobs

    puts "\nPer-job statistics:"
    foreach {name label} {
        ::jobFileOpens                "File opens:                    "
        ::jobFailedLookups            "Failed lookups:                "
        ::jobEmakeRequests            "Emake requests:                "
        ::jobBytesRead                "File bytes read remotely (KB): "
        ::jobBytesTotalRead           "Total file bytes read (KB):    "
        ::jobBytesTotalWrite          "Total file bytes written (KB): "
        ::jobDirectoryClears          "Clear got all dir entries:     "
    } {
        set total [sumArray $name]
        set avg [divide $total $numJobs]
        puts [format {  %s %6.1f per job (%8d total)} $label $avg $total]
    }
}

#----------------------------------------------------------------------------
# update_efs_buffer_caching_statistics
#----------------------------------------------------------------------------

proc update_efs_buffer_caching_statistics {agentNum line} {
    if {[regexp {^ *([^:]*):.*per job[\( ]*([0-9.]*) total\)}\
             $line --> tag count]} {
        if {$tag == "Remote maps"} {
            set ::jobRemoteMaps($agentNum) $count
        } elseif {$tag == "Pages to agent"} {
            set ::jobPagesToAgent($agentNum) $count
        } elseif {$tag == "Pages from agent"} {
            set ::jobPagesFromAgent($agentNum) $count
        } elseif {[string match {Page cache hits} $tag]} {
            set ::jobPageCacheHits($agentNum) $count
        } elseif {[string match {Page cache misses*} $tag]} {
            set ::jobPageCacheMisses($agentNum) $count
        } elseif {[string match {Pages discarded} $tag]} {
            set ::jobPagesDiscarded($agentNum) $count
        }
    }
    return false
}

proc summarize_efs_buffer_caching_statistics {} {
    global numJobs
    puts "\nEFS buffer caching statistics:"
    foreach {name label} {
        ::jobRemoteMaps               "Remote maps:                   "
        ::jobPagesToAgent             "Pages to agent:                "
        ::jobPagesFromAgent           "Pages from agent:              "
        ::jobPageCacheHits            "Page cache hits:               "
        ::jobPageCacheMisses          "Page cache misses:             "
        ::jobPagesDiscarded           "Pages discarded:               "
    } {
        set total [sumArray $name]
        set avg [divide $total $numJobs]
        puts [format {  %s %6.1f per job (%8d total)} $label $avg $total]
    }
}

#----------------------------------------------------------------------------
# update_agent_to_agent_file_transfers
#----------------------------------------------------------------------------

proc update_agent_to_agent_file_transfers {agentNum line} {
    if {[regexp {^ *([^:]*): *([0-9]*) requests, *([0-9]*)\
                     rejections} $line --> tag requests rejections]} {
        if {$tag == "Incoming"} {
            set ::incomingA2ARequests($agentNum) $requests
            set ::incomingA2ARejections($agentNum) $rejections
        } elseif {$tag == "Outgoing"} {
            set ::outgoingA2ARequests($agentNum) $requests
            set ::outgoingA2ARejections($agentNum) $rejections
        }
    }
    if {[regexp {Failures: *([0-9]*) attempts, *([0-9]*)\
                     emake resends} $line --> attempts resends]} {
        set ::outgoingA2AAttempts($agentNum) $attempts
        set ::outgoingA2AResends($agentNum) $resends
    }
    return false
}

proc summarize_agent_to_agent_file_transfers {} {
    puts "\nAgent-to-agent file transfers:"
    foreach {name label} {
        incoming                      "Incoming: "
        outgoing                      "Outgoing: "
    } {
        set requests [sumArray ::${name}A2ARequests]
        set rejections [sumArray ::${name}A2ARejections]
        puts [format {  %s %4d requests, %4d rejections   (%4.1f%%)}\
                  $label $requests $rejections\
                  [percent $rejections $requests]]
    }
    set attempts [sumArray ::outgoingA2AAttempts]
    set resends [sumArray ::outgoingA2AResends]
    puts [format {  Failures:  %4d attempts, %4d emake resends (%4.1f%%)}\
              $attempts $resends [percent $resends $attempts]]
}

#----------------------------------------------------------------------------
# update_other_timers
#----------------------------------------------------------------------------

proc update_other_timers {agentNum line} {
    if {[regexp {^ *([^:]*): *([^s]*)s.*\), *([0-9]+) intvls}\
             $line --> name seconds intervals]} {
        lappend ::otherTimerIntervals($name) $intervals
        lappend ::otherTimerSeconds($name) $seconds
    }
    return false
}

proc summarize_other_timers {} {
    global otherTimerSeconds otherTimerIntervals totalTime numAgentRecords
    puts "\nOther timers:"
    set max [expr {[maxLength [array names ::otherTimerSeconds]] + 1}]
    set fmt "  %-${max}s     %8.2fs (%4.1f%%)%9d intvls, avg %7.1fms"
    foreach timer [lsort -dictionary [array names ::otherTimerSeconds]] {
        if { [llength $otherTimerSeconds($timer)] < $numAgentRecords 
             || [llength $otherTimerIntervals($timer)] < $numAgentRecords } {
            puts [format "  %-${max}s     INCOMPLETE" $timer]
            continue
        }

        set total     [expr [join $::otherTimerSeconds($timer) +]]
        set percent   [percent $total $totalTime]
        set intervals [expr [join $::otherTimerIntervals($timer) +]]
        puts [format $fmt \
                  "${timer}:" $total $percent $intervals\
                  [divide [expr {1000.0*$total}] $intervals]]
    }
}

#----------------------------------------------------------------------------
# update_windows_efs_operations
#----------------------------------------------------------------------------

proc update_windows_efs_operations {agentNum line} {
    global windowsEfsOpSeconds windowsEfsOpCalls windowsEfsOps windowsEfsOpTag
    set ::gotWindowsEFSData 1
    if {[regexp {^ +([^:]*): *([^s]*)s.*\), *([0-9]+) calls}\
             $line --> name seconds calls]} {
        set cleanname [string tolower [string map {" " _} $name]]
        if { ![info exists windowsEfsOpTag($cleanname)] } {
            set windowsEfsOpTag($cleanname) $name
            lappend windowsEfsOps $cleanname
        }
        lappend windowsEfsOpSeconds($cleanname) $seconds
        lappend windowsEfsOpCalls($cleanname)   $calls
    }
    return false
}

proc summarize_windows_efs_operations {} {
    global windowsEfsOpSeconds windowsEfsOpCalls windowsEfsOps windowsEfsOpTag
    global totalTime

    if {$::gotWindowsEFSData} {
        puts "\nWindows EFS operations:"
        foreach name $windowsEfsOps {
            set total   [sumList $windowsEfsOpSeconds($name)]
            set percent [percent $total $totalTime]
            set calls   [sumList $windowsEfsOpCalls($name)]
            puts [format {  %-20s %7.2fs (%5.1f%%), %7d calls, %6.2fms per call}\
                      $windowsEfsOpTag($name): $total $percent $calls\
                      [divide [expr {1000.0*$total}] $calls]]
        }
    }
}

#----------------------------------------------------------------------------
# update_vfs_counters
#----------------------------------------------------------------------------

proc update_vfs_counters {agentNum line} {
    if {[regexp {^ *([^:]*): *([0-9]*)} $line --> name count]} {
        lappend ::vfsCounters($name) $count
    }
    return false
}

proc summarize_vfs_counters {} {
    if { [info exists ::vfsCounters] } {
        puts "\nVFS counters:"
        catch {unset totals}
        foreach counter [array names ::vfsCounters] {
            set totals($counter) [expr [join $::vfsCounters($counter) +]]
        }
        if { $totals(Total chains) } {
            set avg [expr {double($totals(Total versions)) / $totals(Total chains)}]
        } else {
            set avg 0.0
        }
        set max [max $::vfsCounters(Max versions)]

        array set tmp [array get totals]
        array unset tmp "Total chains"
        array unset tmp "Total versions"
        array unset tmp "Read latest count"
        array unset tmp "Max versions"
        array unset tmp "Average versions"

        puts "  Total chains:              $totals(Total chains)"
        foreach type [lsort [array names tmp]] {
            puts [format "    %-26s %d" $type: $tmp($type)]
        }
        puts "  Total versions:            $totals(Total versions)"
        puts "  Max versions:              $max"
        puts "  Avg versions:              [format %.1f $avg]"
        puts "  Read latest count:         $totals(Read latest count)"
    }
}

#----------------------------------------------------------------------------
# update_usage_records
#----------------------------------------------------------------------------

proc update_usage_records {agentNum line} {
    if {[regexp {^ *([^0-9]*) +([0-9]*).*per job; *([0-9]*) raw}\
             $line --> name count raw]} {
        set name [string trim $name]
        lappend ::usage($name) $count
        lappend ::usageRaw($name) $raw
    }
    return false
}

proc summarize_usage_records {} {
    global usage usageRaw numJobs

    puts "\nUsage records:"
    set allUsage [expr [join $::usage(Total) +]]
    set allRaw   [expr [join $::usageRaw(Total) +]]

    unset ::usage(Total)
    unset ::usageRaw(Total)

    # Hack to work around a bug in some versions of the agent that cause
    # Failed Lookup usage to be reported as "Marker".

    set failed "Failed lookup"
    if { [info exists usage(Marker)] 
         && [info exists usage($failed)]
         && [sumList $usage($failed)] == 0 } {
        set usage($failed) $usage(Marker)
        unset usage(Marker)
        unset usageRaw(Marker)
    }
        
    set max [expr {[maxLength [array names ::usage]] + 1}]
    set fmt "  %-${max}s %8d (%5.1f%%), %6.1f per job; %8d raw (%5.1f%%)"
    foreach name [lsort [array names ::usage]] {
        set total [expr [join $::usage($name) +]]
        set totalRaw [expr [join $::usageRaw($name) +]]
        set percent [percent $total $allUsage]
        set rawPercent [percent $total $totalRaw]
        puts [format $fmt \
                  $name $total $percent [divide $total $numJobs]\
                  $totalRaw $rawPercent]
    }
    puts [format $fmt \
              "Total" $allUsage 100.0 [divide $allUsage $numJobs] \
              $allRaw 100.0]
}

#----------------------------------------------------------------------------
# update_idle_intervals
#----------------------------------------------------------------------------

proc update_idle_intervals {agentNum line} {
    if {[regexp {^ *([^ ]*) *([0-9]+) ms[^0-9]+([0-9]+)\
                     intervals, *([0-9.]*) ms} $line --> symbol name\
             count time]} {
        if {$symbol != ">"} {
            set ::idleIntervalNames($name) 1
            set ::idleIntervalCount${name}($agentNum) $count
            set ::idleIntervalTime${name}($agentNum) $time
        } else {
            set ::bigLabel $name
            set ::idleIntervalCountBig($agentNum) $count
            set ::idleIntervalTimeBig($agentNum) $time
        }
    }
    return true
}

proc summarize_idle_intervals {} {
    puts "\nIdle intervals:"
    puts " Length         Count   Cum. Count        Time  Cum. Time"
    set labels [lsort -integer -increasing [array names ::idleIntervalNames]]
    set totalIntervals [sumArray ::idleIntervalCountBig]
    set totalTime [sumArray ::idleIntervalTimeBig]
    foreach label $labels {
        set totalIntervals [expr {$totalIntervals
                                  + [sumArray ::idleIntervalCount$label]}]
        set totalTime [expr {$totalTime
                             + [sumArray ::idleIntervalTime$label]}]
    }
    set cumulativeIntervals 0
    set cumulativeTime 0.0
    foreach label [concat $labels Big] {
        set count [sumArray ::idleIntervalCount$label]
        set time [sumArray ::idleIntervalTime$label]
        set cumulativeIntervals [expr {$cumulativeIntervals + $count}]
        set cumulativeTime [expr {$cumulativeTime + $time}]
        set intervalPercent [percent $cumulativeIntervals $totalIntervals]
        set timePercent [percent $cumulativeTime $totalTime]
        if {$label != "Big"} {
            set firstPart [format { <= %d ms} $label]
        } else {
            set firstPart " >  $::bigLabel ms"
        }
        puts [format {%-12s %8d %9.1f%% %10.1f ms %7.1f%%} $firstPart\
                  $count $intervalPercent $time $timePercent]
    }
    puts " ------------------------------------------------------"
    puts [format {%-12s %8d %9.1f%% %10.1f ms %7.1f%%} " Total"\
              $cumulativeIntervals $intervalPercent $cumulativeTime $timePercent]
}

#---------------------------------------------------------------------------
# readFile
#
#       Read in a file of data, and populate global variables with all of
#       the data that we want to summarize.
#
# Results:
#       None.
#
# Side effects:
#       Zillions of global variables are set.
#
# Arguments:
#       file -              Name of the file containing the data.
#---------------------------------------------------------------------------

proc readFile {f} {
    global input
    set input $f
    set agentName unknown
    
    for {set i 0} {1} {incr i} {
        # Find the next set of agent data for this build and read the
        # "Build information" section.        
    
        while {[gets $f line] != -1} {
            if {[regexp {Build information:$} $line]} {
                # This agent is in "new" format.

                set skipThis 0
                set agentName unknown
                while {[gets $f line] != -1} {
                    if {$line == ""} {
                        break
                    }
                    if {[regexp {^  Build id: *([^ ]*)} $line --> value]} {
                        if {($::buildId != $value) && ($::buildId != "")} {
                            # Log data mixes several builds.  Only used data
                            # for the first build id.
                            
                            set skipThis 1
                            break
                        }
                        set ::buildId $value
                        continue
                    }
                    if {[regexp {^  Agent name:(.*)} $line --> value]} {
                        set agentName [string trim $value]
                        continue
                    }
                    if {[regexp {^  Start time: *(.*)} $line --> value]} {
                        regsub -all / $value - value
                        set time [clock scan $value]
                        if {($::startTime == "") || ($::startTime > $time)} {
                            set ::startTime $time
                        continue
                        }
                    }
                    if {[regexp {^  End time: *(.*)} $line --> value]} {
                        regsub -all / $value - value
                        set time [clock scan $value]
                        if {($::endTime == "") || ($::endTime < $time)} {
                            set ::endTime $time
                        }
                        continue
                    }
                    if {[regexp {^  Elapsed time: *([^s]*)s, ([0-9]*) jobs,\
                            ([0-9]*) com} $line --> tmpTime tmpJobs\
                            tmpCommands]} {
                        set ::time($i) $tmpTime
                        set ::jobs($i) $tmpJobs
                        set ::commands($i) $tmpCommands
                        if {[info exist ::agentEntries($agentName)]} {
                            incr ::agentEntries($agentName)
                            set ::agentTimes($agentName) [expr \
                                    {$::agentTimes($agentName) + $tmpTime}]
                        } else {
                            set ::agentEntries($agentName) 1
                            set ::agentTimes($agentName) $tmpTime
                        }
                        continue
                    }
                    if {[regexp {^  Agent CPU usage: *([^s]*)s user,\
                            *([^s]*)s system} $line --> ::userCPUSeconds($i)\
                            ::systemCPUSeconds($i)]} {
                        continue
                    }
                    if {[regexp {^  Agent version: *(.*)} $line --> value]} {
                        set ::agentVersions($value) xxx
                        continue
                    }
                    if {[regexp {^  EFS version: *(.*)} $line --> value]} {
                        set ::efsVersions($value) xxx
                        continue
                    }
                }
                if {$skipThis} {
                    continue
                }
                break
            }
            
            if {[regexp {^([^:]+):[0-9][0-9][0-9][0-9]:$} $line --> \
                    agentName]} {
                continue
            }
            if {![regexp {^Total time: *([^s]*)s, ([0-9]*) jobs, ([0-9]*) com}\
                      $line --> tmpTime tmpJobs tmpCommands]} {
                continue
            }
            
            break
        }
        
        if {[eof $f]} {
            break
        }
        
        # The statistics for each agent divided into sections with blank lines
        # separating sections (and no other blank lines in the file).  Each
        # section starts with a header line.  The following loop iterates over
        # all the sections, skipping to the next section, reading the header
        # line, and dispatching each line in the section according to the
        # header.

        for {set doneWithThisAgent 0} {!$doneWithThisAgent} {} {
            if {[eof $f]} {
                break
            }
            while {([gets $f line] != -1) && ($line == "")} {
                # Empty loop body
            }
            set charmap [list " " _ - _ : "" \( "" \) ""]
            set section [string trim $line]
            set section [string tolower [string map $charmap $section]]
            while {([gets $f line] != -1) 
                   && ($line != "") 
                   && ($line != "</result>")} {

                if { [llength [info commands update_$section]] == 0 } {
                    continue
                }

                if { [update_$section $i $line] } {
                    set doneWithThisAgent 1
                }
            }
        }
    }
}

#---------------------------------------------------------------------------
# summarize
#
#       This procedure is called after all the agent metrics have been
#       read in.  It prints summary information
#
# Results:
#       None.
#
# Side effects:
#       Statistics are printed.
#
# Arguments:
#       None.
#---------------------------------------------------------------------------

proc summarize {} {
    global totalTime elapsedTime numJobs numAgentRecords

    # Do an initial sanity check to make sure all of the proper arrays
    # got filled in by "readFile".
    
    set numAgents [array size ::agentEntries]
    set numAgentRecords [array size ::time]
    if {$numAgentRecords <= 0} {
        error "input file doesn't appear to contain any agents"
    }
    set totalTime [sumArray ::time]
    set numJobs [sumArray ::jobs]
    foreach i {
        ::jobs ::commands
        
        ::cacheFiles ::cacheMbytes ::cacheMigratedFiles ::cacheMigratedMbytes
        ::cacheMemoryReads ::cacheMemoryMbytes ::cacheBackingReads
        ::cacheBackingMbytes ::cacheAvgWorkingSetBuffers
        ::cacheAvgWorkingSetMbytes ::cacheMaxWorkingSetBuffers
        ::cacheMaxWorkingSetMbytes ::cacheMaxWorkingSetCommand
        
        ::lookupsToEfs ::lookupsToEmake ::readsToEfs ::readsToEmake
        ::writesToEfs ::writesToEmake ::scansToEfs ::scansToEmake
        ::efsPageAccesses ::efsPageMisses
        ::efsNameTableAccesses ::efsNameTableTests
        
        ::jobFileOpens ::jobFailedLookups ::jobEmakeRequests ::jobBytesRead
        ::jobBytesTotalRead ::jobBytesTotalWrite ::jobDirectoryClears
        
        ::jobRemoteMaps ::jobPagesToAgent ::jobPagesFromAgent
        ::jobPageCacheHits ::jobPageCacheMisses ::jobPagesDiscarded
        
        ::incomingA2ARequests ::incomingA2ARejections
        ::outgoingA2ARequests ::outgoingA2ARejections
        
    } {
        if {[array size $i] < $numAgentRecords} {
            parray $i
            puts "array $i is incomplete"
        }
    }
    
    foreach name [array names usage] {
        if { [llength $usage($name)] < $numAgentRecords } {
            puts "usage $name is incomplete"
        }
    }

    puts "Cluster summary statistics"
    puts "--------------------------"
    puts "\nBuild information:"
    puts [format {  Build id:               %s} $::buildId]
    puts [format {  Total agents:           %d, %d reentries} \
            $numAgents [expr {$numAgentRecords - $numAgents}]]

    set timefmt "%Y/%m/%d %H:%M:%S"
    if {$::startTime != ""} {
        puts [format {  Start time:             %s} \
                [clock format $::startTime -format $timefmt]]
    }
    if {$::endTime != ""} {
        puts [format {  End time:               %s} \
                [clock format $::endTime -format $timefmt]]
    }
    if {($::startTime != "") && ($::endTime != "")} {
        set elapsedTime [expr {$::endTime - $::startTime}]
    } else {
        # We don't exactly have the right information to compute the total
        # elapsed time of the build.  Approximate this by taking the longest
        # time that any one agent was involved with the build.
        
        set elapsedTime [maxArray ::agentTimes]
    }
    puts [format {  Elapsed time:           %.0fs, %d jobs, %d commands}\
            $elapsedTime [sumArray ::jobs] [sumArray ::commands]]
    puts [format {  Total agent time:       %.1fs} $totalTime]
    set totalUserSeconds [sumArray ::userCPUSeconds]
    set totalSystemSeconds [sumArray ::systemCPUSeconds]
    puts [format {  Agent CPU usage:        %.1fs user, %.1fs system\
            (%.1f%% overall)} $totalUserSeconds $totalSystemSeconds \
            [percent [expr {$totalUserSeconds + $totalSystemSeconds}] \
            $totalTime]]
    if {[array size ::agentVersions] > 0} {
        puts -nonewline "  Agent version(s):       "
        set prefix ""
        foreach version [array names ::agentVersions] {
            puts "$prefix$version"
            set prefix  "                          "
        }
    }
    if {[array size ::efsVersions] > 0} {
        puts -nonewline "  EFS version(s):         "
        set prefix ""
        foreach version [array names ::efsVersions] {
            puts "$prefix$version"
            set prefix  "                          "
        }
    }
    
    summarize_overall_time_usage
    summarize_emake_request_timers
    summarize_registry
    summarize_bandwidth
    summarize_network_data_compression
    summarize_file_data_statistics
    summarize_active_agents
    summarize_caching
    summarize_per_job_statistics
    summarize_efs_buffer_caching_statistics
    summarize_agent_to_agent_file_transfers
    summarize_other_timers
    summarize_vfs_counters
    summarize_usage_records
    summarize_windows_efs_operations
    summarize_idle_intervals
}

#------------------------------------------------------------------------------
# puts
#
#       Wrapper for standard puts that slaps a [catch] around the I/O.  This
#       avoids ugly error messages when you have redirected output to a pipe
#       and the pipe is closed prematurely.  For example:
#
#               agentsummary foo | less
#------------------------------------------------------------------------------

rename puts real_puts
proc puts {args} {
    catch {eval real_puts $args}
}

if {$argc == 1} {
    set f [open [lindex $argv 0]]
} else {
    set f stdin
}
readFile $f

if {$f != "stdin"} {
    close $f
}

summarize
