#!/usr/bin/perl -w

use File::Basename;

  require "compel.def";
  require "compel.pl";
  use IO::Socket;
  use integer;

  our $pid;
  our $lepid;
  our $audiodesc;
  our $title;
  our $artist;
  our $db_artist;
  our $db_title;
  our $artisttitle;

  my $max = 11;  # Allow current artist/title + last 10
  my %pidhash;
  my %xmlhash;
  # namehash (PID) => audiodesc, LE PID, LCD STRING, DEFAULT_ARTIST, DEFAULT_TITLE
  my %namehash = (
    2049 => [ "047", "7543", "Shine",  ],
    2050 => [ "017", "7513", "Country Gold",  ],
    2051 => [ "018", "7514", "Nashville USA",  ],
    2052 => [ "036", "7532", "Classic Hits",  ],
    2053 => [ "002", "7498", "Songbook",  ],
    2054 => [ "007", "7503", "Unforgettable",  ],
    2055 => [ "006", "7502", "Cashmere",  ],
    2056 => [ "005", "7501", "Adult Alt.",  ],
    2057 => [ "033", "7529", "Strobe",  ],
    2064 => [ "015", "7511", "Rock Show",  ],
    2065 => [ "042", "7538", "Feedback",  ],
    2066 => [ "051", "7547", "The Cafe",  ],
    2067 => [ "049", "7545", "Latin Jazz"  ],
    2068 => [ "058", "7554", "Concrete Beats",  ],
    7534 => [ "038", "7534", "Chilltopia",  ],
    2070 => [ "029", "7525", "Ambrosia",  ],
    7523 => [ "027", "7523", "Frequency",  ],
    2072 => [ "035", "7531", "Jazz Traditions",  ],
    2073 => [ "023", "7519", "Impressions",  ],
    7500 => [ "004", "7500", "60's Pop Hits",  ],
    2081 => [ "022", "7518", "Plaza",  ],
    2082 => [ "012", "7508", "Decades",  ],
    2083 => [ "040", "7536", "Intermezzo",  ],
    2084 => [ "025", "7521", "Easy Instrumentals",  ],
    2085 => [ "010", "7506", "Swing Kings"  ],
    2086 => [ "021", "7517", "The Light",  ],
    2087 => [ "037", "7533", "Kidtunes",  ],
    2088 => [ "046", "7542", "Aura",  ],
    2089 => [ "011", "7507", "Lucille",  ],
    7550 => [ "054", "7550", "Kingston",  ],
    2098 => [ "031", "7527", "Hitline",  ],
    2099 => [ "032", "7528", "Hot FM",  ],
    2100 => [ "028", "7524", "Expressions",  ],
    2101 => [ "041", "7537", "Love Songs",  ],
    2102 => [ "008", "7504", "City Lights",  ],
    2103 => [ "045", "7541", "Moodscapes",  ],
    2104 => [ "048", "7544", "The Party Playlist",  ],
    2105 => [ "050", "7546", "Piano \& Guitar",  ],
    2112 => [ "013", "7509", "Ensemble",  ],
    2113 => [ "000", "7496", "50\'s \& 60\'s Hits",  ],
    2114 => [ "001", "7497", "70\'s Hits",  ],
    2115 => [ "003", "7499", "80\'s Hits",  ],
    2116 => [ "009", "7505", "The Beach",  ],
    2117 => [ "019", "7515", "Cntry Music 1",  ],
    2118 => [ "057", "7553", "The Blvd",  ],
    2119 => [ "052", "7548", "Classic Soul",  ],
    2120 => [ "034", "7530", "Little Italy",  ],
    2121 => [ "056", "7552", "Tropical Breezes",  ],
    2128 => [ "016", "7512", "Roadhouse",  ],
    2131 => [ "039", "7535", "La Musica",  ],
    2132 => [ "059", "7555", "Viva Mariachi",  ],
    7551 => [ "055", "7551", "Modern Soul",  ],
    2134 => [ "044", "7540", "Mojito",  ],,
    2041 => [ "026", "7522", "Environmental",  ],
    7510 => [ "014", "7510", "Summer Fun",  ],  
    7516 => [ "020", "7516", "Belissimo",  ],
    7520 => [ "024", "7520", "Renegade Cntry",  ],
    2039 => [ "030", "7526", "FM-1",  ],
    2037 => [ "043", "7539", "Metro",  ],
    2040 => [ "053", "7549", "Reflections",  ],
    7557 => [ "061", "7557", "NuLounge",  ],
    7563 => [ "067", "7563", "Quebecois",  ],
    2080 => [ "068", "7564", "Rooted",  ],
    7566 => [ "070", "7566", "Modern Soul Demo",  ],
    2133 => [ "072", "7568", "Toned",  ],
    7569 => [ "073", "7569", "Perimeter",  ],
    7570 => [ "074", "7570", "The New Wave",  ],
    7571 => [ "075", "7571", "Varsity",  ],
    7572 => [ "076", "7572", "Stylus",  ],
    7573 => [ "077", "7573", "TBD-4",  ],
    7583 => [ "087", "7583", "Sheetz",  ],
    7584 => [ "088", "7584", "Uptown",  ],
    7579 => [ "083", "7579", "FM Dos",  ],
    7558 => [ "062", "7558", "Promo-3",  ],
    7559 => [ "063", "7559", "Mood Overhead",  ],
    7560 => [ "064", "7560", "Chilltopia",  ],
    7562 => [ "066", "7562", "Red Lobster",  ],
    7565 => [ "069", "7565", "Popeyes Radio",  ],
    7574 => [ "078", "7574", "TBD-2",  ],
    7575 => [ "079", "7575", "Food Lion",  ],
    7576 => [ "080", "7576", "Mens Wearhouse",  ],
    7577 => [ "081", "7577", "Boot Classic",  ],
    7578 => [ "082", "7578", "Rapture",  ],
    7580 => [ "084", "7580", "90s Hits",  ],
    7581 => [ "085", "7581", "Boot Modern",  ],
    7582 => [ "086", "7582", "Cost Plus",  ],
    7585 => [ "089", "7585", "Rock En Espanol", ],
    7586 => [ "090", "7586", "Moe\'s SW Grill",  ],
    7587 => [ "091", "7587", "McDonalds",  ],
    7589 => [ "093", "7589", "TBD-5",  ],
    7590 => [ "094", "7590", "Latin Hits",  ],
    7591 => [ "095", "7591", "Bed Bath Beynd",  ],
    7593 => [ "097", "7593", "Subterranean",  ],
    7594 => [ "098", "7594", "Ulta",  ],
    7760 => [ "099", "7760", "44.1k Test",  ],
    7600 => [ "200", "7600", "Chipotle_East",  ],
    7601 => [ "201", "7601", "Chipotle_Cent",  ],
    7602 => [ "202", "7602", "Chipotle_West",  ],
    7603 => [ "203", "7603", "Chipotle_Mtn",  ],
    7590 => [ "205", "7604", "Latin Hits",  ],
    2097 => [ "206", "7606", "Hawaiian",  ],
    
        
  );

  my $text;
  my $incoming;
  my $sock = new IO::Socket::INET (
                                   LocalPort => '2117',
                                   Proto => 'udp',
                                  )
    or die "Could not create socket: $!\n" unless $sock;

#  my @audiolist = &read_s_audio_info("");
#  print @audiolist;
#  my @audio_array = split ( /\:/, $audiolist[0]);
#	foreach $audio (@audio_array) {
#		print $audio."\n";
#	}
#  exit;

# capture the current time
$start_hour = `date +%H`;
$start_minute = `date +%M`;
$start_second = `date +%S`;
$start_time = ( ($start_hour * 3600) + ($start_minute * 60) + ($start_second) );

# set a flag that tells us if this is the very first outer loop iteration
$first_run = 1;

$packlen = 0;
while($sock->recv($recvdata, 3760) )
{
  $count = 0;

  # capture the current time
  $cur_hour = `date +%H`;
  $cur_minute = `date +%M`;
  $cur_second = `date +%S`;
  $cur_time = ( ($cur_hour * 3600) + ($cur_minute * 60) + ($cur_second) );

  # if the day just changed, reset $start_time
  if ($start_time > $cur_time) {
    $start_time = $cur_time;
  }

  # once at first, then every 110 seconds, check for default artist and title
  if (($first_run) || ($cur_time - $start_time > 110)) {
    # loop through each namehash key, sending default artist and title if there
    foreach $key ( keys %namehash) {
      if ( (@{$namehash{$key}}[3]) && (@{$namehash{$key}}[4])) {
        send_songinfo(@{$namehash{$key}}[0], @{$namehash{$key}}[3], @{$namehash{$key}}[4]);
        print @{$namehash{$key}}[4];
      }
    }

    # reset the time counter, to start the next 110 second interval
    $start_time = $cur_time;
  }

  # set $first_run to false, so we time the future checks for default artist and title
  $first_run = 0; 

  $packlen = length($recvdata);
  while($packlen > ($count * 188)) {
    $data = substr( $recvdata, ($count * 188), 188);
    chomp($data);
	@array=unpack("CCCCCCCCCCCCCA175", $data );
	$data2 = $array[13];

	# Artist / Title
	$len = (($array[6] & 0x4f) * 256) + $array[7] - 10;
	$format = "A".$len."I";
	@data3 = unpack($format, $data2);
	$artisttitle = $data3[0];
	#$crc32 = $data3[1];

    # Parse artist / title
    ($a, $b, $c, $d) = split(/\n/, $artisttitle, 4);
    ($e, $title) = split(/:/, $a);
    ($f, $artist) = split(/:/, $b);
    ($g, $cd) = split(/:/, $c);
    ($h, $label) = split(/:/, $d);
    chomp($artist); chomp($title); chomp($cd); chomp($label);

    $title =~ s/^[ 	]*//;
    $artist =~ s/^[ 	]*//;
    $cd =~ s/^[ 	]*//;
    $label =~ s/^[ 	]*//;

	# PID
	$pid = (($array[1] & 0xbf) * 256) + $array[2];
	$lepid = @{$namehash{$pid}}[0];

	if (defined($namehash{$pid}[0])) {
	    $incoming = "$title, by $artist";
        if (!exists($pidhash{$pid}) || ($incoming ne $pidhash{$pid}[0])) {
	        unshift @{$pidhash{$pid}}, $incoming;
		    pop @{$pidhash{$pid}} if (@{$pidhash{$pid}} > $max);
		    $audiodesc = @{$namehash{$pid}}[0];
		    print_html();
		    if ($lepid) {
				# Make artist/title copies to alter for dbsosr
				$db_artist = $artist;
				$db_title = $title;
				
			    # Put backslash in front of commas to work with dbsosr
    		    $db_artist =~ s/,/\\,/g;
    		    $db_title =~ s/,/\\,/g;

			    # Put backslash in front of double quote to work with dbsosr
    		    $db_artist =~ s/"/\\"/g;
    		    $db_title =~ s/"/\\"/g;

			    # Put backslash in front of double quote to work with dbsosr
    		    $db_artist =~ s/`/\\`/g;
    		    $db_title =~ s/`/\\`/g;

		        print_log();
			    send_songinfo($lepid,"by ".$db_artist,$db_title);
		    }
	    }
		# Get rid of & before we create XML
		$artist =~ s/\&/\&amp;/g;
		$title =~ s/\&/\&amp;/g;
		$cd =~ s/\&/\&amp;/g;
		$label =~ s/\&/\&amp;/g;

		$xmllist = "<artist>$artist</artist>
		<title>$title</title>
		<cd>$cd</cd>
		<label>$label</label>";
        if (!exists($xmlhash{$pid}) || ($xmllist ne $xmlhash{$pid}[0])) {
	        unshift @{$xmlhash{$pid}}, $xmllist;
		    pop @{$xmlhash{$pid}} if (@{$xmlhash{$pid}} > $max);
		    print_xml();
	    }
	}
    $count = $count + 1;
  }
}

sub print_log
{
	my $progname=basename($0, ".pl");
	my $fname="logs/$progname.log-".`date +'%y%m%d'`;
	if (length(@{$namehash{$pid}}[2]) < 8) {
		$tabs="\t\t\t";
	} else {
		if (length(@{$namehash{$pid}}[2]) < 16) {
			$tabs="\t\t";
		} else {
			$tabs="\t";
		}
	}
	open (FH, ">>$fname");
	print FH "[".$pid."]\t".@{$namehash{$pid}}[0]."\t".@{$namehash{$pid}}[2].$tabs."\t".$db_artist." ".$db_title."\t".`date`;
	close (FH);
}

sub print_missing
{
	my $progname=basename($0, ".pl");
	my $fname="logs/$progname.log-".`date +'%y%m%d'`;
	open (FH, ">>$fname");
	print FH "[".$pid."]\t"."- No Table Entry - \t\t".`date`;
	close (FH);
}

sub print_html
{
		open (FH, "> /var/www/html/wpn/$audiodesc.html");
print FH qq|
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<meta http-equiv="Refresh" content="30" />
<title>|; print FH @{$namehash{$pid}}[2]; print FH qq| - What's Playing Now</title>
<link rel="stylesheet" href="wpnpop.css" type="text/css" media="all" />
</head>
 
<body>
<table width="300" border="0" align="center" cellpadding="5" cellspacing="4" bgcolor="#FFFFFF">
<tr>
<td bgcolor="#666666"><div align="center"><img src="whatsplayingnow220.gif" width="220" height="40" /></div></td>
</tr>
<tr>
<td><div id="titles"><p><b>Now on |; print FH @{$namehash{$pid}}[2]; print FH qq|</b><br />|;
print FH @{$pidhash{$pid}}[0];print FH qq|</p>|;
print FH qq|<b>The last ten songs on |; print FH @{$namehash{$pid}}[2];

print FH qq|<br>
</b>|;
	$first = 1;
	foreach $title (@{$pidhash{$pid}}) {
		    if ($first) { $first = 0; next; }
			print FH $title."\n";
print FH qq|<br /><img src="shimi.gif" width="220" height="4" /><br />|;
}
print FH qq|
</div></td></tr>
<tr><td border="0">
<div id="update">Updated: |; print FH `date`; print FH qq|
</div></td></tr>
<tr>
<td bgcolor="#666666" border="0"><div align="center"><a href="javascript:self.close()"><img src="close100.gif" width="100" height="19" border="0" /></a></div></td>
</tr>
</table>
</body>
</html>
	|;
			close (FH);
}

sub print_xml
{
	my $name=@{$namehash{$pid}}[2];

	$name =~ s/\&/\&amp;/g;

	open (FH, "> /var/www/html/wpn/xml/$audiodesc.xml");
	my $datetime = `date +'<last_updated>%Y-%m-%dT%H-%M-%S</last_updated>'`;

print FH qq|
<program>
	<name>$name</name>
	<audio_desc>$audiodesc</audio_desc>
	<echostar_pid>@{$namehash{$pid}}[1]</echostar_pid>
	<le_pid>@{$namehash{$pid}}[0]</le_pid>
	$datetime|;
	
	$first = 1;
	foreach $title (@{$xmlhash{$pid}}) {
		#$title =~ s/\&/\&amp;/g;
		if ($first) {
			print FH qq|	<curr_song>
		|;
		} else {
			print FH qq|
	<prev_song>
		|;
		}
		print FH qq|$title|;
		if ($first) {
			$first = 0;
			print FH qq|
	</curr_song>|;
		} else {
			print FH qq|
	</prev_song>|;
		}
	}
	print FH qq|
</program>
	|;

	close (FH);
}

sub error_logging {
    my ( $msg ) = @_;

	my $progname=basename($0, ".pl");
	my $fname="logs/$progname.err-".`date +'%y%m%d'`;
	open (FH, ">>$fname");
	print FH `date`.$msg."\n";
	close (FH);
}
