#!/usr/bin/perl
use CGI::Carp qw(fatalsToBrowser);

sub songInfo {
	##
	#
	# This function uses the text file and outputs the current song
	#
	# filename: Path to the text file
	# separator: Character used to separate artist and title (ie: '-' would output Artist - Title)
	# default: What to output when no song playing or error (ie: Nothing)
	# history: Number of songs to display as previously heard (this number should be either 0, 3, 5 or 10 depending on your plugin setting)
	# next: Show next track? 0 = No, 1 = Yes
	# track: Show track number out of total? 0 = No, 1 = Yes
	#
	##
	my($filename, $separator, $default, $history, $next, $track) = @_;
	open(INF,$filename);
	@read = <INF>;
	close(INF);
	foreach $i (@read) {
		$filedata .= $i;
	}
	$additional = $filedata;

	@explode = split(/SONG:/,$filedata);
	@explode = split(/:SONG/,$explode[1]);
	$song_info = $explode[0];

	if (($song_info eq "Nothing") || ($song_info eq "") || ($additional eq "SONG:Nothing:SONG")) {
		$song_info = $default;
	} else {
		@explode = split(/ - /,$song_info);
		$song_info = "$explode[0] $separator $explode[1]";

		if ($history ne 0) {
			if (($history eq 3) || ($history eq 5) || ($history eq 10)) {
				# History (if enabled)
				# Customize this output if you wish
				$prevstat = "<br /><br>" . "<i><b>F&ouml;reg&aring;ende l&aring;tar:</b></i><br />";
				for ($i=1;$i<=$history;$i++) {
					$temp1 = "P" . $i . ":";
					$temp2 = ":P" . $i;
					@explode = split(/$temp1/,$additional);
					@explode = split(/$temp2/,$explode[1]);
					$prevtrack = $explode[0];
					if ($i eq "1") {
						if ($prevtrack eq "") {
							$prevstat .= "&ndash;";
							last;
						} else {
							$prevstat .= "* " . $prevtrack . "<br />";
						}
					} else {
						if ($prevtrack ne "") {
							$prevstat .= "* " . $prevtrack . "<br />";
						}
					}
				}
			}
		}
		
		if ($next eq "1") {
			# Next Track (if shuffly isn't on only)
			@explode = split(/NS:/,$additional);
			@explode = split(/:NS/,$explode[1]);
			$nexttrack = $explode[0];
			# Customize this output if you wish
			if ($nexttrack eq "") { $nextstat = "&nbsp;"; }
			else { $nextstat = "<br /><br>" . "<i><b>N&auml;sta låt:</b></i><br>" . $nexttrack; }
		}

		if ($track eq "1") {
			# Track Number (out of) Total Playlist Count
			@explode = split(/S:/,$additional);
			@explode = split(/:S/,$explode[1]);
			$trackno = $explode[0];
			@explode = split(/T:/,$additional);
			@explode = split(/:T/,$explode[1]);
			$totalno = $explode[0];
			# Customize this output if you wish
			$trackstat = "<br />" . "Sp&aring;r " . $trackno . " av " . $totalno;
		}

	}
	# Put everything into one string and return
	return "<i><b>Spelas just nu:</b></i><br>" . $song_info . $trackstat . $nextstat . $prevstat;
}

print "Content-type:text/html\n\n";
print songInfo('/home/m8100/public_db/song.txt','-','<i>ingenting.</i>','3','1','0'); #Filename, Separator, Default, History, Next, Track
