#!/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_listen [options] [channel] [file]

Read audio PCM from dense modem on "channel" [0].
Write audio to "file" [/dev/audio].
If file is suffixed .wav, write a WAV file, else write an .au file.

Options:
	-b board	Select board number [0]
	-t txgain	Set Tx Gain [0x4000]
	-r rxgain	Set Rx Gain [0x4000]

Options (when writing to a file):
	-U		8 bit uLaw [default]
	-A		8 bit ALaw
	-s		16 bit signed linear
	-S		Set stereo mode (forces gains and sets uLaw)
EOF
	exit 1
}

data=ulaw
channels=
board=0
rxgain=0x4000
txgain=0x4000

soxdata_in="-b -U"

# wavplay only can deal with unsigned linear data...
soxdata_out="-u"

while getopts b:r:t:SsUAh? opt
do
        case $opt in
	b)	board="$OPTARG";;
	r)	rxgain="$OPTARG";;
	t)	txgain="$OPTARG";;
	s)	data=linear; soxdata_in="-w -s"; soxdata_out="-w -s";;
	U)	data=ulaw;   soxdata_in="-b -U"; soxdata_out="-u";;
	A)	data=alaw;   soxdata_in="-b -A"; soxdata_out="-u";;
	S)
		data=linear;	# A convenient lie
		soxdata_in="-b -U -c 2"
		soxdata_out="-u -c 2"
		rxgain=0	# Gain 0,0 selects this mode in DSP
		txgain=0	# Gain 0,0 selects this mode in DSP
		;;
        h|\?)	usage;;
        esac
done
shift `expr $OPTIND - 1`

case "$#" in
0)
	chan=0
	file=/dev/audio
	;;
1)
	chan=$1
	file=/dev/audio
	;;
2)
	chan=$1
	file=$2
	;;
esac

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

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

trap "die" 1 2 15

case "$file" in
*.wav)
	sox -t raw $soxdata_in -r 8000 - -t wav $soxdata_out $file \
		< $device &
	;;
*)
	cat $device > $file &
	;;
esac

echo "$data $chan $rxgain $txgain 0" > $device

wait
