#!/bin/sh
#
# getwfdata - generate an ASCII dump of waveforms with downsampling
#
# Usage:  getwfdata [-h] [-ffreq] [-rst,en] runfile wfnum ... > output.csv
#
# where:  -h		specifies that an extra header should be added to
#			the output file, showing time range and frequency
#	  -ffreq	specifies the frequency to which you want the data
#			downsampled (default is sample rate of first WF)
#	  -rst,en	specifies the start and end of the analysis range
#			(default is taken from analysis parameters, or all)
#	  runfile	specifies a run file name or analysis parameter file
#			(no default, runfile must be specified)
#	  wfnum ...	specifies the waveform number(s) of one or more
#			waveforms (no default, at least one must be specified)
#	  output.csv	specifies output text (CSV) file name
#			(default is standard output if not redirected)
#
# Copyright (c) 2005-6, Gilles Detillieux, Spinal Cord Research Centre,
# University of Manitoba.  All Rights Reserved.
#

quote=
#quote='"'	# if you want colum labels quoted
outname=
hopt=
fopt=
ropt=
T=/tmp/gwd$$
while :
do
	case "$1" in
	-\?|-help|--help)	sed -n '3,/^# Univ/s/^#/ /p' "$0"; exit ;;
	-debug|--debug)	shift; T=gwd.out. ;;
	-h)	hopt="$1"; shift ;;
	-f[0-9]*)	fopt=`expr "x$1" : 'x-f\(.*\)'`; shift ;;
	-f)	shift; fopt="$1"; shift ;;
	-r[A-Za-z0-9]*)	ropt=`expr "x$1" : 'x-r\(.*\)'`; shift ;;
	-r)	shift; ropt="$1"; shift ;;
	-*)	set --; break ;;
	*)	break ;;
	esac
done

prmfile="$1"
ywf="$2"
case "$#" in
0|1)	echo "Usage:  getwfdata [-h] [-ffreq] [-rst,en] runfile wfnum ... > output.csv
	or getwfdata --help	for detailed usage information" >&2; exit 1 ;;
2)	format="x" ;;
*)	format="y, x"; shift ;;
esac
shift

ascript=${T}a
anafile=${T}b
xyfile=${T}c
diags=${T}d
mrgfile1=${T}e
mrgfile2=${T}f
case "${T}" in
/tmp/*)	trap "rm -f ${T}[a-f]" 0	# cleanup on exit
	trap "exit 1" 1 2 3 15		# exit, & cleanup, if killed
	;;
esac

case "$ropt" in
"")	;;
[Aa][Ll][Ll])
	ropt="srs0\nemax\nqq"
	;;
[0-9]*\,[0-9]* | [0-9]*\,[Mm][Aa][Xx]*)
	ropt=`echo "$ropt" | sed 's/^/srs/; s/,/s\\\\ne/; s/ *$/s\\\\nqq/; s/[Xx]s/x/'`
	;;
*)	echo "$0: Invalid time range $ropt ignored" >&2
	ropt=
	;;
esac

case "$fopt" in
""|[0-9]*)	;;
*)	echo "$0: Invalid downsampling frequency $fopt ignored" >&2
	fopt=
	;;
esac

case "$hopt" in
-h)	sysvecho "agwyr${ropt}sdutsqqqcvwvr                              qyn" |
	    TERM=dumb DISPLAY= analysis $prmfile > $anafile 2> $diags
	freq=`awk '/^Sampling rate:/ {r = $3}; /^ *'"${ywf}"'  *[0-9][0-9]* .* uV  .*/ {print r/$2}' $anafile`
	case "$fopt" in
	[0-9]*)	freq="$fopt" ;;
	esac
	start=`sed -n -e 's|^<.*Start of run:[ 	]*\([-0-9.e+]*\).*|\1|p' $anafile`
	end=`sed -n -e 's|^<.*End of run:[ 	]*\([-0-9.e+]*\).*|\1|p' $anafile`
	rend=`sed -n -e 's|^Run length:[ 	]*\([-0-9.e+]*\).*|\1|p' $anafile`
	end=`echo "$end $rend" | awk '{ if ($1>$2) print $2; else print $1 }'`
	wfs="$ywf"
	case "$format" in
	"y, x")	wfs="$wfs $*" ;;
	esac
	hdr="\"getwfdata -h -f$freq -r$start,$end $prmfile $wfs\""
	;;
esac

wfcount=$#
for xwf
do
    sysvecho "agwyr${ropt}slwn${xwf}\nrlmin\numax\nqd0\nw1p\nqswn${ywf}\nrlmin\numax\nqqqqdn${format}\\\\n\nqqb\ncvwqyn" > $ascript

    echo "Analysing..." >&2
    if TERM=dumb DISPLAY= analysis $prmfile < $ascript > $anafile 2> $diags
    then
	:
    else
	sed -n -e 's/FATAL ERROR: /analysis: /p' $diags >&2
	echo "$0: analysis failed!" >&2
	exit 1
    fi

    case "$fopt" in
    [0-9]*)	ratediv=`awk '/^Sampling rate:/ {r = $3}; /^ *'"${ywf}"'  *[0-9][0-9]* .* uV  .*/ {print int(r/$2/'"${fopt}"'+0.5)}' $anafile`
	;;
    *)	ratediv=1
	;;
    esac
    case "$ratediv" in
    1)
	echo "Extracting..." >&2
	;;
    [1-9]*)
	echo "Extracting/downsampling by $ratediv..." >&2
	;;
    *)	echo "$0: Got invalid rate divisor '$ratediv' from frequency '$fopt'" >&2
	exit 1
	;;
    esac
    xwname=`sed -n -e 's|,.*||; s|^ *'"${xwf}"'  *.* uV  ||p' $anafile`
    case "$format" in
    x)	echo "$quote$xwname$quote" > $xyfile ;;
    *)	ywname=`sed -n -e 's|,.*||; s|^ *'"${ywf}"'  *.* uV  ||p' $anafile`
    	echo "$quote$ywname$quote,$quote$xwname$quote" > $xyfile ;;
    esac
    sed -e '1,2d; /^Run:/,$d; /2\.14.*e/d; /^[ 	]*$/d; s/[ 	]*//g' $anafile | \
	awk '(NR-1) % '"${ratediv}"' == 0 {print}' >> $xyfile
    if [ `wc -l < $xyfile` -le 1 ]
    then
	echo "$0: analysis did not produce any usable numbers from WF $ywf and $xwf." >&2
	exit 1
    fi

    wfcount=`expr $wfcount - 1`
    (
	if [ $wfcount -gt 0 ]
	then
		exec > $mrgfile2
	else
		case "$hopt" in
		-h)	echo "$hdr" ;;
		esac
	fi
	if [ -s $mrgfile1 ]
	then
		echo "Merging..." >&2
		pr -t -m -J --sep-string=, $mrgfile1 $xyfile
		tcount=`wc -l < $xyfile | tr -d ' \011'`
		if [ $tcount -ne $lcount ]
		then
			lm=less
			[ $tcount -gt $lcount ] && lm=more
			echo "$0: analysis produced $lm samples from WF $xwf than previous ones." >&2
		fi
	else
		cat $xyfile
	fi
    )
    if [ -s $mrgfile2 ]
    then
	mv $mrgfile2 $mrgfile1
	lcount=`wc -l < $mrgfile1 | tr -d ' \011'`
    fi
    format="x"
done
