#!/bin/bash

# this script is written by Peter Plessas
# and was published through http://plessas.mur.at
# It is released under the GNU/GPL license
# and requires aubiocut, sox, awk, seq 
#
# This is version 20161211 (switched to aubioonset and timestamps in samples)

# check if the input file exists and is readable
if [ ! -f $1 ]; then echo "Input file does not exist or is not readable"; exit 1; fi

# have at least two arguments been specified?
if [ "$#" -lt 2 ]; then echo "Two arguments required"; exit 1; fi

# if only two arguments, set threshold to default value 0.3
if [ "$#" -lt 3 ]; then THRESH=0.3; else THRESH=$3; fi

# get input file properties
INPUTRATE=`sox --i -r $1`
INPUTCHN=`sox --i -c $1`
INPUTBITS=`sox --i -b $1`
INPUTENC=`sox --i -e $1`

# Check for encodings not supported by aubiocut.
if [ "$INPUTENC" = "Signed Integer PCM" ]
then
	INPUTENC="signed-integer"
elif [ "$INPUTENC" = "Unsigned Integer PCM" ]
then
	INPUTENC="unsigned-integer"
elif [ "$INPUTENC" = "Floating Point PCM" ]
then
	INPUTENC="floating-point"
else 
	# exit with error message
	echo "pp_shuffleOnset.sh: Input file encoding" $INPUTENC" not accepted. Exiting."
	exit 1
fi

# get input file length in seconds
INPUTLEN=`/usr/bin/sox --i -D $1`

# lets get the splicepoints into an array
splicelist=( $(aubiocut -i $1 -t $THRESH -M 100ms) )

# and get the length of this array
LISTLEN=${#splicelist[*]}

# add zero element to beginning, and INPUTLEN to end of array
splicelist=(0, ${splicelist[@]}, $INPUTLEN)
# Now 2 entries larger than LISTLEN, but since indices is created from zero onwards and we don't request the last entry of the array, LISTLEN is just fine.

# create an array of randomized indices
indices=`seq 0 $LISTLEN | sort -R`

for index in $indices;
do
	# get start- and endposition in seconds and convert to samples
        TRIMSTART=${splicelist[$index]}
	TRIMSTART=`echo $TRIMSTART $INPUTRATE | awk '{print int($1 * $2)}'`
	TRIMEND=${splicelist[`expr $index + 1`]}
	TRIMEND=`echo $TRIMEND $INPUTRATE | awk '{print int($1 * $2)}'`

	# this is where the work is done to stdout
	sox $1 -t raw - trim ${TRIMSTART}s =${TRIMEND}s

# and here the stdin is assembled into a file after the loop has exited.
done | sox -t raw -b $INPUTBITS -r $INPUTRATE -c $INPUTCHN -e $INPUTENC - $2

exit 0

# TODO:
# switch to aubioonset and have it report times as samples?
# aubiocut writes 16bit samples regardless of input sample format
# have aubiocut read from stdin directly? This way we could convert certain (which?) input file to its input directly
# are we handling spaces in paths or filenames correctly?
# let's skip slices and handle them in groups. Means: Decrease amount of counter indices, increase counter hopsize and lookup posision in the second table accordingly.
# set/increase aubiocut's -M (inter onset minimum interval" from script call as argument with optional default?
# arguments by -t -M keywords?