#!/usr/bin/env bash

m=$HOME/tmp/$$.dat
test -d $HOME/tmp || mkdir -p $HOME/tmp
trap "rm -f $m" EXIT

#Calculate the loudness of the main microphone
#signal.

function g_die() { x="ERR: $*"; echo $x; echo $x 1>&2; exit 1;}

ES=$(type -p emphasis_stevens.py) || g_die "Cannot find emphasis_stevens.py" || exit 3
CODE="$ES"
DB='DB.fiat'
DBD='.'
DT=0.010
CLUSTERSIZE=0
DT=0.010
rewrite=''
s='True'
while true
do
	arg=$1; shift;
	case "$arg" in
	'') break;;
	--) break;;
	-harmless) CODE='';;
	-rewrite) rewrite=$m;;
	-j) CLUSTERSIZE=$1; shift;;
	-qmake) CLUSTERSIZE=$1; shift;;
	-s) s="$1"; shift;;
	-dt) DT=$1; shift;;
	-db) DB="$1"; DBD=$(dirname "$1"); shift;;
	*)	g_die "Unrecognized arg: $arg" || exit 2;;
	esac
done

if test "$CLUSTERSIZE" -gt 0 && type qmake >/dev/null 2>&1
then
  np=''
  make="qmake -V -cwd -- -j $CLUSTERSIZE"
else
  np=-j\ $(grep '^processor.:' /proc/cpuinfo | wc -l)
  make=make
fi

>$m
echo DT=$DT >>$m
echo CODE=$CODE >>$m
echo ES=$ES >>$m
echo REWRITE=$rewrite >>$m
echo '.PHONY: all' >>$m
echo '.SUFFIXES:' >>$m
echo >>$m

select_fiat_entries.py -select "$s" -penv 'import os.path' -penv "_dir='$DBD'" -show "'all : %s\n' % os.path.join(_dir, d, f, 'loud.dat')" $DB >>$m

cat <<'ENDEND' >>$m

%/loud.dat : %/raw.dat $(CODE) $(REWRITE)
	mkdir -p $$(dirname $*); python $(ES) -write BITPIX=-32 -dt $(DT) -f $*/raw.dat -c 0 -o $@

ENDEND

$make $np -f $m || g_die "$0 fails!" 
