#!/usr/bin/env tclsh

# segsum : Report the sum of the segment durations in the input file or stream
# Written by Peter Shawhan
# Copyright 2003, 2004, 2012 Peter Shawhan

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

#-- This utility can't use SegSum in the segments library because we want
#-- it to be able to read from stdin as well as from a file

if { $argc >= 1 } {
    set file [lindex $argv 0]
    set isfile 1
} else {
    set file ""
    set isfile 0
}

if { $argc > 1 || [string match "-*" $file] } {
    puts "Usage:  [file tail [info script]] \[<filename>\]"
    puts "This program displays the total time of all segments in a file."
    puts "If no filename is specified, the program reads from standard input."
    puts "There is no strict requirement for the format of the file; the\
            program"
    puts "just looks for two 9- or 10-digit numbers separated by one or more"
    puts "spaces, dashes, commas or semicolons."
    puts "A '\#' character in the file comments out the rest of the line."
    puts "Certain header/summary lines (e.g. in the output from conlog) are\
            also ignored."
    exit 1
}

if { $isfile } {
    set fid [open $file]
} else {
    set fid stdin
}

set total 0
set isreal 0
while { [gets $fid line] >= 0 } {
    #-- Remove comments
    regsub {#.*$} $line {} line
    #-- Ignore certain lines from conlog listings
    if [regexp -nocase {^(between |elapsed time | science data )} $line] \
	    continue
    if [regexp {(\d{9,10}\.?\d*)[\s\-,;]+(\d{9,10}\.?\d*)} $line \
	    match start end] {
	set total [expr {$total+($end-$start)}]
	if { $isreal == 0 && [regexp {\.} "${start}${end}"] } {
	    set isreal 1
  	}
    }
}

if { $isfile } { close $fid }
if { $isreal } {
    puts [format %.6f $total]
} else {
    puts $total
}
