#!/bin/sh
#
# nsm2run -- convert Rybak/Markin NSM simulation export files to run files
#
# Usage: nsm2run nsm-file [runfile]
#
# Input file format e.g. as follows (lines terminated by CR/LF or just LF):
# <Header>
# Generated by NSM v2.0
# Duration = 10000 msec
# Precision = 0.1 msec
# column_0 = Name # 1; min = 0.43; max = 2.08398; calibr = 0.000127196
# column_1 = Name # 2; min = 0.43; max = 1.79733; calibr = 0.0001097
# </Header>
#
# Duration & Precision in ms, Precision is 1.0 / sampling frequency in KHz.
# calibr is mV / AD-level, so 1.0 / calibr gives ca_height for ca_level of 1000
# No. of channels determined by no. of column_* lines.
# samples follow header, all channels interleaved, all values little-endian
# 16-bit 2's complement (short) integers.

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

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

if [ ! -r "$ifile" ]
then
	echo "$0: Can't read nsm file: $ifile" >&2
	exit 1
fi
(
	lines=
	while read line
	do
		lines="$lines$line
"
		case "$line" in
		*/Header*)	break ;;
		esac
	done
	eval `echo "$lines" | tr -d '\015' |
	      awk '/^Duration/	{ duration=$3 }
		   /^Precision/	{ precision = $3; freq = 1000.0 / $3 }
		   /^column/	{ ++nchan }
		   END	{ nsamp = duration * freq / 1000.0;
			  printf("nsamp=%d nchan=%d freq=%g duration=%g precision=%g\n", nsamp, nchan, freq, duration, precision) }'`
	fsize=`ls -l "$ifile" | awk '{print $5}'`
	hsize=`echo "$lines" | wc -c | tr -d ' '`
	fsizehdr=`expr "$nchan" \* "$nsamp" \* 2 + $hsize - 1`
	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 duration in $ifile: $duration ($nsamp samples)" >&2
		case "$ignorelen" in
		y)	echo "$0: Continuing anyway..." >&2 ;;
		*)	exit 1 ;;
		esac
	fi
	if [ "$freq" -lt 1 -o "$freq" -gt 100000 ]
	then
		echo "$0: Invalid precision in $ifile: $precision ($freq Hz)" >&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
	 echo "$lines" | tr -d '\015' |
	   sed -n 's/^column_[0-9]* = \([^;]*\); .*calibr = \(.*\)/\2 \1/p' |
	   while read calib name
	   do
		level=`echo "16384000 * $calib + 0.5" | bc | sed 's/\..*//'`
		echo "cw$i"
		echo "l$level"
		echo "h16384"
		echo "z0"
		echo "n$name"
		sysvecho "qq\c"
		i=`expr $i + 1`
	   done
	echo "csqqyn") | TERM=dumb DISPLAY= analysis "$ofile" > /dev/null 2>&1
) < $ifile
