#!/bin/bash

WHERE="$JR_HOME/rjrv/mergeout/moutils"
GETCHUNK=$WHERE/getchunk
ATTACK=$WHERE/attack
SPLIT=$WHERE/split

# Needed for proper sorting:
lc="$LC_ALL"
export LC_ALL="C"

if [ -z "$1" -o "$1" = "-h" ]; then
	if [ -z "$1" ]; then echo -e "$0: Error: Directory expected as argument\n" 1>&2; fi
	echo "Usage: mergeout dir"
	echo "Merges rjrv output files into a single file that is just like jrv -i."
	exit
fi

# each input file (pc*) looks like
#
#    ... lines of header stuff ...
#    DATE
#    ... lines of good stuff ...
#    DATE
#    ... lines of trailer stuff ...
#
# the "good stuff" looks like (any number of):
#
#    name of test:
# OR
#    name of test:
#       error

# want to to merge all the good stuff and sort by name of test.
# the hard part is keeping the error line (if one appears) with the test name.
# (no guarantee that good stuff in a given file is sorted by test name;
#  if it were, could probably improve by merging.)

# basic idea of how this works:
#   first:
#     (GETCHUNK) on each file, get good stuff between the DATE lines
#     (ATTACK) on each test line that has error line, combine the lines into 1.
#   then:
#     (sort) sort all the lines
#     (SPLIT) split any lines that were combined into 2 lines
#             (i.e., test name line and error line)

dir=$1
files=$dir/pc*

for f in $files
do
    ## echo $f
    $GETCHUNK < $f | $ATTACK

done |
sort | $SPLIT > $dir/merged
