#! /bin/bash

# file: score			G. Moody	22 December 2013
#				Last revised:	 6 January 2014
# Challenge 2014 evaluation, stage 4:  calculate scores

# Define pathnames of needed tools not in the default PATH. 'bxb' and
# 'sumstats' are components of the WFDB Software Package, and 'field' is
# compiled from http://physionet.org/physiotools/utilities/field.c .
BXB=/usr/local/bin/bxb
FIELD=/usr/local/bin/field
SUMSTATS=/usr/local/bin/sumstats

# Unpack the results and reference annotations, and the .hea files, into the
# temporary directory.
( uudecode | tar xfz - -C $WDIR ) 2>&1 || exit 1
tar xfz `dirname $0`/data/set-t-atr.tar.gz -C $WDIR 2>&1 || exit 1
tar xfz `dirname $0`/data/set-t-hea.tar.gz -C $WDIR 2>&1 || exit 1

# Work within the temporary directory.
cd $WDIR

# If stage 3 timed out, print its report and exit without a score.
if grep -q "Stage 3 timed out" report; then
    cat report
    exit 1
fi

# Report numbers of timeouts and failures if any occurred.
if ! grep -q success report; then
    cat report
fi

# Compare the .atr and .qrs files for each record.
for R in `cat RECORDS`
do
    if [ ! -e $R.qrs ]; then
	cp missing.qrs $R.qrs
    fi
    $BXB -r $R -a atr qrs -f 0 -t 10:01 -l eval.out seval.out >/dev/null 2>&1
done

# Calculate and print the summary statistics.
echo "+++ Scores +++"
echo -e "\tSe (%)\t+P (%)"
$SUMSTATS eval.out | tail -5 | head -2 | $FIELD -w 1 2 3 | tee stats
GS=`grep Gross stats | $FIELD 3`
GP=`grep Gross stats | $FIELD 2`
AS=`grep Average stats | $FIELD 3`
AP=`grep Average stats | $FIELD 2`
OV=`echo "$GS $GP $AS $AP + + + 0.25 * p" | dc`
echo "Overall     $OV"

# Successful exit.
exit 0
