#!/usr/bin/perl

#
# mp3tolibros.pl - Imports an mp3 directory into a book database
#
# Copyright (C) 2000	  Angel Ortega <angel@triptico.com>
#
# 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., 675 Mass Ave, Cambridge, MA 02139, USA.
#

print "Directory where the mp3 are [/cdrom]: ";
$dir=<>;
chop($dir);
$dir="/cdrom" unless $dir;

print "Database file name [mp3.dat]: ";
$database_file=<>;
chop($database_file);
$database_file="mp3.dat" unless $database_file;

print "Content for location field (e.g.: MP3 CD 25): ";
$location=<>;
chop($location);

print "Content for genre field (empty if mixed): ";
$genre=<>;
chop($genre);

$next_code=0;

load_database();

open(DIR,"ls $dir|") or die "Can't 'ls' $dir";

while(<DIR>)
{
	my ($rec);
	my ($author,$song);

	chop($_);
	($author,$song)=split(/\s-\s/,$_,2);

	next unless $song =~ /\.mp3$/;

	$song =~ s/\.mp3$//;

	$rec->{'code'}=$next_code++;
	$rec->{'author'}=$author;
	$rec->{'title'}=$song;
	$rec->{'genre'}=$genre;
	$rec->{'where'}=$location;
	$rec->{'notes'}="";

	push(@list_all, $rec);
}

close DIR or die "Can't 'ls' $dir";

$database_title="MP3 Personal Collection" unless $database_title;

save_database();

exit(0);



####################################################

sub load_database
{
	my (@line,$rec);

	@list_all=();

	if(open(DAT,$database_file))
	{
		$_=<DAT>;
		chop;
		s/\r//g;

		($next_code,$database_title)=split(/\|/,$_);

		while(<DAT>)
		{
			chop();
			s/\r//g;

			@line=split(/\|/,$_);

			$rec={};
			$rec->{"code"}=$line[0];
			$rec->{"author"}=$line[1];
			$rec->{"title"}=$line[2];
			$rec->{"genre"}=$line[3];
			$rec->{"where"}=$line[4];
			$rec->{"notes"}=$line[5];

			push(@list_all,$rec);
		}

		close DAT;
	}
}


sub save_database
{
	my ($line,$rec);

	if(open(DAT, ">".$database_file))
	{
		print DAT "$next_code|$database_title|\n";

		foreach $rec (@list_all)
		{
			$line=join("|",(sprintf("%05d",$rec->{'code'}),
					$rec->{'author'},$rec->{'title'},
					$rec->{'genre'},$rec->{'where'},
					$rec->{'notes'}));

			print DAT $line . "\n";
		}

		close DAT;
	}
}


