#!/opt/local/bin/perl
#
# Converts FLAC to MP3 preserving tags
# License: GPLv2
# Home: http://www.GuruLabs.com/downloads.html
#
# Note: Only use on flac files that you trust. A
# malicious FLAC/ID3v1 tag could hose you.
#

use Audio::FLAC::Header;

foreach $file (@ARGV) {
  if (!($file =~ /\.flac$/)) {
    print "Skipping $file\n";
    next;
  }
  undef $year; undef $artist; undef $comment; undef $album; undef $title; undef $genre; undef $tracknum;
  if ($flac = Audio::FLAC::Header->new($file)) {
  	$tag = $flac->tags();
    $year = $tag->{DATE};
    $artist = $tag->{ARTIST};
    $comment = $tag->{COMMENT};
    $album = $tag->{ALBUM};
    $title = $tag->{TITLE};
    $genre = $tag->{GENRE};
    $tracknum = $tag->{TRACKNUMBER};
    chomp($year, $artist, $comment, $album, $title, $genre, $tracknum);
    $tracknum = sprintf("%2.2d", $tracknum);
  } else {
    print "Couldn't get flac tags for $file.\n";
  } 
  if (($artist) && ($title) && ($tracknum)) {
     $outfile = "$tracknum" . "_-_" . "$title.mp3";
	 `flac -c -d "$file" | lame --alt-preset standard --ty $year --ta "$artist" --tc "$comment" --tl "$album" --tt "$title" --tg "$genre" --tn $tracknum - "$outfile"`;
  } else {
    $outfile = $file;
    $outfile =~ s/\.flac$/.mp3/;
	`flac -c -d "$file" | lame --alt-preset standard - "$outfile"`;
  }
}
