#!/bin/sh
## Changes id3 tags based on filename
## Uses `id3` or `id3v2`, depending on $deftag,
## Or run `./name2id3 1` to force v1, or `./name2id3 2` for v2.
deftag=id3v2

for file in *.mp3
do
	dir=`pwd`
	filename=${file%.mp3}
	adlen=`expr match "$dir" '.*/'`
	artdir=${dir:0:(($adlen-1))}
	artist=${artdir##/*/}
	album=${dir##/*/}
	tracklen=`expr index "$filename" ' '`
	track=${filename:0:(($tracklen-1))}
	title=${filename#* - }
	nottrack=${filename:$tracklen}
	titlest=`expr index "$nottrack" '[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890]'`
	title=${nottrack:(($titlest-1))}
## Debug output
#	echo "    file = $file"
#	echo "     dir = $dir"
#	echo "filename = $filename"
#	echo "   adlen = $adlen"
#	echo "  artdir = $artdir"
#	echo "  artist = $artist"
#	echo "   album = $album"
#	echo "tracklen = $tracklen"
#	echo "   track = $track"
#	echo "nottrack = $nottrack"
#	echo " titlest = $titlest"
#	echo "   title = $title"
#	echo "=========="
## Real output
	if [[ $1 == "1" ]] ;
		then tagger=id3 ;
	elif [[ $1 == "2" ]] ;
		then tagger=id3v2;
		else tagger=$deftag ;
	fi ;
	echo $tagger -a "$artist" -A "$album" -T "$track" -t "$title" "$file"
done
