#!/bin/sh
#
# ecgfrq - plot ECG spike frequencies and calculate average
#
# Usage:  ecgfrq [-w wfnum] [-t thresh] [-h hyst] [-d discr] [-m minw] [-r st,en] runfile ...
#
# where:  -w wfnum	specifies waveform number for ECG signal
#			(default is 5)
#	  -t thresh	specifies spike threshold for ECG pulse detection
#			(default is automatic, or existing parameter)
#	  -h hyst	specifies ECG spike hysteresis relative to threshold
#			(default is 0 for no hysteresis, or existing parameter)
#	  -d discr	specifies discriminator threshold for spike rejection
#			(default is none, or existing parameter)
#	  -m minw	specifies minimum allowable spike width (in ms),
#			causing single-unit number 1 data to be generated for
#			the ECG signal waveform to reject narrow spikes,
#			only spikes between this minimum and 10 ms are kept
#			(default is no minimum, and no single-unit generated,
#			but if an existing single-unit is set it will be used)
#	  -r st,en	specifies the start and end of the analysis range
#			(default is the whole run)
#	  runfile	specifies one or more run file names to be measured
#			(no default, runfile must be specified)
#
# ecgfrq performs a spike frequency analysis on the specified range in each
# runfile, producing an HPGL plot file of spike frequency vs time, as well
# as summarising the mean frequency and standard deviation.  The plot files
# will be named after the specified runfile names, with "-ecgfrq.plt" appended.
#
# Copyright (c) 2012, Gilles Detillieux, Spinal Cord Research Centre,
# University of Manitoba.  All Rights Reserved.
#

swfnum=5 sthresh= hyst= discr= minw= range=
T=/tmp/ecg$$
while :
do
	case "$1" in
	-\?|-help|--help)	sed -n '3,/^# Univ/s/^#/ /p' "$0"; exit ;;
	-debug|--debug)	shift; T=ecg.out. ;;
	-w)	shift; swfnum="$1"; shift ;;
	-t)	shift; sthresh="$1"; shift ;;
	-h)	shift; hyst="$1"; shift ;;
	-d)	shift; discr="$1"; shift ;;
	-m)	shift; minw="$1"; shift ;;
	-r)	shift; range="$1"; shift ;;
	-*)	set --; break ;;
	*)	break ;;
	esac
done
ascript=${T}a
diags=${T}b
anafile=${T}c

case "$#" in
0)	echo "Usage:  ecgfrq [-w wfnum] [-t thresh] [-h hyst] [-d discr] [-m minw] [-r st,en] runfile ...
	or ecgfrq --help	for detailed usage information" >&2; exit 1 ;;
esac

case "$swfnum" in
[0-9]*)	;;
*)	echo "$0: Invalid number for spike waveform: -w $swfnum" >&2
	exit 1
	;;
esac

case "$sthresh" in
[0-9]*|-[0-9]*)	;;
"")	;;
*)	echo "$0: Invalid number for spike threshold: -t $sthresh" >&2
	exit 1
	;;
esac

case "$hyst" in
[0-9]*|-[0-9]*)	;;
"")	;;
*)	echo "$0: Invalid number for spike hysteresis: -h $hyst" >&2
	exit 1
	;;
esac

case "$discr" in
[Mm][Ii][Nn]*|[Mm][Aa][Xx]*)
	case "$hyst" in
	-*)	discr=max ;;
	*)	discr=min ;;
	esac
	;;
"")	;;
[0-9]*|-[0-9]*)	;;
*)	echo "$0: Invalid number for spike discriminator: -d $discr" >&2
	exit 1
	;;
esac

case "$minw" in
[.0-9]*)	minw="un1
wl$minw
u10ms
qvdaq" ;;
"")	;;
*)	echo "$0: Invalid number for minimum spike width: -m $minw" >&2
	exit 1
	;;
esac

start=0 end=max
range=`echo "$range" | tr -d ' '`
case "$range" in
""|[Aa][Ll][Ll])
	;;
[0-9]*\,[0-9]* | [0-9]*\,[Mm][Aa][Xx]*)
	start=`echo "$range" | sed 's/^\([-0-9.e+scm]*\),.*/\1/'`
	end=`echo "$range" | sed 's/^[^,]*, *\([-0-9.e+MmAaXxsc]*\).*$/\1/'`
	case "$start,$end" in
	[0-9]*\,[0-9Mm]*)	;;
	*)	echo "$0: Invalid range specified: -r $range" >&2
		exit 1
		;;
	esac
	;;
*)	echo "$0: Invalid range specified: -r $range" >&2
	exit 1
	;;
esac

case "${T}" in
/tmp/*)	trap "rm -f ${T}[a-c]" 0		# cleanup on exit
	trap "exit 1" 1 2 3 15			# exit, & cleanup, if killed
	;;
esac

results=0
for run
do
	rm -f "$run-ecgfrq.plt"
	cat <<! > $ascript
agavfrsrs$start
e$end
qcw-1
qswn$swfnum
qqmianqqgnnqqw$swfnum
ssvds$sthresh
e$hyst
d$discr
${minw}qqqy
pd2
f$run-ecgfrq.plt
agavfasdtsyqqgb1
qdn+ y\\n
qqb
sdthyqn++ y\\n
qqb
qyn
!

	sysvecho "$run:\t\c"
	if TERM=dumb DISPLAY= analysis "$run" < $ascript > $anafile 2> $diags
	then
		frqs=`grep '^ *++* *[-0-9.e+]* *$' $anafile`
		avg=`echo "$frqs" | sed -n '1s/^ *+  *//p'`
		sdev=`echo "$frqs" | sed -n '2s/^ *+  *//p'`
		nfrqs=`echo "$frqs" | sed -n '$s/^ *++ *//p'`
		if [ -z "$frqs" -o -z "$avg" -o -z "$nfrqs" ]
		then
			echo "No spike frequencies found for W.F. $swfnum from $start to $end (ms)"
			continue
		fi
		sdev="${sdev:-unknown}"
		echo "Mean ECG frequency $avg (S.D. $sdev) for $nfrqs spikes from $start to $end (ms)"
		results=`expr $results + 1`
	else
		sed -n -e 's/FATAL ERROR: *//p' $diags
		#sed -n -e 's/FATAL ERROR: /analysis: /p' $diags >&2
		#echo "$0: analysis failed!" >&2
		#echo
	fi
done

test "$results" -gt 0 || exit 2
