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

basicheader() unless $ARGV[0] eq "bh";

$time = time;
chdir("/home12c/sub007/sc13648-GPVH/") || print "Couldn't change directory $!<BR>\n";

$cookie = $ENV{"HTTP_COOKIE"};
$id = $1 if $cookie =~ m/cpid\=([^;,]+)/;
$subfolder = substr($id,0,1);
exit unless $id;
open(DATA,"CPs/$subfolder/$id/girl.txt") || open(DATA,"girls/$subfolder/$id/girl.txt");
while ($_ = <DATA>) {
	$info{$1} = $2 if m/^([^=]+)\=(.*)/;
}
close(DATA);
$name = $info{"name"};

open(DATA,"CPs/$subfolder/$id/chr.txt") || open(DATA,"CPs/$subfolder/$id/chr.txt");
while ($_ = <DATA>) {
	$infochr{$1} = $2 if m/^([^=]+)\=(.*)/;
}
close(DATA);

$phr = param("phr");

($fl = param("fl")) || ($fl = $ARGV[0]);
$tease = param("tease");
$tl = $info{"traininglevel"};

printpage("index.htm") unless $fl;

$newfile = $fl;

$fl =~ s/\.txt//;
$shortprefix = $fl;
$prefix = "t/$fl";

$time = time();
srand($time - 1000 * int($time/1000));



##############

$dirid = $id . $time;
mkdir("/home12c/sub007/sc13648-GPVH/cp/t/$dirid");
$dirlocation = "/home12c/sub007/sc13648-GPVH/cp";
chdir($dirlocation) || print "Couldn't change directory $!<BR>\n";

##### get the page to put data in

open(DATA,"cgi-bin/shells/scriptshell.htm") || open(DATA,"cgi-bin/shells/scriptshell.htm") || gracefulend(" reading scriptshell");

@lines = <DATA>;
close(DATA);
$endfront = "<!---endfront--->";
$startend = "<!---startend--->";
$stage = 1;
foreach (@lines) {
	if (m/$endfront/o) {
		$stage = 2;
	}
	elsif (m/$startend/o) {
		$stage = 3;
	}
	elsif ($stage == 1) {
		push @front, $_;
	}
	elsif ($stage == 3) {
		push @end, $_;
	}
}

############## Getting the script

open(DATA,"cgi-bin/scripts/$newfile") || open(DATA,"cgi-bin/scripts/$newfile") || gracefulend(", for some reason, reading $newfile");
@lines = <DATA>;
close(DATA);


########### finding the random picture files at the start
$i = 0;
CHECKFORRANDOM: foreach (@lines) {
	if (m/^\*\*\*(\S*)/) {
		$firstpage = $1;
		last CHECKFORRANDOM;
	}
	elsif (s/image\-random(.)\: //) {
		$j = $1;
		$findimagefile{"$j"} = $i;
		$singular[$i] = 1 if $j eq "~";
		chomp;   #????
		s/\s+$//;
		if ($j eq "s") {
			$imagedir[$i] = "images/people/$subfolder/$id";
		}
		elsif ($j eq "h") {
			($hyppic=$info{"hyppic"}) || ($hyppic = "e2");
			$imagedir[$i] = "images/images/$hyppic";
		}
		elsif ($j eq "b") {
			if (opendir(FILES,"/home12c/sub007/sc13648-GPVH/cp/images/people/$subfolder/$id/br") ) {
				closedir(FILES);
				$imagedir[$i] = "images/people/$subfolder/$id/br";
			}
			else {
				$imagedir[$i] = "images/$_";
			}
		}
		elsif ($j eq "q") {
			$targetname = param("targetname");
			$targetname = "Miranda" unless $targetname;
			$imagedir[$i] = "images/people/$targetname";
		}
		elsif ($j eq "c") {
			if (opendir(FILES,"/home12c/sub007/sc13648-GPVH/cp/images/people/$subfolder/$id/ct") ) {
				closedir(FILES);
				$imagedir[$i] = "images/people/$subfolder/$id/ct";
			}
			else {
				$imagedir[$i] = "images/$_";
			}
		}
		elsif ($j eq "o") {
			open(DATA3,"cgi-bin/newbin/files/haremgirls.txt") || open(DATA3,"cp/cgi-bin/newbin/files/haremgirls.txt") || print "couldn't open harmgirls.txt: $!<BR>\n";;
			while ($_ = <DATA3>) {
				push @women, "images/people/$1" if m/(\w+)/;
			}
			close(DATA3);
			@women = grep ! m/$name/i, @women;
			$r = int(rand(@women));
			$othername = $women[$r];
			$imagedir[$i] = "images/people/$othername";
		}
		elsif ($j eq "~") {
			$imagedir[$i] = "images/cate/paralite";
			$imagedir[$i] = "images/cate/para" if $tl > 13;
			$imagedir[$i] = "images/cate/para2" if $tl >= 17;
			$imagedir[$i] = "images/cate/para3";  ####should key on training top
		}
		else {
			@imgd = split /\,/, $_;
			if (@imgd > 1) {
				@imgd = grep ! m/$name/, @imgd;
				$r = int(rand(@imgd));
				$_ = $imgd[$r];
				m/people.(.+)/;
				$othername = $1;
			}
			$imagedir[$i] = "images/$_";
		}
		$i++;
	}
}


######## random pictures
for ($i=0; $i < @imagedir; $i++) {
#### get picture names and store in @temp 2
	if ($imagedir[$i] =~ m/^images\/([te]pic)s/) {
		$type = $1 . "choices";
		@pfl = split /\,/, $info{"$type"};
		@temp2 = ();
		foreach (@pfl) {
			$jfile = "/home12c/sub007/sc13648-GPVH/cp/images/cate/$_";
			opendir(FILES,$jfile) || print "Couldn't open directory +$jfile+: $!<BR>\n";
			@temp = readdir(FILES);
			closedir(FILES);
			@temp3 = grep m/(jpg|jpeg|gif|tif|bmp)/i, @temp;
			foreach $temp (@temp3) {
				push @temp2, "cate/$_/$temp";
			}
		}
		$imagedir[$i] = "images";
	}
	else {
		$jfile = "/home12c/sub007/sc13648-GPVH/cp/" . $imagedir[$i];
		opendir(FILES,$jfile) || print "Couldn't open directory ++$jfile++: $!<BR>\n";
		@temp = readdir(FILES);
		closedir(FILES);
		@temp2 = grep m/(jpg|jpeg|gif|tif|bmp)/i, @temp;
	}

#### shuffle and store in rimagesfilesnames
	$n = @temp2;
	@temp2 = shuffle(@temp2);
	$counter[$i] = 0;
	$ncounter[$i] = $n;
	$ncounter[$i] = 1 if $singular[$i];
	$rimagesfilenames[$i] = [];
	foreach $fl3 (@temp2) {
		push @{$rimagesfilenames[$i]}, $imagedir[$i]. "/" . $fl3;
	}
}

$starting = "yes";

$imagestart = "<img src=/";


## Edit the regular lines
$namemarker = "<!--name-->";
foreach (@lines) {
	if (s/^\~\~\~/<p>/) {
		s/HERNAME/$othername/go;
		s/NAME/$name/go;
	}
	elsif (param("sgtarget") eq "yes") {
		s/NAME/$targetname/go;
	}
	s/$namemarker/$name/o;
	while (m/\!\!\!prefix([\w\-]+)/ ) {
		push @links,$1;
		s/\!\!\!prefix/t\/$dirid\//;
	}
	s/TARGETFET/$targetfet/go;
	if (m/^image/) {
		if (m/^image.*random(.)/) {
			$jj = $1;
			addimage($jj);
		}
		else {
			s/ .*//;
			push @images, $_;
			chomp;
			$_ = "<img src=/images/" . $_ . " align=right class=picture>\n";
		}
	}
	elsif (m/^(stories|cate|supplies)\//) {
		s/ .*//;
		push @images, $_;
		chomp;
		$_ = "<img src=/images/" . $_ . " align=right class=picture>\n";
	}
	elsif (s/\#\#\#([\w\-]*)//) {
		chomp;
		$link = $1;
		push @links,$link;
		$_ = "<p><a href=/t/" . $dirid . "/" .  $link . ".htm>" . $_ . "</a>\n";

	}
	elsif (s/\@\@\@//) {
		chomp;
		push @links,$_;
		$_ = "<input type=hidden name=nextfile value=/t/" . $dirid . "/" .  $_ . ".htm>";
	}
	elsif (s/^INSTRUCTION(.)\://) {
		$temp = $1;
		if ($temp ne $instruction) {
			$_ = "";
		}
		else {
			$_ = "<p>" . $_;
		}
	}
	elsif (m/OTHERNAME/) {
		s/OTHERNAME/$othername/go;
	}

	elsif (m/TRIGGER/) {
		$trigger = $infochr{"trigger"};
		s/TRIGGER/$trigger/go;
	}
	elsif (m/^[\w"]/) {
		$_ = "<p>" . $_;
	}
	elsif (m/^\*\*\*([\w\-]*)/) {
		push @addresses, $1;
		if ($starting eq "yes") {
			$starting = "no";
		}
		else {
			push @newlines,"</td></tr></table></body></html>\n";
		}
	}
	if (m/^\*\*\*/) {
		if (s/\+\+\+(\d+) (.+)//) {
			$link = $2;
			$t = $1;
			push @links,$link;
			$url = "/t/" . $dirid . "/" .  $link . ".htm";
			$url = $link if substr($link,0,1) eq "/";
			#$entry = '<meta http-equiv="refresh" content="' . $t . "000;URL=/t/" . $dirid . "/" .  $link . '.htm">' . "\n";
			$entry = '<meta http-equiv="refresh" content="' . $t . "000;URL=" . $url . '">' . "\n";

			push @newlines, $_;
			push @newlines, "<html><head>\n";
			push @newlines, $entry;
		}
		else {
			push @newlines, $_;
			push @newlines, "<html><head>\n";
		}
		push @newlines,@front;
	}
	else {
		push @newlines, $_;
	}
}

push @newlines,"</td></tr></table></body></html>";


foreach (@newlines) {
	if (m/^\<meta http\-equiv\=\"refresh/) {
		s/000//;
	}
}

$counter = 0;

foreach (@newlines) {
	if (m/^\*\*\*([\w\-]+)/) {
		$nextfile = $1;
		if ($counter > 0) {
			$fl = "t/" . $dirid . "/" . $newfile . ".htm";
			open(DATA,">$fl") || open(DATA,">$fl") || gracefulend("There was a problem opening $fl for writing.");
			print DATA $newpage;
			close(DATA);

		}
		$newfile = $nextfile;
		$counter++;
		exit if $counter > 500;
		$newpage = "";
	}
	elsif ($counter > 0) {
		$newpage .= $_;
	}
}
####writing the last page -- the others were done as new pages were found
$fl = "t/" . $dirid . "/" . $newfile . ".htm";
open(DATA,">$fl") || open(DATA,">$fl") || gracefulend("There was a problem opening $fl for writing.");
print DATA $newpage || gracefulend("Error writing to $fl.");
close(DATA);

($p = param("start")) || ($p = $ARGV[1]);
printpage("t/$dirid/$p.htm");

exit;


sub basicheader {
	print <<eND;
Content-type: text/html

eND
	return;
}

sub gracefulend {
	$mssg = $_[0];
	print <<eND;
<BR>There was a problem: $mssg.
</body>
</html>
eND
	exit;
}

sub printpage {
	$fl = $_[0];
	chdir("/home12c/sub007/sc13648-GPVH/cp");
	open(DATA,"$fl") || open(DATA,"$fl") || gracefulend("There was a problem reading $fl");
	@lines = <DATA>;
	close(DATA);
	$name = $info{"name"};
	foreach (@lines) {
		s/$namemarker/$name/o;
		print;
	}
	basicclose();
}

sub basicclose {
	print <<eND;
</td></tr></table>
</body>
</html>
eND
	exit;
}

###apparently does images that aren't tpic or epic

sub addimage {
	my $jj = $_[0];
	$i = $findimagefile{"$jj"};
	print "Seems to be an image without a file: $jj<BR>\n" unless defined($findimagefile{"$jj"});
	$pict = ${$rimagesfilenames[$i]}[$counter[$i]];
	$counter[$i]++ unless ($jj eq "<" || $jj eq ">" || $jj eq "{" || $jj eq "}" || $jj eq "[" || $jj eq "]" || $jj eq "(" || $jj eq ")");
;
	$counter[$i] = 0 if $counter[$i] == $ncounter[$i];
	push @images, $pict;
	$_ = "<img src=/" . $pict . " align=right class=picture>\n";
	return;
}

sub shuffle {
	$n = @_;
	my $temp;
	for ($j=0; $j < $n - 1; $j++) {
		$k = int( rand(1) * ($n-$j) ) + $j;
		$temp = $_[$k];
		$_[$k] = $_[$j];
		$_[$j] = $temp;
	}
	return @_;
}

sub addphrase {
	my $let = $_[0];
	$p = ${$phrases{$let}}[$phrasecounter{$let}];
	push @trlines, "<p>Imagine " . $p;
	$phrasecounter{$let}++;
	$phrasecounter{$let} = 0 if $phrasecounter{$let} == $phrasetotal{$let};
}

sub addpic {
	my $let = $_[0];
	$r = \@tpics if $let eq "t";
	$r = \@epics if $let eq "e";
	$pict = $$r[$counter{$let}];
	$counter{$let}++;
	$counter{$let} = 0 if $counter{$let} == $ncounter{$let};
	push @images, $pict;
	push @trlines, "<img src=/" . $pict . " align=right class=picture>\n";
	return;
}




