#!/bin/bash
# Sox Varispeed, change the tempo and pitch of a WAV file. 
# Concept and Testing by Glen MacArthur, coded by Google Gemini 3.

LOG="$HOME/.avl-mxe-file-action.log"
echo "--- Sox YAD Speed Started: $(date) ---" > "$LOG"

if [ $# -eq 0 ]; then
    echo "No files received." >> "$LOG"
    exit 1
fi

# 1. YAD Dialog using :NUM for speed factor
# Range: 0.1 (very slow) to 10.0 (very fast). Default: 1.0 (normal)
DATA=$(yad --title="Sox Varispeed" \
    --image="/usr/local/share/icons/custom/sox-app.png" \
    --window-icon="/usr/local/share/icons/custom/sox.png" \
    --form \
    --text="<b>Varispeed Guide:</b>\n\
• <b>0.5:</b> Half-Speed (one octave down)\n\
• <b>1.0:</b> Normal Speed\n\
• <b>2.0:</b> Double-Speed (one octave up)" \
    --field="Speed Factor:NUM" "1.0!0.1..10.0!0.1!2" \
    --button="OK:0" --button="Cancel:1" --width=400)

[ $? -ne 0 ] && exit 1

# Extract value (keeping decimals for speed)
FACTOR=$(echo "$DATA" | cut -d'|' -f1)
SUFFIX="speed_${FACTOR}"

# 2. Processing Loop
for item in "$@"; do
    [[ "$item" == "bash" ]] && continue

    process_file() {
        local input="$1"
        local output="${input%.*}-${SUFFIX}.wav"
        
        # 'speed' effect changes both pitch and duration (resampling style)
        sox -V3 "$input" "$output" speed "$FACTOR" >> "$LOG" 2>&1
    }

    if [ -d "$item" ]; then
        for f in "$item"/*.wav; do
            [ -f "$f" ] && process_file "$f"
        done
    elif [ -f "$item" ]; then
        process_file "$item"
    fi
done

notify-send "Sox Varispeed" "Completed: ${FACTOR}x speed applied! ✅"