#!/bin/bash

set -e
set -o pipefail

RECORD=$1 # Something like 'a0001'

# Validate input argument.
# TODO: Remove
# if [[ "$RECORD" =~ ^.*\.wav$ ]]; then
#     RECORD_FILE="$RECORD"
# else
#     RECORD_FILE="$RECORD.wav"
# fi
# 
# if [ ! -f "$RECORD_FILE" ]; then
#    echo "File does not exist: $RECORD_FILE"
#    exit 1;
# fi
RECORD_FILE="$RECORD"

MATLAB='matlab -nosplash -nodisplay -nojvm -r'
PYTHON='python3'

TRAINING='./trained-parameters'
TMP='./tmp'
mkdir -p $TMP

# 0: Run Springer segmentation.
$MATLAB "do_single_segmentation('$RECORD_FILE', '$TMP/segmented.mat'); exit();"

# 1: Apply scattering transform.
$PYTHON do_scattering.py -i $TMP/segmented.mat -o $TMP/raw_features.mat

# 2: Perform dimensionality reduction.
$PYTHON dim-reduction.py -i $TMP/raw_features.mat -o $TMP/reduced.mat -p $TRAINING/dim-reduction.pkl
# $MATLAB "do_ols('$TMP/raw_features.mat', '$TMP/reduced.mat', '$TRAINING/olsparams.mat'); exit();"
#$PYTHON do_ols_test.py -i $TMP/raw_features.mat -o $TMP/reduced.mat -p $TRAINING/olsparams.mat

# 3: Append summary features
echo 'append summary features...'
$PYTHON append_summary_features.py --deep $TMP/reduced.mat --summary $TMP/segmented.mat --segment $TMP/segmented.mat -o $TMP/final_features.mat

# 5: Normalize
echo 'normalize'
$PYTHON normalize.py -i $TMP/final_features.mat -o $TMP/normalized_features.mat -p $TRAINING/normalize.pkl

# 7: Classify the feature vector.
$PYTHON classifier.py -i $TMP/normalized_features.mat -p $TRAINING/classifier.pkl -o $TMP/prediction.txt

# 7: Append result to answers.txt.
echo -e "$RECORD_FILE,\c" >> answers.txt
cat $TMP/prediction.txt >> answers.txt


# Cleanup
rm -rf $TMP
