#!/bin/sh
#
# raw2run -- convert U of Montreal .raw or .ave files to run files
#
# Usage: raw2run raw-file [runfile]
#
# Input file format is as follows:
# 12 byte header, all values little-endian:
#   0-1:	gain (1,2,5,10,20,50,100 -> +/-5V / gain, -1,9999 -> +/- 10V)
#   2-3:	# of samples in average (I'm guessing)
#   4-7:	# of samples per channel (32-bit)
#   8-9:	# of channels
# 10-11:	sampling frequency (Hz)
# samples follow header, all channels interleaved, all values little-endian

ignorelen=n
case "$1" in
-i)	ignorelen=y ; shift ;;
esac
if [ "$#" -lt 1 -o "$#" -gt 2 ]
then
	echo "Usage:  $0 raw-file [runfile]" >&2
	exit 1
fi

ifile="$1"
ofile="${2:-$1}"
case `basename "$ofile"` in
*.raw)		ofile=`expr "$ofile" : '\(.*\)\.raw$'` ;;
*.ave)		ofile=`expr "$ofile" : '\(.*\)\.ave$'` ;;
#???????????*)	ofile=`expr "$ofile" : '\(.*/..........\).*$'` ;;
esac

if [ ! -r "$ifile" ]
then
	echo "$0: Can't read raw file: $ifile" >&2
	exit 1
fi
(
	gain=`dd bs=2 count=1 2>/dev/null | od -t d2 -A n -v -w2 | sed 's/ //g'`
	nsweeps=`dd bs=2 count=1 2>/dev/null | od -t d2 -A n -v -w2 | sed 's/ //g'`
	nsamp=`dd bs=4 count=1 2>/dev/null | od -t d4 -A n -v -w4 | sed 's/ //g'`
	nchan=`dd bs=2 count=1 2>/dev/null | od -t d2 -A n -v -w2 | sed 's/ //g'`
	freq=`dd bs=2 count=1 2>/dev/null | od -t d2 -A n -v -w2 | sed 's/ //g'`
	fsize=`ls -l "$ifile" | awk '{print $5}'`
	fsizehdr=`expr "$nchan" \* "$nsamp" \* 2 + 12`
	case "$gain" in
	1|2|5|10|20|50|100)	level=`expr 5000000 / $gain` ;;
	-1|9999)		gain=0.5; level=10000000 ;;
	#1)	gain=5 level=5000 ;;
	#-1)	gain=10 level=10000 ;;
	#9999)	gain=10000 level=10000 ;;
	#9999)	gain=10000 level=10000000 ;;
	*)	echo "$0: Invalid gain code in $ifile: $gain" >&2
		exit 1 ;;
	esac
	if [ "$nsweeps" -lt 0 ]
	then
		echo "$0: Invalid sweep count in $ifile: $nsweeps" >&2
		exit 1
	fi
	if [ "$nchan" -lt 1 -o "$nchan" -gt 16 ]
	then
		echo "$0: Invalid channel count in $ifile: $nchan" >&2
		exit 1
	fi
	if [ "$nsamp" -lt 1 -o "$fsize" -ne "$fsizehdr" ]
	then
		echo "$0: Invalid sample count in $ifile: $nsamp" >&2
		case "$ignorelen" in
		y)	echo "$0: Continuing anyway..." >&2 ;;
		*)	exit 1 ;;
		esac
	fi
	if [ "$freq" -lt 1 -o "$freq" -gt 32767 ]
	then
		echo "$0: Invalid frequency in $ifile: $freq" >&2
		exit 1
	fi
	dsepr -f"$freq" -nu"$nchan" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -o "$ofile"
	(i=0
	while [ "$i" -lt "$nchan" ]
	do
		echo "cw$i"
		echo "l$level"
		echo "h2048"
		echo "z0"
		sysvecho "qq\c"
		i=`expr $i + 1`
	done
	echo "csqqyn") | TERM=dumb DISPLAY= analysis "$ofile" > /dev/null 2>&1
) < $ifile
