#!/usr/bin/perl -w

use Getopt::Std;
use Data::Dumper;

my $id3 = "id3ed -i";

getopts("vhn");

if(defined $opt_h  && $opt_h){

die<<USAGE;
usage: playlist.pl > playlist.m3u

looks at the track number information in the ID3 tags of all
the mp3s in the current directory and sorts the songs by track
number. 

USAGE
}

my $verbose = $opt_v if defined $opt_v;

opendir DIR, "$ENV{'PWD'}" or die "cannot open directory: $!";

my %finfo = ();
while (my $file = readdir DIR ){

  if($file =~ /mp3$/i){
    print STDERR "reading info on $file\n" if $verbose;
    my $info = `$id3 "$file"`;
    foreach (split /\n/, $info){
      if(my ($key, $value) = /(\w+):\s+(.+)/){
        print "$file: $key->$value\n" if $verbose;
        $finfo{$file}{$key} = $value;
      }
    }
  }
}

#print Dumper(%finfo);

# sort the playlist by track number
my @playlist = sort {$finfo{$a}{'tracknum'} <=> $finfo{$b}{'tracknum'}} keys %finfo; 

foreach (@playlist){

  print "$finfo{$_}{'tracknum'}: " if (defined $opt_n && $opt_n);
  print "$_\n";

}
