#!/bin/bash
# Signed 16 bit Little Endian, Rate 22050 Hz, Mono
#
# use "play" command to play back audio

# store location that this script is in
D="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
RAW_DIR="$D/audio/raw"
COOKED_DIR="$D/audio/cooked"
FLAC_DIR="$D/audio/cooked/flac"
MP3_DIR="$D/audio/cooked/mp3"

if [ "$1" = "-m" ]; then
  ENCODE_TO_MP3=YES
else
  ENCODE_TO_MP3=NO
fi

cd "$RAW_DIR"
for DIR in *; do
  if [ ! -d "$FLAC_DIR/$DIR" ]; then
    mkdir -p "$FLAC_DIR/$DIR"
  fi
  if [ "$ENCODE_TO_MP3" = "YES" ]; then
      if [ ! -d "$MP3_DIR/$DIR" ]; then
      mkdir -p "$MP3_DIR/$DIR"
    fi
  fi
  cd "$DIR"
  echo "working in $DIR"
  for INFILE in *.raw; do
    echo "working on $INFILE"
    FIX="`echo $INFILE | sed -e 's/^\[.*\] //g'`"
    BASENAME="`basename \"$FIX\" .raw`"
    TEMP_OUTFILE="$BASENAME.wav"
    echo "...converting to intermediate format $TEMP_OUTFILE"
    #sox -r 44100 -e unsigned -b 8 -c 1 <RAW_FILE> <TARGET_FILE>
    sox -r 22050 -e signed -b 16 -L -c 1 "$INFILE" "$TEMP_OUTFILE"
    if [ -f "$FLAC_DIR/$DIR/$BASENAME.flac" -o -f "$MP3_DIR/$DIR/$BASENAME.mp3" ] ; then
      FUDGE="$RANDOM"
      FLAC_FILE="$FLAC_DIR/$DIR/$BASENAME-$FUDGE.flac"
      MP3_FILE="$MP3_DIR/$DIR/$BASENAME-$FUDGE.mp3"
    else
      FLAC_FILE="$FLAC_DIR/$DIR/$BASENAME.flac"
      MP3_FILE="$MP3_DIR/$DIR/$BASENAME.mp3"
    fi
    if [ ! -f "$FLAC_FILE" ]; then
      echo "...converting it to FLAC: $FLAC_FILE"
      flac -s -8 "$TEMP_OUTFILE" -o "$FLAC_FILE" 
    else
      echo "...already converted"
    fi
    if [ "$ENCODE_TO_MP3" = "YES" ]; then
      if [ ! -f "$MP3_FILE" ]; then
        echo "...converting it to MP3: $MP3_FILE"
        lame --quiet --preset studio "$TEMP_OUTFILE" "$MP3_FILE"
      else
        echo "...already converted"
      fi
    fi
    rm -f "$TEMP_OUTFILE"
  done
  cd ..
done
