# Shared routines for flac2itunes.pl
# (i.e., those tested by the test suite).
# Copyright 2004 Mark T. Abbott

use strict;

sub parse_metadata
# Get the artist name, album name, and track names from the metadata .txt file.
{
	my ($f_txt) = @_;
	open TXT, $f_txt	or	die;
	my ($artist, @album, @n_tracks, @tracks, @notes);
	my $n_disc = 1;
	my $max_track = 0;
	my $album_done = undef;
	while (<TXT>)
	{
		chomp;
		s#\r##g;

		# Track lines.  Examples:
		# 05.  John Hardy's Wedding                  [06:21]
		# 04. Rasta Cyborg
		# 01. ???
		# d1t01 - Bonnie & Clyde [03:56.30]
		# 04:     Moanin' Lisa                            -       06:18:56        
		# 6.  North Country Girl,
		# 5. ?
		# Sample false positives:
		# 8-13-2003
		# 11/20/01

		my $re_num	= '^(?:d1t)?\s*0?(\d+)';
		my $re_num_end	= '[^\d/][-\s]*';
		my $re_name	= '(\S.*?)[\s,*]*';
		my $re_time	= '(?:[-\s]+([\[\]\d:.]*)\s*)?$';
		if ( $album_done and m#$re_num$re_num_end$re_name$re_time#i )
		{
			my ($num, $name, $time) = ($1, $2, $3);
			#warn "found track $num, $name, $time\n";
			push @tracks, [$num, $name];
			if ( $num < $max_track )
			{
				++$n_disc;
			}
			$max_track = $num;
			++$n_tracks[$n_disc];
			next;
		}

		# Artist line.
		unless ($artist)
		{
			$artist = $_;
			next;
		}

		# From here on, ignore long lines.
		#next	if	length($_) > 40;

		# Album lines.
		if ( m#\S# and not $album_done )
		{
			s#\s+$##;	# Trim trailing space.
			push @album, $_;
			next;
		}
		else
		{
			$album_done = 1;
		}
		push @notes, $_	if	m#\S#;
	}
	close TXT;

	my $album = join '; ', @album;
	my $notes = join "\n", @notes;
	return (
		$artist, 
		$album, 
	#	$notes, 
		\@n_tracks, 
		@tracks
	);
}

1;

