#!/bin/sh

umask 0
ffmpeg="/Users/bbraun/bin/ffmpeg"
sox="/Users/bbraun/bin/sox"
gnuplot="/Users/bbraun/bin/gnuplot"
infile="$1"
mkdir -p athumb
mkdir -p thumbnails
`$ffmpeg -i "$infile" -ar 1000 -y "athumb/$infile.wav" > /dev/null 2>&1`
`$sox "athumb/$infile.wav" -r 1000 -c 1 athumb/tmpplot.dat`
echo "set terminal png" > athumb/tmp.plot
echo "set output \"athumb/$infile.png\"" >> athumb/tmp.plot
echo "set datafile commentschars \";\"" >> athumb/tmp.plot
echo "plot \"athumb/tmpplot.dat\" with lines" >> athumb/tmp.plot
`$gnuplot athumb/tmp.plot`
loudframe=`perl -e '$max=-1e38; while (<>) {@t=split; $max=$t[0] if $t[0]>$max}; print $max' < athumb/tmpplot.dat`

#if [ -z "$loudframe" -o "$loudframe" -eq 0 ]; then
if [ -z "$loudframe" ]; then
	loudframe=30
fi

`$ffmpeg -i "$infile" -vframes 1 -itsoffset $loudframe "thumbnails/$infile.jpg" > /dev/null 2>&1`
