#!/bin/perl -w 
package ReadTag;

# Code blatantly stolen from Slim/Music/Info.pm
my %tagFunctions = (
		    'mp3' => \&Slim::Formats::MP3::getTag
		    ,'mp2' => \&Slim::Formats::MP3::getTag
		    ,'ogg' => \&Slim::Formats::Ogg::getTag
		    ,'flc' => \&Slim::Formats::FLAC::getTag
		    ,'flac' => \&Slim::Formats::FLAC::getTag
		    ,'wav' => \&Slim::Formats::Wav::getTag
		    ,'aif' => \&Slim::Formats::AIFF::getTag
		    ,'wma' => \&Slim::Formats::WMA::getTag
		    ,'mov' => \&Slim::Formats::Movie::getTag
		    ,'m4a' => \&Slim::Formats::Movie::getTag
		    ,'shn' => \&Slim::Formats::Shorten::getTag
		    ,'mpc' => \&Slim::Formats::Musepack::getTag
		   );


sub getMatchingExts {
	my @files = @_;
	my @files2;
	for my $file(@files) {
  	for my $ext(keys %tagFunctions) {
   		push(@files2,$file) if ($file =~ /\.$ext$/);
    }
  }
	return @files2;
}

sub getTrackNum {
	my $num = shift;
	my @files = @_;
	for my $file(@files) {
		my $tag = getTag($file) || warn "No tag to get from: $file\n";
		if ($tag->{"TRACKNUM"} && $tag->{"TRACKNUM"} =~ /^0?$num$/) 
			{ return $file; } 
	}
}

sub isVarious {
	my @files = @_;
	my $file1 = getTrackNum(1,@files);
	my $file2 = getTrackNum(2,@files);
	if (!$file1 && !$file2) {
		return 0;
	}
	my $tag1 = getTag($file1);
	my $tag2 = getTag($file2);
	if (!$tag1 || !$tag2) {
		return 0;
	}
	if ($tag1->{"ARTIST"} ne $tag2->{"ARTIST"}) {
		return 1;
	}
	if ($tag1->{"GENRE"} && $tag1->{"GENRE"} =~ /Soundtrack/i) {
		return 1;
	}
	return 0;
}

sub getTag {
  my $file = shift;
  my $attrs;
  my ($ext) = $file =~ (/.*\.(.*?)$/);
  warn "$file $ext\n";
  if (!$ext || !$tagFunctions{$ext}) {
    warn "$file has an unknown extension type\n";
    return;
  }
  return &{$tagFunctions{$ext}}($file);
}
