#!/usr/bin/perl

# For adding the date 
use Time::Local;

$File = "iTunes Music Library.xml";

$SongNumber = 0;

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);

open (FILE, "$File");

print "<html>\n";
print "<head>\n";
print "<style type=text/css>th {background-color:yellow}</style>\n";
print "</head>\n";
print "<body>\n";
print "<h3>COMPLETE SONG LIST<\h3>\n";
printf "Compiled %02d-%4d <p>\n", $mon+1, $year+1900;
print "<table border=4>\n";
print "<tr>\n";
print "<th>SONG:</th>\n";
print "<th>ARTIST:</th>\n";
print "<th>ALBUM:</th>\n";
print "</tr>\n";


while (<FILE>) {
	chomp;
				
	#Note that Name, Artist, Albuma nd Genre must be in the exact order as they are in the iTunes XML file
	
		if (/>Name</){
			$prep = s/\r/\n/g;
			$prep = s/\r$//g;
			$prep = s/\t//g;
			$prep = s/<key>Name<\/key><string>//;
			$prep = s/<\/string>//;
			$Name = "$_";
			chomp $Name;
					}					
						

		elsif (/>Artist</){
			$prep = s/\r/\n/g;
			$prep = s/\r$//g;
			$prep = s/\t//g;
			$prep = s/<key>Artist<\/key><string>//;
			$prep = s/<\/string>//;
			$Artist = "$_";
			chomp $Artist;
					}

					
		elsif (/>Album</){
			$prep = s/\r/\n/g;
			$prep = s/\r$//g;
			$prep = s/\t//g;
			$prep = s/<key>Album<\/key><string>//;
			$prep = s/<\/string>//;
			$Album = "$_";
			chomp $Album;
			$SongNumber++;


			}					


		elsif (/>Genre</){
			$prep = s/\r/\n/g;
			$prep = s/\r$//g;
			$prep = s/\t//g;
			$prep = s/<key>Genre<\/key><string>//;
			$prep = s/<\/string>//;
			$Genre = "$_";
			chomp $Genre;		

	#Once Genre has been captured, we filter out the audiobooks, podcasts and radio stations	
			if (($Genre eq 'Audiobook') || ($Genre eq 'Podcast') || ($Genre eq 'Radio')){
				$SongNumber--;
						}

	#Here we print out the song info, as part of the genre loop	
			else 		{
				print "<td>";
				print "$Name";
				print "</td><td>";			
				print "$Artist";
				print "</td><td>";			
				print "$Album";
				print "</td></tr>\n";			
					}

				}

										
	}


print "</tr>\n";

print "<b>Total number of songs: $SongNumber <\/b>\n";

print "</body>\n";
print "</html>\n";


close FILE;
