#!/bin/sh
#
# convtore -- convert and merge batches of Tore's U of Goteborg .dat files
#
# Usage:  convtore [-f freq] [-t] [-s startnum] [-e endnum] dir ...
#
# where:  -f freq	specifies the sampling frequency in Hz, overriding the
#			sampling period in the data file header (if given)
#	  -t		specifies that traces, rather than waveforms, should
#			be output in the resulting runfile
#	  -s startnum	specifies the starting file name or number in the
#			directory, to make conversion skip over previous files
#	  -e endnum	specifies the ending file name or number
#	  dir		specifies a directory of data files in Tore's format
#		 	from the U. of Goteborg's Visual BASIC capture software
#
# convtore will run tore2run on all the raw D*.DAT files in the specified
# directories and merge the results into files that contain the number of
# frames that is specified in the first of each group.  D*.DAT files contain
# only a single raw frame, but to be useful for analysis it is usually
# necessary to merge them into a run of several frames.
#
# Copyright (c) 2006, Gilles Detillieux, Spinal Cord Research Centre,
# University of Manitoba.  All Rights Reserved.
#

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

if [ "$#" -lt 1 ]
then
	echo "Usage:  $0 [-f freq] [-t] [-s startnum] [-e endnum] dir ...
	or  $0 --help  for detailed usage information" >&2
	exit 1
fi

[ ! -z "$stfile" ] && stfile=`basename "$stfile" .DAT | tr -dc '[0-9]'`
[ ! -z "$enfile" ] && enfile=`basename "$enfile" .DAT | tr -dc '[0-9]'`

lastnum=-1
lastfile=
find ${@+"$@"} -name D\*.DAT -print | sort |
    while read rfile
    do
	filenum=`basename "$rfile" .DAT | tr -dc '[0-9]'`
	[ ! -z "$enfile" ] && [ "$filenum" -gt "$enfile" ] && break
	[ ! -z "$stfile" ] && [ "$filenum" -lt "$stfile" ] && continue
	newrun=`expr "$rfile" : '\(.*\)\.DAT'`
	sysvecho "$newrun: \c" >&2
	tore2run $fopt $topt "$rfile" "$newrun"
	if [ -z "$lastfile" -o "$filenum" -gt "$lastnum" ]
	then
		nsweeps=`(dd bs=1 count=79 2>/dev/null >&2; dd bs=2 count=1 2>/dev/null | od -t d2 -A n -v -w2 | sed 's/ //g') < "$rfile"`
		lastnum=`expr "$filenum" + "$nsweeps" - 1`
	else
 		echo Y | appendrun "$lastfile" "$newrun" 2>/dev/null &&
				rm -f "$newrun".frm "$newrun".txt "$newrun".w?? &&
				renamerun "$lastfile" "$newrun"
		if [ "$filenum" -ge "$lastnum" ]
		then
			nfrm=`dumprun "$newrun" | sed -n 's/^No. of frames:[ 	]*\([^ 	]*\)[ 	].*/\1/p'`
			[ "$nfrm" -gt 1 ] && echo "$newrun: $nfrm frames"
		fi
	fi
	lastfile=$newrun
    done
