#!/bin/sh

## "concatMeta"
## Command-line interface to concatenate multiple LIGO_LW files containing rows
##     from the same database table
## Written by Peter Shawhan, February 2002
# $Id$

## This script is a hybrid of sh and Tcl/Tk commands.

## Use "tclshexe" if it is in the PATH, otherwise use "tclsh" #\
shell=tclsh                                                   #\
for dir in `echo $PATH | perl -p -e "s/:/ /g"`; do            #\
  if test -x $dir/tclshexe; then shell=tclshexe; fi           #\
done                                                          #\
exec $shell "$0" ${1+"$@"}                                    #\

##=========================================================================
## Name: Main
##

proc Main {} {

    ;##- If there were no arguments, just print usage info and exit
    if { [llength $::argv] <= 1 } {
	PrintUsage; exit 0
    }

    ;##- Parse command-line arguments
    set infiles [lrange $::argv 0 end-1]
    set outfile [lindex $::argv end]

    ;##- Make sure the output file does not already exist
    if [file exists $outfile] {
	puts stderr "Specified output file $outfile already exists"
	exit 1
    }

    ;##- Open the output file
    if [catch {open $outfile w} ofid] {
	puts stderr "Error opening output file $outfile"
	exit 1
    }

    ;##- Loop over input files
    set firstfile 1
    set some_output 0
    foreach file $infiles {

	;##- Open the input file
	if [catch {open $file r} ifid] {
	    puts stderr "Error opening input file $file"
	    ;##- Close and delete the output file
	    close $ofid
	    file delete $outfile
	    exit 1
	}

	;##- Loop over lines in the input file until we get to the Stream
	set head ""
	set found_stream 0
	while { [gets $ifid line] >= 0 } {
	    if { [regexp {^(\s*?<Stream[^>]+Name=[^>]+?)(.)>} $line \
		    match streamline fchar] } {
		set found_stream 1
		if { [string equal $fchar "/"] } {
		    set empty_stream 1
		    append streamline ">"
		} else {
		    set empty_stream 0
		    append streamline "${fchar}>"
		}
		break
	    }
	    append head "$line\n"
	}

	;##- If we never found the Stream, raise an error
	if { ! $found_stream } {
	    puts stderr "Input file $file does not contain a LIGO_LW stream"
	    ;##- Close input and output files, and delete the output file
	    close $ifid
	    close $ofid
	    file delete $outfile
	    exit 1
	}

	;##- If file contains an empty stream, skip to the next file
	if { $empty_stream } {
	    close $ifid
	    continue
	}

	if { $firstfile } {
	    ;##- Copy the header to the output file
	    puts -nonewline $ofid $head
	    puts $ofid $streamline
	}

	;##- Remove the Comment from the header
	regsub {<Comment>.*?</Comment>} $head {} head

	if { $firstfile } {
	    ;##- Save the header for later comparisons
	    set firsthead $head
	} else {
	    ;##- Compare against the header from the first file
	    if { ! [string equal $firsthead $head] } {
		puts stderr "Input file $file has a different header"
		;##- Close input and output files, and delete the output file
		close $ifid
		close $ofid
		file delete $outfile
		exit 1
	    }
	}

	if { ! $empty_stream } {
	    ;##- Now copy table data from the input file to the output file
	    set first_from_file 1
	    while { [gets $ifid line] >= 0 } {
		if { [regexp {^\s*</Stream>} $line] } break
		if { [string is space $line] } continue

		if { $first_from_file } {
		    if { $some_output } {
			#-- Add a delimiter and a newline
			puts -nonewline $ofid ",\n"
		    } else {
			set some_output 1
		    }
		    set first_from_file 0
		    puts -nonewline $ofid "$line"
		} else {
		    puts -nonewline $ofid "\n$line"
		}
	    }
	}

	close $ifid
	set firstfile 0
    }

    ;##- If all input files contained no events, just copy blank output
    if { $some_output } {
	;##- Close the stream
	puts $ofid "\n      </Stream>"
    } else {
	puts -nonewline $ofid $head
	set streamline "[string range $streamline 0 end-1]/>"
	puts $ofid $streamline
    }

    ;##- Finish off the output file
    puts $ofid "   </Table>\n</LIGO_LW>"

    ;##- Close the output file
    close $ofid

    return
}


##=========================================================================
## Name: PrintUsage  (Prints usage information to stderr)
##

proc PrintUsage {} {
    puts stderr "Usage:  concatMeta <file> \[<file> ...\] <outfile>"
    puts stderr "The input files must all be LIGO_LW files containing a single Table object,"
    puts stderr "with the same table definition in all files"
    return
}


##=========================================================================
## Name: main
##
## Comments:
##   OK, we've defined all the procs, including Main.  Now run it!

;#barecode
Main
