#!/usr/bin/env bash

m=$HOME/tmp/$$.dat
test -d $HOME/tmp || mkdir -p $HOME/tmp
trap "rm -f $m" EXIT
trap '' SIGHUP
echo '#' $(date) >>LOG
echo $0 $* >>LOG

#Calculate the quasi-duration of the main microphone signal.
function g_die() { x="ERR: $*"; echo $x; echo $x 1>&2; exit 1;}

OV=$(type -p pseudoduration.py) || g_die "Cannot find pseudoduration.py" || exit 1
CODE="$OV"

CLUSTERSIZE=0

DT=0.010
rewrite=''
s='True'
DB='DB.fiat'
DBD='.'
misc=''
pdmisc=''
debug=0
make=make
write='-write BITPIX=0'
while true
do
	arg=$1; shift;
	case "$arg" in
	'') break;;
	--) break;;
	-harmless) CODE='';;
	-rewrite) rewrite=$m;;
	-debug) debug=1;;
	-j) CLUSTERSIZE=$1; shift;;
	-qmake) make="qmake -V -cwd --" ;;
	-db) DB="$1"; DBD=$(dirname "$1"); shift;;
	-dbav) DB="-rav $1"; DBD=$(dirname "$1"); shift;;
	-k |-t) misc="$misc $arg" ;;
	-dur|-logdur|-ctr) pdmisc="$pdmisc $arg" ;;
	-s) s="$1"; shift;;
	-write) write="-write $1"; shift; ;;
	-dt) DT=$1; shift;;
	--) break;;
	*)	g_die "Unrecognized arg: $arg" || exit 2;;
	esac
done

if test "$CLUSTERSIZE" = 0 
then
  np=-j\ $(grep '^processor.:' /proc/cpuinfo | wc -l)
else
  np="-j $CLUSTERSIZE"
fi

>$m
echo DT=$DT >>$m
echo CODE="$CODE" >>$m
echo OV="$OV" >>$m
echo WRITE="$write" >>$m
echo REWRITE="$rewrite" >>$m
echo pdmisc="$pdmisc" >>$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, 'pdur.dat')" $DB >>$m

cat <<'ENDEND' >>$m

%/pdur.dat : %/raw.dat $(CODE) $(REWRITE)
	mkdir -p $$(dirname $*); python $(OV) $(WRITE) -dt $(DT) $(pdmisc) -f $*/raw.dat -c 0 -o $@

ENDEND

if test $debug = 0
then
  $make $np $misc -f $m || g_die "$0 fails!" 
else
  cat $m
fi
