#!/bin/bash

# functions
encode() { # put your encoding settings here

    when=$(date +%Y%m%d%H%M%S)
    FFREPORT=file="$log/$baseext.$when.log":level=32 \
    ffmpeg -hide_banner -loglevel quiet -i "$file" -af volume="$r128"dB -vn -y -c:a flac -ar 41000 -sample_fmt s16 "$tmpdir/$base.flac" 
}
# help
if [ $# -eq 0 ]; then echo "anything to flac for CD at 44100 Hz"; exit 1; fi

# source config file and timer
config="$HOME/bin/singularity.cfg"
if [ -e "$config" ]; then
    source "$config"
else 
    echo "$config does not exist"; exit 1
fi 

source "$HOME/bin/timer_func"

# main
while [ $# -gt 0 ]; do

    file=$(readlink -f "$1")
    # echo ".............................."
    echo "$file"
    baseext=$(basename "${1}")     # file.ext
    base="${baseext%.*}"           # file

    echo "$out/$base.flac"

    hasAudio "$file" || { >&2 echo "No Audio in $file" ; shift; continue; } # "continue" should skip to next file in this while loop.
    
    #if $(isMXF "$file"); then
    #echo "MXF detected"
    #MXFdownmix "$file" "$tmpdir"
    #file="$tmpdir/$base.Stereo.wav" # this is the new target for encode function now
    #fi
    
    # IS r128 = true, then encode with that in mind ...
    if [ "$EBUR128" == "true" ]; then # this is set in config
        r128=$(r128corectionPlus6 "$file")
        echo "$r128"
    else    
        r128="0"
    fi
    
    # action
    encode # function
    mv "$tmpdir/$base.flac" "$out/$base.flac" # will replace files with same name 

shift
done

printf 'done in %s\n' $(timer $tmr)