#!/bin/bash


function processSound
{
    INFILE="$1"
    OUTFILE="$2"
    VOL="$3"

    FREQ=""
    if [ ! -z "$4" ]
    then
        FREQ="-r $4"
    fi

    TARGETSIZE="$5"

    echo
    echo "Creating sound file $OUTFILE"
    sox -v "$VOL" "$INFILE" -c 1 $FREQ --bits 8 --encoding unsigned "$OUTFILE"
    tr '\0' '\1' < "$OUTFILE" > "$OUTFILE.tmp"
    mv "$OUTFILE.tmp" "$OUTFILE"

    if [ ! -z "$TARGETSIZE" ]
    then
        CURRSIZE=`stat -f '%z' "$OUTFILE"`
        if [ $CURRSIZE -lt $TARGETSIZE ]
	    then
	        BYTESTOADD=`expr $TARGETSIZE - $CURRSIZE`
	        dd if=/dev/zero bs="$BYTESTOADD" count=1 2> /dev/null | tr '\0' '\177' >> "$OUTFILE"
	    fi
	    if [ $CURRSIZE -gt $TARGETSIZE ]
	    then
	        dd if="$OUTFILE" bs="$TARGETSIZE" count=1 of="$OUTFILE.tmp" 2> /dev/null
	        mv "$OUTFILE.tmp" "$OUTFILE"
	    fi
    fi

    dd if=/dev/zero bs=1 count=1 2> /dev/null | cat >> "$OUTFILE"
}


DEFAULT_FREQ=11025
export LC_CTYPE=C

processSound segments.wav ../segments.raw 1.0 $DEFAULT_FREQ 2940
processSound bonus.wav ../bonus.raw 1.0 $DEFAULT_FREQ
processSound death.wav ../death.raw 1.0 $DEFAULT_FREQ
processSound fire.wav ../fire.raw 1.0 $DEFAULT_FREQ
processSound kill.wav ../kill.raw 1.0 $DEFAULT_FREQ
processSound spider.wav ../spider.raw 1.0 $DEFAULT_FREQ 14700
processSound extralife.wav ../extralife.raw 1.3 5513
processSound flea_loop_256b.wav ../flea.raw 2.2 "" 255
processSound scorpion.wav ../scorpion.raw 4.5 $DEFAULT_FREQ
