#!/bin/sh
#
# burstareaplot - plot normalized area under curve for bursts in run
#		  also plots normalized mean amplitude, burst & cycle durations
#
# Usage:  burstareaplot [-c wfnum] [-n npoints] [-t] runfile ...
#
# where:  -c wfnum	specifies the waveform number for the marked up bursts
#			(default is 0)
#	  -n npoints	specifies the number of points to be averaged when
#			smoothing the curves
#			(default is 10, use 1 for no smoothing)
#	  -t		specifies that time should be plotted on X-axis
#			(default is burst number)
#	  runfile	specifies one or more run file names to be measured
#			(no default, runfile must be specified)
#
# Copyright (c) 2006, Gilles Detillieux, Spinal Cord Research Centre,
# University of Manitoba.  All Rights Reserved.
#

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

case "$#" in
0)	echo "Usage:  burstareaplot [-c wfnum] [-n npoints] [-t] runfile ...
	or burstareaplot --help	for detailed usage information" >&2; exit 1 ;;
esac

trap "rm -f ${T}" 0			# cleanup on exit
trap "exit 1" 1 2 3 15			# exit, & cleanup, if killed

burstareas -c "$cwfnum" ${@+"$@"} |
    differ -a -c1 -d - |
    sed '$d' |
    awk -F, '{print $1 "," $2 "," $3-$1 "," $4 "," $5}' |
    npra "$nopt" -s -c2-5 - |
    normalize -c2-5 - > ${T}

case "$topt" in
-txt|--txt)	cat ${T} ; exit ;;
-t)	topt="-xf${T} -xc1 -xhTime" ;;
*)	topt="-xhBurst" ;;
esac

genplot -yf${T} -yc5 -yr0,1.0001 -yw0 -yp2 -yh "" $topt	# Area in blue
genplot -yf${T} -yc4 -yr0,1.0001 -yw0 -yp4 -xp0 $topt	# Mean ampl. in red
genplot -yf${T} -yc3 -yr0,1.0001 -yw0 -yp3 -xp0 $topt	# Burst dur. in green
genplot -yf${T} -yc2 -yr0,1.0001 -yw0 -yp5 -xp0 $topt	# Cycle dur. in purple
sysvecho "PU8680,5420;SP2;PD8880,5420;PU8900,5420;SP1;LO12;SR0.8,1.55555;LBArea\003;"
sysvecho "PU8680,5170;SP4;PD8880,5170;PU8900,5170;SP1;LO12;SR0.8,1.55555;LBMean ampl.\003;"
sysvecho "PU8680,4920;SP3;PD8880,4920;PU8900,4920;SP1;LO12;SR0.8,1.55555;LBBurst dur.\003;"
sysvecho "PU8680,4670;SP5;PD8880,4670;PU8900,4670;SP1;LO12;SR0.8,1.55555;LBCycle dur.\003;"
