#! /bin/bash -e

#####################################################################
#                                                                   #
#               Process files with Faust DSP                        #
#               (c) Grame, 2017                                     #
#                                                                   #
#####################################################################

. faustpath
. faustoptflags
. usage.sh

CXXFLAGS+=" $MYGCCFLAGS"  # So that additional CXXFLAGS can be used

ARCHFILE=$FAUSTARCH/sndfile.cpp

#-------------------------------------------------------------------
# Set Faust include path

CXX=g++

#PHASE 2 : dispatch command arguments
while [ $1 ]
do
    p=$1

    if [ $p = "-help" ] || [ $p = "-h" ]; then
        usage faust2sndfile "[Faust options] <file.dsp>"
        require libsndfile
        echo "Process files with Faust DSP"
        option "Faust options"
        exit
    fi
    
    if [ ${p:0:1} = "-" ]; then
        OPTIONS="$OPTIONS $p"
    elif [[ -f "$p" ]] && [ ${p: -4} == ".dsp" ]; then
        FILES="$FILES $p"
    else
        OPTIONS="$OPTIONS $p"
    fi

shift

done

#-------------------------------------------------------------------
# compile the *.dsp files
#

for f in $FILES; do

	SRCDIR=$(dirname "$p")
	LINPUTS=$(faust $OPTIONS -uim "$f" | grep FAUST_INPUTS)
	NINPUTS=${LINPUTS//[^0-9]/}
	if [ $NINPUTS -gt 0 ]; then
		echo "Will process an input file to produce an output file"
		echo "With the compiled program 'foo', you can add [-c samples] for the number of frames to append beyond the input file"
		ARCHFILE=$FAUSTARCH/sndfile.cpp
	else
		echo "Will generate an output file"
		echo "With the compiled program 'foo' you can add:"
		echo "[-bd 16|24|32] to setup the output file bit-depth (default: 16)"
		echo "[-sr <num>] to setup the output file sample rate (default: 44100)"
		echo "[-s <num>] to setup the output file length in frames (default: SR*5)"
		ARCHFILE=$FAUSTARCH/synthfile.cpp
	fi

    # compile Faust DSP then create the binary
    faust -i -a $ARCHFILE $OPTIONS "$f" -o "$f.cpp" || exit
    (
        $CXX $CXXFLAGS "$f.cpp" `pkg-config --cflags --static --libs sndfile` -o "${f%.dsp}"
    ) > /dev/null || exit

    # remove c++ file
    rm "$f.cpp"
    
    # collect binary file name for FaustGIDE
    BINARIES="$BINARIES$SRCDIR/${f%.dsp}"
 
done

echo $BINARIES
