#!/bin/bash
#
# shell-script iterprets parameters and starts simulator
#
# 15.12.2004 H. finster
#
#
#

#
# environment
#
work_root_d=$PWD/work
sim_d=$PWD/simulator
data_d=$sim_d/data
room_d=$data_d/rooms
noise_d=$data_d/noise
errorpattern_d=$data_d/errorpattern

echo $*


echo "============================================="

sessid=$1
echo "sessid :           $sessid"
room=$2
echo "room :             $room"
t60=$3
echo "t60 :              $t60"
noise=$4
echo "noise :            $noise"
sn=$5
echo "sn :               $sn"
filter=$6
echo "filter :           $filter"
codec=$7
echo "codec:             $codec"
errorrate=$8
echo "errorrate :        $errorrate"
dataformat=$9
echo "dataformat :       $dataformat"

#
# complete name and path of the input file
# (may be a tmp file with a cryptic name)
#
input_tmpfilename=${10}
echo "input_tmpfilename     $input_tmpfilename"

#
# basename of the original input file
# (as given by the user in the input dialog)
# used to derive the output-filename
#
input_basefilename=${11}
echo "input_basefilename $input_basefilename"

referrer_ip=${12}
echo "referrer-ip        $referrer_ip"
echo "============================================="



echo "start at "`date`



##
# split dataformat
# must be format dds
#
# with dd = one of wv (wav), be (big endian), le (little endian)
#
# s = sampling frequency ( 8 = 8kHz or 16 = 16kHz )
#

datarep=${dataformat:0:2}
fs=${dataformat:2}

echo "data-representation : $datarep"
echo "fs :                  $fs"

#===========================
#
# set up working directory

work_d=$work_root_d/$sessid

echo "working directory $work_d";

mkdir -p $work_d
mkdir -p $work_d/in
mkdir -p $work_d/out


#
#
#===========================
 
#===========================
# file format conversion
#
# @TODO conversion
#
# desired format is either (expressed in aplay parameters)
# aplay -r  8000 -f S16_LE
# aplay -r 16000 -f S16_LE
#
#

infile=$work_d/in/$input_basefilename
intermediatefile=$work_d/in/tmp.raw

echo "get the input file";
echo "-------------------------";


if [ $input_tmpfilename == "-" ] ; then
    #
    # name of transmitted tmp-file is '-'
    # this means, that no file has been transmitted at all
    # as the user did not specify a filename in the input dialog
    # this is ok: we will use a sample file
    #
    echo "no input-file specified, using sample file $sim_d/in.$fs.wav"
    cp $sim_d/in.$fs.wav $infile
else
    #
    # there is a non-default tmp-filename
    #
    echo "input-file specified $input_tmpfilename"
    if test -f $input_tmpfilename ; then
	#
	# the tmp-file exists, i.e. the user has transmitted
	# a new file
	#
	echo "temporary input-file exists, using it as input-file"
	echo "copy  $input_tmpfilename  $infile"
        cp  $input_tmpfilename  $infile		
    else
	#
	# the tmp-file does not exist
	# a copy should still exist as infile
	# (no action required)
	#
        echo "temporary input-file does not exist, using previous input-file $infile"
    fi
fi

#
# finally check, if an input file exists
#
if test -f $infile ; then
    echo "$infile exists: ok";
else
    echo "ERROR: upload failed" 1>&2;
    exit;
fi

#
# the uploaded file is $infile from here
# 



echo "file format conversion";
echo "-------------------------";

if [[ `file $infile | grep WAVE` ]] ; then
    #
    # convert (arbitrary) wav to raw
    #
    echo "convert WAV-File $infile into intermediatefile $intermediatefile with fs ${fs}000";

    sox $infile -s -r ${fs}000 -c 1 $intermediatefile 2>&1

elif [ $datarep == "le" ] ; then
    #
    # little endian
    #
    echo "LITTLE ENDIAN $fs -> copy";
    cp $infile $intermediatefile

elif [ $datarep == "be" ] ; then
    #
    # big endian
    #
    echo "BIG ENDIAN $fs -> swap bytes";

    sox -t raw -s -w -r ${fs}000 -x $infile  -s -r ${fs}000 -c 1 $intermediatefile 2>&1


else
    echo "ERROR: unknown data-format" 1>&2;
    exit;
fi


#
# now there should exist an intermediate raw file in the following format:
# fs = 8 / 16 kHz (as specified in $fs)
# 2 bytes per sample
# mono
# little-endian format
#

#
#end file format conversion
#===========================

echo "END file format conversion";


#============================
# create parameters to simulator
#

params=""

#
# room/reverberation
#
if [ $room != "-" ] ; then
	roompar=-room=$room_d/$room.$fs.wav
	echo "roompar: $roompar";

	if [ $room != "car" ] ; then
		t60par=-revt60=$t60
		echo "t60par: $t60par"
		roompar="$roompar $t60par"
	else
		t60="-";
	fi
	params="$params $roompar"
else
	t60="-";
fi


#
# noise
#
if [ $noise != "-" ] ; then
	noisepar="-snr=$sn -noise=$noise_d/$noise.$fs"
	echo "noisepar : $noisepar"
	params="$params $noisepar"
else
	# set sn to '-' if sn is not used in simulation
	sn="-";	
fi

#
# filter
#
if [ $filter != "-" ] ; then
	filterpar="-filter=$filter"
	echo "filterpar : $filterpar"
	params="$params $filterpar"
fi

#
# codec / errorpattern
#
if [ $codec != "-" ] ; then
	codecpar="-amrmode=MR${codec##*MR}"
	echo "codecpar : $codecpar"

	if [ $errorrate != "-" ] ; then
	    errorfilepar="-errorpattern=$errorpattern_d/pattern_${codec}_${errorrate}"
	fi

	params="$params $codecpar $errorfilepar "
else
	# set errorrate to '-' if no codec is used
	errorrate="-";
fi
	

#
#
#============================

#============================
# create result filename based on (possibly corrected) parameters
#

#
# field separator used in filenames
# (needed by parser in php-Script)
#
sep="+";

#
# create result-filename from session-id + parameters
#
result_filename=$work_d/out/$input_basefilename$sep$room$sep$t60$sep$noise$sep$sn$sep$filter$sep$codec$sep$errorrate

echo "result_filename :     $result_filename"


#
#
#============================






#============================
# process data
#

params="$params -dbg=10"
echo "PARAMS $params"

$sim_d/voice_transmission_simulator -fs=${fs}000 -in=$intermediatefile -out=$result_filename $params -normalize=1 2>&1 

#
# end process data
#============================


#
# check, if file has been created
#

if test -f $result_filename ; then
    echo "result $result_filename successfully created";
else
    echo "ERROR: simulation failed" 1>&2;
    exit;
fi

#=============================
#
# conversion to wav
#

sox -V -t raw -r ${fs}000 -w -s $result_filename $result_filename.wav 2>&1

rm $result_filename

#
# end conversion to wav
#
#=============================





echo "finish at "`date`
echo "============================================="

## echo "ok" 1>&2
