#!/bin/sh

# Copyright 1999 by Digi International (www.digi.com)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED; without even the 
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
# PURPOSE.  See the GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#


usage() {
cat <<EOF
Usage:
	dm_eqm [options] [channel] [file]

Read Eye Quality data from dense modem on "channel" [0].
Write the data to "file".  The default output file name
is $basefile.bin for format -f binary, $basefile.txt for
format -f ascii, and $basefile.xplot for format -f xplot.

Options:
	-b board	Select board number [0]
	-f format	Set output format (ascii, binary, xplot) [binary]
			ascii is two numbers per line.
			binary is 16 bit signed
			xplot is an xplot 0.81 formatted file
	-m mode		XY data to collect (eqm, pcm, "x,y") [eqm]
	-n samples	Collect <samples> [infinite]
	-r rate		Sample rate in HZ [100]

NOTE:
	When set for -f xplot format, the raw binary data is also saved
	to the basename of "file" suffixed with .bin.
EOF
	exit 1
}

basefile=eqmdata
suffix=bin
board=0
data=binary
mode=eqm
rate=100
samples=0
xplot=0

while getopts b:f:m:n:r:? opt
do
        case $opt in
	b)	board="$OPTARG";;
	f)
		case "$OPTARG" in
		a*|A*)	data=ascii; suffix=txt;;
		b*|B*)	data=binary; suffix=bin;;
		x*|X*)	data=binary; suffix=xplot; xplot=1;;
		*)	usage;;
		esac
		;;
	m)	mode="$OPTARG";;
	n)	samples="$OPTARG";;
	r)	rate="$OPTARG";;
        h|\?)	usage;;
        esac
done
shift `expr $OPTIND - 1`

case "$mode" in
eqm|pcm);;
*)
	mode=`echo "xy $mode" | sed 's/,/ /'`
	;;
esac

case "$#" in
0)
	chan=0
	file=$basefile.$suffix
	;;
1)
	chan=$1
	file=$basefile.$suffix
	;;
2)
	chan=$1
	file=$2
	basefile=`echo "$file" | sed 's/\.[^.]*$//'`
	;;
esac

device=/dev/dg/dgdm/eqm$board

die() {
	echo "stop" > $device;
	# trap "kill 0; exit" 1 2 15
}

trap "die" 1 2 15

if [ $xplot = 1 ]; then
	tee $basefile.bin < $device |
	perl \
		-e 'print "signed signed\n";'			\
		-e 'while (read(STDIN, $buf, 4)) {'		\
		-e '	@val = unpack("ss", $buf);'		\
		-e '	print "dot @val[0]  @val[1]\n";'	\
		-e '}'						\
	> $file &
else
	cat $device > $file &
fi

echo "$mode $data $chan $rate $samples" > $device

wait
