#!/bin/bash

[ $# -eq 0 ] && {
    echo "Usage:"
    echo "  $0 path/to/wav_or_trs"
    exit 1
}

MXMLC=/usr/local/flex/bin/mxmlc
TMP=/tmp/book/
rm -fr $TMP
mkdir -p $TMP
cd $TMP
$OLDPWD/cut.py $1 | sh

echo 'package
{
    import flash.display.Sprite;
    public class snd_small extends Sprite
    {
        [Embed(source="snd_small.mp3", mimeType="audio/mpeg")]
        public var small:Class;
    }
}' > snd_small.as

echo 'package
{
    import flash.display.Sprite;
    public class snd extends Sprite
    {' > snd.as

function compile()
{
    timeout 6s $MXMLC snd_small.as >/dev/null 2>&1
    if [ $? -eq 124 ]
    then
        echo $file again
        lame $file 2>/dev/null
        mv $file.mp3 $file
        compile
    fi

}

for file in *mp3
do
    trap exit TERM INT
    [[ $file == snd_small.mp3 ]] && continue
    echo $file
    ln -sf $file snd_small.mp3
    compile
    base=$(basename $file .mp3)
    echo "\
        [Embed(source='$file', mimeType='audio/mpeg')]
        public var $base:Class;
    " >> snd.as
done

echo "\
    }
}" >> snd.as
$MXMLC snd.as
#cp snd.swf $OLDPWD/$2_snd.swf
