#!/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 sox and awk
#
# This is version 20161211

# get samplerate
SR=`soxi -r "$1"`

# get duration in samples and divide by two
DUR_SAM=`soxi -s "$1"`
# odd durations will be truncated to next lower even number
HALFDUR_SAM=`expr $DUR_SAM / 2`

# crossfade length in samples, truncated to integer
XFADE_SAM=`echo $3 $SR | awk '{print int($1 * $2)}'`

# each side of the excess is half the crossfade
EXCESS_SAM=`expr $XFADE_SAM / 2`

# splice position has to be duration plus excess, all in samples
POS_SAM=`expr $HALFDUR_SAM + $EXCESS_SAM`

# cut the input file in two halves
sox "$1" /tmp/tmp1.wav trim 0 `echo $HALFDUR_SAM`s
sox "$1" /tmp/tmp2.wav trim -`echo $HALFDUR_SAM`s

# splice together the two halves in flipped order and apply crossfade
# sox tmp2.wav tmp1.wav $2 splice -q `echo $POS_SAM`s,`echo $EXCESS_SAM`s,0s
sox /tmp/tmp2.wav /tmp/tmp1.wav $2 splice -q `echo $HALFDUR_SAM`s,`echo $EXCESS_SAM`s,0s

# delete temporary files
rm /tmp/tmp1.wav /tmp/tmp2.wav

# TODO:
# use sox --i instead of soxi
# crossfades of exactly half the filesize are not possible
# due to the creation/deletion of hardcoded tmp files only one invocation of this script can be active
# howto create two file names with a unique identifier name?
# check for correct number and type of arguments, if files and directories are writeable and if awk and sox(i) are installed
# suppress SoX warning
