#!/bin/sh
#
# condtest - run a trace average based on tag value to calculate condition+test
#
# Usage: condtest [-t a,b] runfile ...
#
# where: -t a,b selects tag values a and b to be used as condition and test
#		(default is first & last used tag values)
#	 runfile selects one or more run runfiles to analyze
#
# The script will produce a runfile-tavg for each runfile specified, which will
# have 3 frames in it: the 2 frames for condition and test, and a third which
# is the difference of these two, as calculated by qm's Run/Calc operation.
#
# Copyright (c) 2010, Gilles Detillieux, Spinal Cord Research Centre,
# University of Manitoba.  All Rights Reserved.
#

tags=
while :
do
	case "$1" in
	-\?|-help|--help)	sed -n '3,/^# Univ/s/^#/ /p' "$0"; exit ;;
	-t[0-9]*)	tags=`expr "x$1" : 'x-c\(.*\)'`; shift ;;
	-t)	shift; tags="$1"; shift ;;
	-*)	set --; break ;;
	*)	break ;;
	esac
done

case "$#" in
0)	echo "Usage:  condtest [-t tag1,tag2] runfile ...
	or condtest --help	for detailed usage information" >&2; exit 1 ;;
esac

bs=`sysvecho '\b\c'`

for run
do
	case "$run" in
	*.frm)	run=`expr "$run" : '\(.*\)\.frm'` ;;
	esac
	taglevels=$tags
	case "$taglevels" in
	"")	taglevels=`dumprun -f "$run" 2>/dev/null | sed -n 's/^.*Tags:* *[-A-Z]*\([0-9]*\)[	 ].*/\1/p' | sort -u | sed -n 's/^$/0/; $!s/$/,/; 1p; 1n; $p' | tr -d '\012'` ;;
	esac
	echo "Averaging tags $taglevels in $run..."
	(TERM=dumb DISPLAY= analysis "$run" 2>&1 > /dev/null |
		sed -n -e 's/FATAL ERROR: */analysis: /p' >&2) <<!
atbsab2
qqst$taglevels
qb$run-tavg
y${bs}
qyn
!
	test -w "$run-tavg.frm" || continue
	echo "Calculating difference for tags $taglevels in $run-tavg..."
	TERM=dumb DISPLAY= qm "$run-tavg" > /dev/null 2>/dev/null <<!
rcf3=f1-f2
qn
!
done
