###############################################################################
#    Speaker spectrum mesure script
#    This script uses ALSA command to change input source and volume
###############################################################################
#
#  reference parameters
#  WhiteNoise:          $1 = W
#      Sampling Freq :  $2 =  48000 Hz
#      #Taps         :  $3 =   2048
#      Duration      :  $4 =     30 sec
#
#      Sampling Freq :  $2 =  96000 Hz
#      #Taps         :  $3 =   4096
#      Duration      :  $4 =     30 sec
#
#      Sampling Freq :  $2 = 192000 Hz
#      #Taps         :  $3 =   8192
#      Duration      :  $4 =     30 sec
#
#
#  SweptSine:           $1 =  S
#      Sampling Freq :  $2 =  48000 Hz
#      #Taps         :  $3 =   2048
#      Repeat Times  :  $4 =     32 times
#
#      Sampling Freq :  $2 =  96000 Hz
#      #Points       :  $3 =   4096
#      Duration      :  $4 =     32 times
#
#      Sampling Freq :  $2 = 192000 Hz
#      #Points       :  $3 =   8192
#      Duration      :  $4 =     32 times
#
#


#
#	set library path just in case
#
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH

#
#	pause audio processer
#
echo PAUSE >../pause.txt
echo QUIT  >../quit.txt
sleep 2

#
#    chenage input source to Mic
#    set up volume level and capturing gain
#
amixer -c 0 sset Master off
VOL=$(amixer -c 0 sget Master | grep "Playback [0-9]* \[[0-9]*%\]" | awk '{print $3}')
amixer -c 0 sset Master 52
amixer -c 0 sset 'Input Source,0' 'Mic'
amixer -c 0 sset 'Capture,0' 41
amixer -c 0 sset Master on
sleep 1

#
#    pre-measuring processing
#
D=$(date +"%y%m%d%H%M%S")

#
#    measure spectrum
#
if [[ "$1" == "S" ]]
then

	#    using Swept Sine signal

	DIR="ImpulseResponse_$D"
	mkdir ../$DIR
	cd ../$DIR
	../bin/sweptsine $2 1 $3 SSResponse.wav ImpulseResponse.wav InverseResponse.wav $4 response.wav inverse.wav

else

	#    using white noise

	DIR="FrequencySpectrum_$D"
	mkdir ../$DIR
	cd ../$DIR
	../bin/whitenoise $2 $3 $4 response.wav inverse.wav


fi

#
#    post-measuring processing
#
cd ../
chown -R toyozumi:toyozumi $DIR
chmod -R 777 $DIR
cp -f $DIR/inverse.wav  Filters/inverse_New.wav
chown toyozumi:toyozumi Filters/inverse_New.wav
chmod 777 Filters/inverse_New.wav


#    chenage input source to Line
#    restore the volume level and capturing gain
#
amixer -c 0 sset Master off
amixer -c 0 sset Master $VOL
amixer -c 0 sset 'Input Source,0' 'Line'
amixer -c 0 sset 'Capture,0' 20
amixer -c 0 sset Master on
sleep 1

#
#	resume audio processer
#
rm -f pause.txt

