#!/usr/bin/perl

# license = gpl
# author = jacob jarick, mem.namefix@gmail.com , mem on #wiidev @ efnet

#--------------------------------------------------------------------------------------------------------------
# includes
#--------------------------------------------------------------------------------------------------------------

use CGI qw /:standard -nosticky/;
use Cwd;
use warnings;
use File::Copy;

use LWP::UserAgent;
use HTTP::Request;
use HTTP::Response;


#--------------------------------------------------------------------------------------------------------------
# variables
#--------------------------------------------------------------------------------------------------------------

our $dir = $0;

$dir =~ s/\\/\//g;
if($dir =~ /\//)
{
	$dir =~ s/^(.*)\/(.*?)$/$1/;
}
else
{
	$dir = cwd();
}

do "$dir/subs.pm";

do "$dir/config.pl" or die "ERROR: !! couldnt load $dir/config.pl";

if(-f "$dir/config.new")
{
	our %conf_new 		= &read_config("$dir/config.new");
	if($conf_new{'theme'})
	{
		$theme 		= $conf_new{'theme'};
	}
	if($conf_new{'enc_opts'})
	{
		$enc_opts 	= $conf_new{'enc_opts'};
	}
	if($conf_new{'duration'})
	{
		$duration 	= $conf_new{'duration'};
	}
	if($conf_new{'flvtool_exe'})
	{
		$flvtool_exe 	= $conf_new{'flvtool_exe'};
	}
	if($conf_new{'use_flvtool'})
	{
		$use_flvtool	= $conf_new{'use_flvtool'};
	}
	if($conf_new{'enc_exe'})
	{
		$enc_exe 	= $conf_new{'enc_exe'};
	}
	unlink("$dir/config.new");
	&save_config;
}

our $tf_ext		= "txt|bat|ini|nfo|log";
our $pf_ext		= "jpg|gif|png|jpeg|bmp|tif|tiff";

$version = "0.3.2-RC2";

$mf_ext = "avi|mpeg|mpg|mov|flv|dat|asf|wmv|mp4|ogm|mkv|vob";

our $file 		= param('file');
our $name		= param('name');
our $action 		= param('action');
our $our_wd		= param('our_wd');
our $tpl_id		= param('id');

$ico_pic 	= "$theme_dir/ico_img.png";
$ico_mp3 	= "$theme_dir/ico_mp3.png";
$ico_vid 	= "$theme_dir/ico_vid.png";
$ico_zip 	= "$theme_dir/ico_zip.png";
$ico_dir 	= "$theme_dir/ico_dir.png";
$ico_txt 	= "$theme_dir/ico_txt.png";
$ico_home	= "$theme_dir/ico_home.png";
$ico_up		= "$theme_dir/ico_up.png";
$ico_bin	= "$theme_dir/ico_bin.png";
$ico_play	= "$theme_dir/ico_play.png";
$ico_del	= "$theme_dir/ico_del.png";
$ico_config	= "$theme_dir/ico_config.png";
$ico_links	= "$theme_dir/ico_links.png";
$ico_forward	= "$theme_dir/ico_fwd.png";
$ico_back	= "$theme_dir/ico_back.png";
$ico_flash	= "$theme_dir/ico_flash.png";
$background	= "$theme_dir/background.jpg";

our @drives_data 	= ();
our @table_data 	= ();
our @info 		= ();

# backwards compat code for themes
if(!-f "$theme_local_dir/tpl/main.tpl")
{
	our @html 		= &readf("$theme_local_dir/main.html");
}
else
{
	our @html 		= &readf("$theme_local_dir/tpl/main.tpl");
}
our $date 		= localtime(time());


#--------------------------------------------------------------------------------------------------------------
# code
#--------------------------------------------------------------------------------------------------------------

print "Content-type: text/html\n\n";

if($our_wd)
{
	chdir $our_wd;
	$our_wd =~ s/\\/\//g;
}
else
{
	$our_wd = cwd;
	$our_wd =~ s/\\/\//g;
}

if($our_wd ne "/")
{
	$our_wd =~ s/(\/|\\)$//ig;
}

#--------------------------------------------------------------------------------------------------------------
# get drives data ready.

@drives_data = &readf("$tpl_local_dir/drives_header.tpl");
@tmp = &readf("$tpl_local_dir/drives_body.tpl");

@drives = &drive_arr($drive_list);

for $d(@drives)
{
	@tmp2 = @tmp;
	for $line(@tmp2)
	{
		$line =~ s/<<drive>>/$d/ig;
		$line =~ s/<<cgi>>/$cgi_dir/ig;
		push @drives_data, $line;
	}
}
push @drives_data, &readf("$tpl_local_dir/drives_footer.tpl");

#--------------------------------------------------------------------------------------------------------------
# get link_buttons data ready.

our @link_buttons = &readf("$tpl_local_dir/link_buttons.tpl");

$vars_data = "<!-- 
	VARS \n\$file = $file
	\$action = \"$action\"
	\$our_wd = \"$our_wd\"
	\$file = \"$file\"
-->\n";

#--------------------------------------------------------------------------------------------------------------
# respond to cgi requests

if(!$action)
{
	@info = &lsdir;
}

# lil bit of backwards compatiblity

elsif($action =~ /^(shoutcast|config)$/i)
{
	$tpl_id = $action;
	$action = "tpl";
}

elsif($action eq "file" && -f $file && $file =~ /\.($tf_ext)$/i)
{
	$action = "tpl";
	$tpl_id = "txt_display";
}

# Plugin Templates

if($action =~ /^(tpl|vidiframe|vidplay|vidplugin)/)
{
	# setup vars and refs
	
	@info = ();
	
	my $theme_combo = \&html_theme_combo;
	my $file_content = \&html_file_content;
	my $enc_opts_combo = \&html_enc_combo;
	my $lsdir_content = \&lsdir;
	
	print "<!-- \$use_flvtool = $use_flvtool -->\n";
	$use_flvtool_check = "";
	if($use_flvtool eq "on")
	{
		$use_flvtool_check_on = "checked";
	}
	else
	{
		$use_flvtool_check_off = "checked";
	}
	
	if($action =~ /^(vidiframe|vidplay|vidplugin)/i)
	{
		$vid_plugin = 1;
		$count = param('count');
		if(!$count)
		{
			print "<!-- count wasnt sent on a param, so guessing from \$action = \"$action\"\n";
			$count = $action;
			$count =~ s/\r|\n//ig;
			print "\$count = \"$count\"\n";
			$count =~ s/^.*(\d+)$/$1/ige;
			print "\$count = \"$count\"\n-->";
		}
		if($count !~ /^\d+$/)
		{
			print "<!-- \$count isnt a number, setting to zero -->\n";
			$count = "0";
			print "<!-- \$count = \"$count\" -->\n";
		}
		$action =~ s/\n|\r/$1/eig;
		$action =~ s/\d+$//;
	
		print "<!-- \n\$action = \"$action\" \n\$count = \"$count\"\n-->\n";
	
		$count++;
		$file 			= "$count"."default.flv";
		$tmpdur 		= $duration + $refresh_delay;
		$filename 		= $file;
		$file 			= "$flv_dir/$file";
		$file_http 		= "$flv_dir/$filename";
		$file_local 		= "$flv_local_dir/$filename";
		$redirect_url 		= "$cgi_dir/?action=$action"."$count";
		$tpl_id 		= "$action";
	}
	else
	{
		$vid_plugin = 0;
	}
	# read tpl's
	if($action eq "tpl2")
	{
		push @info, &readf("$tpl_local_dir/$tpl_id_header.tpl");
	}
	push @info, &readf("$tpl_local_dir/$tpl_id.tpl");
	if($action eq "tpl2")
	{
		push @info, &readf("$tpl_local_dir/$tpl_id_footer.tpl");
	}
	
	if($vid_plugin == 1)
	{
		@info = &insert_req_vid_tpls(@info);		
	}
	@info = &insert_req_tpls(@info);
	@info = &insert_vars(@info);

	if($action eq "tpl1" || $vid_plugin == 1)
	{
		print @info;
		exit 1;
	}
}

elsif($action eq "sc_search")
{
	$genre		= param('genre');
	$count  	= param('count');
	$sc_url		= param('sc_url');
	
	@info = &readf("$tpl_local_dir/sc_search_header.tpl");
	@tmp = &readf("$tpl_local_dir/sc_search_body.tpl");
	$tmp_url = $sc_url . $genre . "&startat=$count";
	@d = &www_get("$tmp_url");
	
	for(@d)
	{
		if(/.*?<a href=\"(\/sbin\/shoutcast-playlist\.pls\?.*?)\".*/i)
		{
			$pls_url = $1;
			$pls_url = "http://shoutcast.com$pls_url";
		}
		if(/<a id=\"listlinks\" target=\"_scurl\".*?>(.*?)<\/a>/i)
		{
			$pls_title = $1;
			@tmp2 = @tmp;
			for(@tmp2)
			{
				s/<<title>>/$pls_title/ig;
				s/<<file>>/$pls_url/ig;
				s/<<count>>/$count/ig;
			}
			push @info, @tmp2;
		}
	}
	
	$count += 20;
	@tmp = &readf("$tpl_local_dir/sc_search_footer.tpl");
	for(@tmp)
	{
		s/<<count>>/$count/ig;
		s/<<genre>>/$genre/ig;
		s/<<sc_url>>/$sc_url/ig;
	}
	push @info, @tmp;
}

elsif($action eq "sc_pls_load")
{
	$title	= param('title');
	
	my @pls = &www_get("$file");
	
	print "<!-- file = $file
	pls: @pls -->\n";
	my @tmp = &readf("$tpl_local_dir/config.inc.php.tpl");
	for(@pls)
	{
		if(/File\d*=/i)
		{
			s/File\d*=//ig;
			s/\s*$//;

			$sc_url = $_;
			s/^http:\/\///ig;

			if(/(.*?):(\d+)\/(.*)/i)
			{
				$h = $1;
				$p = $2;
				$url_path = $3;
			}
			elsif(/(.*?):(\d+)\/{0,1}$/i)
			{
				$h = $1;
				$p = $2;
				$url_path = "/";
			}
			if($url_path ne "/")
			{
				next;
			}
			last;
		}
	}
	
	for(@tmp)
	{
		s/<<host>>/$h/ig;
		s/<<port>>/$p/ig;
		s/<<title>>/$title/ig;
		s/<<path>>/$url_path/ig;
	}
	
	open(FILE, ">$theme_local_dir/shoutcast/config.inc.php");
	print FILE @tmp;
	close(FILE);
	
	$goto_url = "$cgi_dir/?action=tpl&id=shout_play";
	$msg = "Station set to <b>$title</b>, going to shoutcast player";
	
	@info = &readf("$tpl_local_dir/msg.tpl");
}

elsif($action eq "favs")
{
	@info = &readf("$tpl_local_dir/favs_header.tpl");
	@favs = &readf("$favourites");
	@tmp = &readf("$tpl_local_dir/favs_body.tpl");
	for(@favs)
	{
		chomp;
		@tmp2 = @tmp;
		($name, $file) = split(/\t+/);
		for(@tmp2)
		{
			s/<<file>>/$file/ig;
			s/<<name>>/$name/ig;
		}
		push @info, @tmp2;
	}
	push @info, &readf("$tpl_local_dir/favs_footer.tpl");
}

elsif($action eq "options")
{
	if(param('theme'))
	{	
		$theme 		= param('theme');
	}
	if(param('flvtool'))
	{
		$flvtool_exe	 	= param('flvtool');
	}
	if(param('use_flvtool'))
	{
		$use_flvtool	 	= param('use_flvtool');
	}
	if(param('enc_exe'))
	{
		$enc_exe		= param('enc_exe');
	}
	if(param('enc_opts'))
	{
		$enc_opts		= param('enc_opts');
	}
	if(param('duration'))
	{
		$duration		= param('duration');
	}
	if(param('drive_list'))
	{
		$drive_list		= param('drive_list');
	}

	@info 		= &readf("$tpl_local_dir/msg.tpl");
	$msg 		= "Config Settings Saved. Returning To Config Screen.";
	$goto_url	= "$cgi_dir/index.pl?action=tpl&id=config";
	&save_config;
}

elsif($action eq "pls_del")
{
	open(FILE, ">$mp3_pls") or die "";
	close(FILE);
	open(FILE, ">$mp3_txt") or die "";
	close(FILE);

	@info 		= &readf("$tpl_local_dir/msg.tpl");
	$msg 		= "Playlist Cleared, returning to config menu.";
	$goto_url	= "$cgi_dir/index.pl?action=config";
}

elsif($action eq "pls_update")
{
	&update_mp3_pls;
	@info 		= &readf("$tpl_local_dir/msg.tpl");
	$msg 		= "Playlist Updated, returning to config menu.";
	$goto_url	= "$cgi_dir/index.pl?action=config";
}

elsif($action eq "jobs_del")
{
	opendir(DIR, "$work_dir") or die "couldnt open dir: \"$work_dir\" to read\n";
	@dir = readdir(DIR);
	close(DIR);
	
	system("$sys_shell $tools_local_dir/kill_encoder");
	
	for(@dir)
	{
		if(!/\.(bat|sh)$/i)
		{
			next;
		}
		$file = "$work_dir/$_";
		unlink("$file");
	}

	@info 		= &readf("$tpl_local_dir/msg.tpl");
	$msg 		= "Jobs cleared, returning to config menu.";
	$goto_url	= "$cgi_dir/index.pl?action=config";
}

elsif($action eq "playlist")
{
	@info = ();
	push @info, &readf("$tpl_local_dir/playlist_header.tpl");
	@tmp = &html_edit_pls;
	push @info, @tmp;
	push @info, &readf("$tpl_local_dir/playlist_footer.tpl");
}

elsif($action eq "delete")
{
	@info =  &readf("$tpl_local_dir/playlist_del.tpl");
	for(@info)
	{
		s/<<name>>/$name/ig;
		s/<<file>>/$file/ig;
	}
	@tmp = &readf("$mp3_txt");
	open(FILE, ">$mp3_txt") or die "couldnt open $mp3_txt to update";

	$c = 0;
	for(@tmp)
	{
		chomp;
		if(/$file$/)
		{
			$c++;
			next;
		}
		if($c != $file)
		{
			print FILE "$_\n";
		}
	$c++;
	}
	&update_mp3_pls;	
}

elsif($action eq "drive")
{
	$file =~ s/\/*$/\//ig;
	chdir $file;
	chdir "/";
	$our_wd = cwd();
	@info = &lsdir;
}

elsif($action eq "mp3adddir")
{
	@info 	= &readf("$tpl_local_dir/msg.tpl");
	@tmp 	= &read_dir("$our_wd");
	@tmp 	= &update_mp3_pls_filter(@tmp);
		
	open(FILE, ">>$mp3_txt");
	for(@tmp)
	{
		if($_ eq "." || $_ eq "..")
		{
			next;
		}
		print FILE "$our_wd/$_\n";
	}
	close(FILE);
	&update_mp3_pls;
	
	$goto_url = "$cgi_dir/?action=tpl&id=mp3_play";
	if(!-f "$tpl_local_dir/mp3_play.tpl")
	{
		$goto_url = "$theme_dir/mp3play";
	}
	$msg = "dir loaded";
	
	@info = &readf("$tpl_local_dir/msg.tpl");
}

elsif($action eq "favsadddir")
{
	$file_title 	= $our_wd;
	$file_loc	= $our_wd;
	
	$file_title	=~ s/\\/\//g;
	$file_title	=~ s/^.*\/(.*)$/$1/eg;
	$file_loc	=~ s/\\/\//g;
		
	open(FILE, ">>$favourites");
	print FILE "$file_title\t\t$file_loc\n";
	close(FILE);
	
	$goto_url = "$cgi_dir/";
	$msg = "$file_title added to favourites";
	
	@info = &readf("$tpl_local_dir/msg.tpl");
}

elsif($action eq "file" and -d $file)
{
	chdir $file;
	$our_wd = cwd();
	$our_wd =~ s/\\/\//g;
	@info = &lsdir;
}

elsif($action eq "file" and $file =~ /\.swf$/ig)
{
	@info 		= &lsdir;

	@info 		= &readf("$tpl_local_dir/msg.tpl");
	$msg 		= ("Trying to load $file.");

	$loc 		= "";
	$loc 		= "$our_wd/$file";
	$loc		= CGI::escapeHTML($loc);

	$goto_url	= "$cgi_dir/fileget.php?loc=".$loc;
}

elsif($action eq "links")
{
	@info = &readf("$links");
	for(@info)
	{
		s/^\s*-\s*/<hr style=\"width:80%;\"\/>/;
		s/^b$/<br\/>/i;
		s/(.*)\t+(.*)/<font size=\"5\"><a href=\"$2\">$1<\/a><\/font><br\/>\n/;
	}
}

elsif($action eq "file" && -f $file && $file =~ /\.($pf_ext)$/i)
{
	my $loc="$our_wd/$file";
	$loc = CGI::escapeHTML($loc);
	@tmp = &read_dir("$our_wd");
	@tmp2 = ();
	for(@tmp)
	{
		if(/\.($pf_ext)$/i)
		{
			push @tmp2, $_;
		}
	}
	
	$file_forward = $file_back = $tmp2[0];
	
	$count = 1;
	my $s = scalar @tmp2;
	for(@tmp2)
	{
		if(/^$file$/)
		{
			if($count == $s)
			{
				$file_forward = $tmp2[0];
			}
			else
			{
				$file_forward = $tmp2[($count)];
			}
			if($count == 0)
			{
				$file_back = $tmp2[($s - 1)];
			}
			else
			{
				$file_back = $tmp2[($count - 2)];
			}
		}
		$count++;
	}
	
	@info = &readf("$tpl_local_dir/pic_display.tpl");
	for(@info)
	{
		s/<<loc>>/$loc/ig;
		s/<<file>>/$file/ig;
		s/<<file_back>>/$file_back/ig;
		s/<<file_forward>>/$file_forward/ig;				
	}
}

elsif($action eq "file" && -f $file && $file =~ /\.(mp3|m3u|pls)$/i)
{
	@info = &readf("$tpl_local_dir/mp3.tpl");
	my @new_mp3s = ();

	if($file =~ /mp3$/i)
	{
		@new_mp3s = ("$our_wd\/$file\n");
	}
	elsif($file =~ /\.(m3u|pls)$/i)
	{	# assuming playlist
	
		@tmp = &readf("$our_wd/$file");
		# assume pls
		for(@tmp)
		{
			s/^\s*|\s*(\n|\r)*$//ig;	# trim string
			if(!/^File/i && !/mp3$/i && /^#/)
			{
				print "<!-- rejecting: $_ -->\n";
				next;
			}

			# cleanup
			
			s/\\/\//g;
			s/^File\d+\=//ig;

			# if we are using relative paths, change it to full path for wiicr
			if(!/^(\/|\w:)/i)
			{
				$_ = "$our_wd/$_\n";
				print "<!-- changed path to: $_ -->\n";
			}
			else
			{
				$_ = "$_\n";
			}
			push @new_mp3s, $_;
		}
	}

	for(@new_mp3s)
	{
		s/\/\//\//g;	# avoid c://test.mp3
		s/\\/\//g;	# avoid c:\
	}

	open(FILE, ">>$mp3_txt") or die "ERROR couldnt open $mp3_txt";
	print FILE @new_mp3s;
	close(FILE);

	&update_mp3_pls;
	print "<!-- !! $file -->";	
}

elsif($action eq "file" and -f $file && $file =~ /\.($mf_ext)$/i)
{
	$cmd = "\"$perl_exe\" \"$cgi_local_dir/encode.pl\" \"$our_wd\/$file\"";
	$rand = rand();
	open(FILE, ">>$work_dir/$rand.bat");
	print FILE "$cmd\n";
	close(FILE);

	@info = &readf("$tpl_local_dir/encoding.tpl");
}

elsif($action eq "file" and !-f $file)
{
	$cwd = cwd();
	$error_msg = "sorry we cant see $file in current directory: $cwd";
	@info = &readf("$tpl_local_dir/error.tpl");
}

else
{
	@info = &lsdir;
}

#--------------------------------------------------------------------------------------------------------------
# Done everything, fill in template and print webpage

for(@html)
{
	s/<<info>>/@info/ig;
}

@html = &insert_req_tpls(@html);
@html = &insert_vars(@html);

print @html;

exit 1;

#--------------------------------------------------------------------------------------------------------------
# subroutines
#--------------------------------------------------------------------------------------------------------------

sub lsdir 
{
	my @dir 	= &read_dir_s(".");
	my @data 	= ();
	my @tmp 	= ();
	my $tmp2 	= "";
	my $file 	= "";
	my @tmp 	= &readf("$tpl_local_dir/dir_header.tpl");
	my $dirs 	= \&html_cwd;
	my $dl_tpl 	= ""; 
	$file_loc	= cwd();
	$our_wd		= cwd;
	$file_loc =~ s/\\/\//ig;
	for(@tmp)
	{
		s/<<dirs>>/$dirs->()/eig;
		s/<<cwd>>/$our_wd/ig;
	}
	
	if(-f "$tpl_local_dir/lsdir_download.tpl")
	{
		$dl_tpl = join(/ /, &readf("$tpl_local_dir/lsdir_download.tpl"));
	}
	@tmp2 = ();
	push @data, @tmp;
	
	@tmp = &readf("$tpl_local_dir/dir_body.tpl");

	for(@dir)
	{
		if(!$_)
		{
			next;
		}
		$ico_tmp = $ico_bin;
		
		$dl_insert = $dl_tpl;
		if(-d $_ && $_ eq "..")
		{
			$ico_tmp = $ico_up;
			$dl_insert = "";
		}		
		elsif(-d $_)
		{
			$ico_tmp = $ico_dir;
			$dl_insert = "";
		}		
		elsif(/\.($tf_ext)$/i)
		{
			$ico_tmp = $ico_txt;
		}		
		elsif(/\.(mp3|m3u|pls)$/i)
		{
			$ico_tmp = $ico_mp3;
		}		
		elsif(/\.swf$/i)
		{
			$ico_tmp = $ico_flash;
		}		
		elsif(/\.($pf_ext)$/i)
		{
			$ico_tmp = $ico_pic;
		}		
		elsif(/\.($mf_ext)$/i)
		{
			$ico_tmp = $ico_vid;
		}
		elsif(/\.(zip|ace|tar|gz|rar|r\d{2})$/i)
		{
			$ico_tmp = $ico_zip;
		}		
		
		$file_name = $file = $_;

		@tmp2 = @tmp;
		for(@tmp2)
		{
			s/<<download>>/$dl_insert/ig;
		}
		for(@tmp2)	# note: shift to insert_vars
		{
			s/<<file_name>>/$file_name/ig;
			s/<<file_loc>>/$file_loc/ig;
			s/<<file>>/$file/ig;
			s/<<icon>>/$ico_tmp/ig;
			s/<<cwd>>/$our_wd/ig;	
		}
		
		push @data, @tmp2;
	}
	push @data, &readf("$tpl_local_dir/dir_footer.tpl");
	
	$string = join(/\n/, @data);
	
	return $string;
}

#--------------------------------------------------------------------------------------------------------------
sub html_edit_pls
{
	my @mp3_list = &readf("$mp3_txt");
	my @data = ();
	my @tmp = &readf("$tpl_local_dir/playlist_body.tpl");

	my $c = 0;
	for(@mp3_list)
	{
		if(!$_)
		{
			$c++;
			next;
		}

		$name = $_;
		$name =~ s/.*\/(.*?\.mp3)$/$1/ig;
		@tmp2 = @tmp;
		for(@tmp2)
		{
			s/<<cwd>>/$our_wd/ig;
			s/<<file>>/$c/ig;
			s/<<name>>/$name/ig;			
			s/<<ico_del>>/$ico_del/ig;
		}
		push @data, @tmp2;
		$c++;
	}
	return @data;
}


#--------------------------------------------------------------------------------------------------------------

#--------------------------------------------------------------------------------------------------------------
# update_mp3_pls

# Note: its only xml code in this sub, 0 html.

sub update_mp3_pls 
{
	my @tmp 		= &readf("$mp3_txt");
	my @tmp3		= ();
	my $file_title		= "";
	my $loc			= "";
	my $count		= 0;
	
	my @pls_header	= &readf("$tpl_local_dir/mp3_pls_header.tpl");
	my @pls_body	= &readf("$tpl_local_dir/mp3_pls_body.tpl");
	my @pls_footer	= &readf("$tpl_local_dir/mp3_pls_footer.tpl");	

	@tmp = &update_mp3_pls_filter(@tmp);
		
	open(FILE, ">$mp3_txt");
	for(@tmp)
	{
		print FILE "$_\n";
	}
	close(FILE);
	
	open(FILE, ">$mp3_pls");
	print FILE @pls_header;
	
	for(@tmp)
	{
		$file_title = $_;
		$file_title =~ s/^.*\///ig;
		$file_title =~ s/\.mp3$//ig;
		$file_title =~ s/(_|\.)/ /ig;
		$file_title =~ s/^(\s+|-|\d+)+//ig;
		$file_location = $_;		

		@tmp3 = @pls_body;
		for(@tmp3)
		{
			s/<<cgi>>/$cgi_dir/ig;
			s/<<file_title>>/$file_title/ig;
			s/<<file_location>>/$loc/ig;
			s/<<count>>/$count/ig;
		}
		$count++;
		print FILE @tmp3;
	}
	
	print FILE @pls_footer;
	close(FILE);

	# backwards compat code for theme
	if(-d "$theme_local_dir/mp3play")
	{
		copy($mp3_pls, "$theme_local_dir/mp3play/mylistdata.xml")
	}
	return 1;
}

sub update_mp3_pls_filter
{
	my @arr = @_;
	my @arr_new = ();
	
	@arr = &uniq_arr(@arr);
	@arr = sort(@arr);
	for(@arr)
	{
		$_ =~ s/\n|\r//g;
		$_ =~ s/\s+$//g;
		$_ =~ s/^\s+//g;
		
		if($_ !~ /\.mp3$/i)
		{
			print "<!-- mp3_filter - rejected: file isnt an mp3: \"$_\"--> \n";
			next;
		}
		if(/^\/\//)	# we dont handle network paths right now.
		{
			print "<!-- mp3_filter - rejected: we dont like network paths: \"$_\"--> \n";
			next;
		}
		if( !-f $_)
		{
			print "<!-- mp3_filter - rejected: file doesnt exist: \"$_\"--> \n";

			next;
		}
		
		push @arr_new, $_;
	}	
	return @arr_new;
}

sub www_get
{
	my $url 	= shift;
	my $brow 	= LWP::UserAgent->new();
	my $content 	= 0;
	my $i 		= 0;
	
	while (!$content)	# just keep retrying till we get it
	{
		$i++;

		if($i == 10)
		{
			last;
		}
		
		$request 	= HTTP::Request->new(GET => $url);
		$response 	= $brow->request($request);
	
		if ($response->is_error())
		{
			next;
		}
		
		$content 	= $response->content();

	}
	return split(/\n/, $content);
}

# genereate select dialog for theme selection

sub html_theme_combo
{
	my @tmp = &read_dir("$wiicr_local_dir/themes");
	
	my $combo = ("<select NAME=\"theme\">\n");
	for(@tmp)
	{
		if($_ eq "." || $_ eq ".." || !-d "$wiicr_local_dir/themes/$_")
		{
			next;
		}
		if($_ eq $theme)
		{
			$combo .= "<option value=\"$_\" selected=\"selected\">$_</option>\n";
		}
		else
		{
			$combo .= "<option value=\"$_\">$_</option>\n";
		}
	}
	$combo .= "</select>";

	return $combo;
}

sub html_enc_combo
{
	my @tmp = &readf("$wiicr_local_dir/enc_opts.txt");
	
	my $combo = ("<select name=\"enc_opts\">\n");
	for(@tmp)
	{
		s/#.*//ig;
		s/\r|\n//ig;
		s/\s+$//ig;
		($a, $b) = split(/\s*\t+\s*/);
		
		if($a eq "" || $b eq "")
		{
			next;
		}
		if($b eq $enc_opts)
		{
			$combo .= "<option value=\"$b\" selected=\"selected\">$a</option>\n";
		}
		else
		{
			$combo .= "<option value=\"$b\">$a</option>\n";
		}
	}
	$combo .= "</select>";

	return $combo;
}

sub html_file_content
{
	my @tmp = &readf("$file");
	my $string = join(/\n/, @tmp);
	return $string;
}

# Insert Vars

sub insert_vars
{
	my $theme_combo 	= \&html_theme_combo;
	my $file_content 	= \&html_file_content;
	my $enc_opts_combo 	= \&html_enc_combo;
	my $lsdir_content 	= \&lsdir;
	my $dirs		= \&html_cwd;

	my $count1 = $count - 1;
		
	print "<!-- \$use_flvtool = $use_flvtool -->\n";
	$use_flvtool_check = "";
	if($use_flvtool eq "on")
	{
		$use_flvtool_check_on = "checked";
		$use_flvtool_check_off = "";
	}
	else
	{
		$use_flvtool_check_off = "checked";
		$use_flvtool_check_on = "";
	}
	
	my @arr = @_;
	
	for(@arr)
	{
		s/<<ico_config>>/$ico_config/ig;
		s/<<ico_play>>/$ico_play/ig;
		s/<<icon_back>>/$ico_back/ig;
		s/<<icon_forward>>/$ico_forward/ig;
		s/<<icon_dir>>/$ico_dir/ig;
		s/<<ico_dir>>/$ico_dir/ig;
		s/<<error_msg>>/$error_msg/ig;

		s/<<goto_url>>/$goto_url/ig;
		s/<<msg>>/$msg/ig;

		s/<<date>>/$date/ig;
		s/<<version>>/$version/ig;
		s/<<vars>>/$vars_data/ig;
		s/<<count>>/$count/ig;
		s/<<count-1>>/$count1/ig;
			
		s/<<cwd>>/$our_wd/ig;		
		s/<<cgi>>/$cgi_dir/ig;
		s/<<theme_dir>>/$theme_dir/ig;
		s/<<flv_dir>>/$flv_dir/ig;	
		s/<<flv_local_dir>>/$flv_local_dir/ig;	
	
		s/<<drives>>/@drives_data/ig;
		s/<<background>>/$background/ig;
	
		s/<<lsdir>>/$lsdir_content->()/eig;
		s/<<enc_opts_combo>>/$enc_opts_combo->()/eig;
		s/<<theme_combo>>/$theme_combo->()/eig;
		s/<<dirs>>/$dirs->()/eig;

		s/<<file_content>>/$file_content->()/eig;
		s/<<file>>/$file/ig;
		s/<<file_name>>/$file_name/ig;
		s/<<file_loc(ation|)>>/$file_location/ig;
		
		s/<<enc_exe>>/$enc_exe/ig;
		s/<<flv_tool>>/$flvtool_exe/ig;
		s/<<use_flvtool_check_on>>/$use_flvtool_check_on/ig;
		s/<<use_flvtool_check_off>>/$use_flvtool_check_off/ig;
		s/<<enc_opts>>/$enc_opts/ig;
		s/<<duration>>/$duration/ig;
		s/<<drive_list>>/$drive_list/ig;
	}
	
	return @arr;
}

sub insert_req_tpls
{
	my @arr = @_;
	my $tmp = "";
	my $replace_me = "";
	my $tpl_object = "";
	my $count = 0;
	
	while($count < 4)
	{
		for(@arr)
		{
			s/<<drives>>/@drives_data/ig;
			s/<<link_buttons>>/@link_buttons/ig;
			
			# insert user selected tpl's
			
			if(/<<tpl_object: .*?>>/)
			{
				$tmp = $_;
				$tmp =~ s/<<tpl_object:\s*(.*?)\s*>>/$1/ig;	# get tpl name
				$replace_me = $_;
				$replace_me =~ s/(<<tpl_object:.*?>>)/$1/;	# grab bracket to replace
				$tpl_object = "$tpl_local_dir/$tmp.tpl";
				$tpl_object =~ s/\n|\r//ig;
				
				print "<!-- \$tmp = $tmp \n \$tpl_object = \"$tpl_object\"\n \$replace_me = \"$replace_me\" -->\n";
				if(-f "$tpl_object")				# see if tpl exists
				{
					@tpl_object = &readf("$tpl_object");	# read tpl then insert
	
					s/$replace_me/@tpl_object/ig;
				}
				else
				{
					print "<!-- Sorry but tpl : \"$tpl_object\" doesnt exist -->\n";
				}
			}
		}
		$count++;
	}
	return @arr;
}

# Insert Requested Video Teplate objects

# this has to be done before normal templates because some vars are different.

sub insert_req_vid_tpls
{
	print "<!-- inserting requested video templates -->";
	my @arr = @_;
	my $tmp = "";
	my $video_object_tpl = "";
	my @video_object = ();
	my $n = 0;
	
	while($n < 4)
	{
		for(@arr)
		{
			if($_ =~ /<<video_object:\s*.*?>>/ig)
			{
				$tmp = $_;
				$tmp =~ s/.*<<video_object:\s*(.*?)\s*>>.*/$1/ig;
				$tmp =~ s/\n|\r//ig;
				print "<!-- \$tmp = \"$tmp\" -->\n";
				$video_object_tpl = "$tpl_local_dir/video_object_$tmp.tpl";
				print "<!-- video object file = $video_object_tpl -->";
				if(-f "$video_object_tpl")
				{
					@video_object = &readf("$video_object_tpl");
					s/<<video_object:\s*.*?>>/@video_object/ig;
				}
				else
				{
					print "<!-- ERROR: couldnt load video_object: \"$video_object_tpl\" -->\n";
				}
			}
		}
	
		# we also do the video specific vars here
		for(@arr)
		{
			s/<<filename>>/$filename/ig;
			s/<<file_http>>/$file_http/ig;
			s/<<file_local>>/$file_local/ig;						
			s/<<redirect_url>>/$redirect_url/ig;
			s/<<file>>/$file/ig;
			s/<<count>>/$count/ig;
			s/<<duration>>/$tmpdur/ig;
		}
		$n++;
	}
	return @arr;
}

sub html_cwd
{
	my @arr = ();
	my $dir = $our_wd;
	$dir =~ s/\\/\//g;
	my @tmp = split(/\//, $dir);
	my $s = "";
	my $file_name = "";
	my $file_loc = "";
	
	push @arr, &readf("$tpl_local_dir/dirs_header.tpl");
	@tmp2 = &readf("$tpl_local_dir/dirs_body.tpl");
	for(@tmp)
	{
		$s .= "$_/";
		$file_name = $_;
		$file_loc = $s;

		@tmp3 = @tmp2;
		for(@tmp3)
		{
			s/<<file_name>>/$file_name/ig;
			s/<<file_loc>>/$file_loc/ig;
		}
		push @arr, @tmp3;
	}
	push @arr, &readf("$tpl_local_dir/dirs_footer.tpl");
	
	my $string = join(/ /, @arr);
	
	return $string;
}

sub save_config
{
	open(FILE, ">$wiicr_local_dir/config.dat") or die "ERROR: couldnt write to config.dat";
	print "<!-- save config says - \$duration = $duration -->\n";

	print FILE 
"
##################
# WiiCR settings #
##################

theme		= $theme
flvtool_exe	= $flvtool_exe
use_flvtool	= $use_flvtool
enc_exe		= $enc_exe
enc_opts	= $enc_opts
duration	= $duration
drive_list	= $drive_list

########################
# OS Specific settings #
########################

xampp_dir	= $xampp_dir
perl_exe	= $perl_exe
sys_shell	= $sys_shell

";

	close(FILE);
}

1;