#! /bin/bash -e

#####################################################################
#                                                                   #
#               Compiles Faust programs to a fausgen~ patch         #
#               (c) Grame, 2015-2025                                #
#                                                                   #
#####################################################################

. faustpath
. faustoptflags
. usage.sh

POLY="MONO"
NVOICES=-1
MC="0"

JSFILE_PATH="ui.js"

echoHelp()
{
    usage faust2gen "[options] <file.dsp>"
    require Max/MSP SDK
    echo "Compiles Faust programs to a fausgen~/mc.faustgen patch"
    option
    option '-nvoices <num>'
    option -mc "to activate multi-channels model"
    exit
}

if [ "$#" -eq 0 ]; then
    echo 'Please, provide a Faust file to process !'
    echo ''
    echoHelp
fi

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

    if [ $p = "-help" ] || [ $p = "-h" ]; then
       echoHelp
    elif [ $p = "-mc" ]; then
        MC="1"
    elif [[ -f "$p" ]] && [ ${p: -4} == ".dsp" ]; then
        FILES="$FILES $p"
    elif [ $p = "-nvoices" ]; then
        POLY="POLY1"
        shift
        NVOICES=$1
        if [ $NVOICES -ge 0 ]; then
            CXXFLAGS="$CXXFLAGS -DNVOICES=$NVOICES"
        fi
    else
        OPTIONS="$OPTIONS $p"
    fi

shift

done

# look for polyphonic "nvoices" metadata in the DSP file

grep "declare nvoices" $FILES && POLY="POLY1" 2>/dev/null

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

for p in $FILES; do

    f=$(basename "$p")

    # create Max patch
    if [ $POLY = "POLY1" ]; then
    	if [ $MC = "1" ]; then
        	cat $FAUSTARCH/max-msp/mc-faustgen-wrapper-poly.maxpat > ${f%.dsp}-temp1.maxpat
        else
        	cat $FAUSTARCH/max-msp/faustgen-wrapper-poly.maxpat > ${f%.dsp}-temp1.maxpat
        fi
    else
    	if [ $MC = "1" ]; then
        	cat $FAUSTARCH/max-msp/mc-faustgen-wrapper.maxpat > ${f%.dsp}-temp1.maxpat
        else
        	cat $FAUSTARCH/max-msp/faustgen-wrapper.maxpat > ${f%.dsp}-temp1.maxpat
        fi
    fi
    sed -e "s/DSP_NAME/"${f%.dsp}"/g" ${f%.dsp}-temp1.maxpat >> ${f%.dsp}-temp2.maxpat
    sed -e "s/UI_FILE/"$JSFILE_PATH"/g" ${f%.dsp}-temp2.maxpat > ${f%.dsp}.maxpat

    # collect binary file name for FaustGIDE
    BINARIES="$BINARIES${f%.dsp}.maxpat;"

    # copy JavaScript UI file
    cp $FAUSTARCH/max-msp/ui.js .

    rm ${f%.dsp}-temp1.maxpat
    rm ${f%.dsp}-temp2.maxpat

done

BINARIES="$BINARIES ui.js"

echo $BINARIES
