#! /bin/sh

# Split an mp3 file into 5-minute segmenst, preserving id3 in a reasonable way.

if [ $# -eq 0 ]; then
  echo "Usage: splitmp3 file.mp3"
fi

fnam=$1
base=$(basename $fnam | sed -e 's/\.[^\.]*$//')
newdir=$(basename $fnam .mp3)

echo fnam $fnam
echo base $base

title=$(id3tool $fnam | grep Title | sed 's/Song Title:[ \t]*//')
artist=$(id3tool $fnam | grep Artist | sed 's/Artist:[ \t]*//')
album=$(id3tool $fnam | grep Album | sed 's/Album:[ \t]*//')
note=$(id3tool $fnam | grep Note | sed 's/Note:[ \t]*//')
#genre=$(id3tool $fnam| grep Genre | sed 's/Genre:[ \t]*//' | sed 's/[ \t]\(.*$\)//' )
genre="Speech"

# Make sure none of these are blank:
if [ x"$title" = x ]; then
    title=$base
fi
#if [ x"$album" = x ]; then
#    album=$title
#fi
if [ x"$artist" = x ]; then
    artist=$title
fi
if [ x"$genre" = x ]; then
    genre="Other"
fi
if [ x"$note" = x ]; then
    note=""
fi

# Make the title (which will become the "album" name) start with 0
# so it shows up at the beginning of the list.
title="0 $title"
echo title is now $title

mp3splt -f -t 5.0 -o @n_$base $fnam

if [ ! -e $newdir ]; then
    mkdir $newdir
fi

for f in *_$base.mp3; do
    fnum=$(echo $f | cut -c 1-3)
    id3tool -t "$fnum $title" -a "$title" -r "$artist" -G "$genre" -n "$note" $f
    if [ -d $newdir ]; then
        mv $f $newdir
    fi
done

