#!/usr/bin/perl
#
# m3u generator for a given directory of OGGs
#
# designed for use on a given album. Sorts output by track number.
#
######################### 
# $Id: m3u_gen.pl 130 2005-02-09 00:23:37Z steve $
#########################
# $Log$
# Revision 1.1  2005/02/09 00:23:37  steve
# initial revision
#
#########################

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

my ($version) = '$Revision: 130 $' =~ /Revision:\s*(.+?)\s*\$/;

our ( $opt_h, $opt_V );
getopts("hV");

usage() if $opt_h;
usage() unless @ARGV;

die "$0 version: $version\n" if $opt_V;

#### end init

my $vorbiscomment = "vorbiscomment";

my @ogg_files = @ARGV;

my @sorted_playlist;

foreach my $ogg ( @ogg_files ){
    
    my $meta = read_vorbis($ogg, $vorbiscomment);
    my $tracknum = $meta->{'tracknumber'};

    unless( $tracknum ){
	warn "no track number for $ogg. skipping\n";
	next;
    }

    $sorted_playlist[$tracknum] = $ogg;

}

for my $i (1 .. $#sorted_playlist ){
    print ( $sorted_playlist[$i] ? 
	    $sorted_playlist[$i] : 
	    "# track $i goes here" );
    print "\n";
}

#### helper subs

sub read_vorbis{
    my( $file, $vorbiscomment ) = @_;

    my %read_vorbis;

    open PIPE, "-|", "$vorbiscomment", "-l", "$file"
	or die "cannot open pipe from $vorbiscomment: $!\n";

    while( my $line = <PIPE> ){
	my( $key, $value ) = $line =~ /^([^=]+)=(.+)$/;

	unless( $key ){
	    warn "unknown output from $vorbiscomment line $.\n";
	    next;
	}

	$read_vorbis{$key} = $value;
    }

    return \%read_vorbis;
}


sub usage(){
    die <<USAGE;
usage: $0 [options] file.ogg [file.ogg [...]]
 
Reads a bunch of OGGs (generally, a directory full) and spits out
a playlist of them, sorted by track number.

Designed to generate an m3u from an album-full of OGGs.

options:
    -h          this help
    -V          print version information

Copyright(C) 2005 Steve Pomeroy <steve\@staticfree.info>
Licensed under the GNU GPL. See documentation for complete details.
USAGE

}

__END__

=head1 NAME

m3u_gen

=head1 ENVIRONMENT

No environment variables are used.

=head1 AUTHOR

Steve Pomeroy <steve@staticfree.info>
http://staticfree.info/

=head1 LICENSE

Copyright © 2005 Steve Pomeroy <steve@staticfree.info>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA

=head1 SEE ALSO

perl(1)

=head1 BUGS


=cut
