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

basicheader() unless $ARGV[0];

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


$cookieid = "atid";
$cookie = $ENV{"HTTP_COOKIE"};
if ($cookie =~ m/$cookieid\=([^;]+)/) {
	$id = $1;
}
else {
	print "cookie was $cookie<BR>\n";
	printpage("index.htm");
}
$subfolder = substr($id,0,3);

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

$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/at/t/$dirid");
$dirlocation = "/home12c/sub007/sc13648-GPVH/at";
chdir($dirlocation) || print "Couldn't change directory $!<BR>\n";

##### get the page to put data in
if ($fl =~ m/jack/i) {
	open(DATA,"cgi-bin/shells/atshell.htm") || open(DATA,"cgi-bin/shells/atshell.htm") || gracefulend(" reading scriptshell ($!)");
}
else {
	open(DATA,"cgi-bin/shells/atshell.htm") || open(DATA,"cgi-bin/shells/atshell.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
$pic = $info{"pics"};
$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;
		if ($j eq "z") {
			$pic = $info{"picloc"};
			if ($pic eq "you") {
				print "This is not available at this time<BR>\n";
			}
			elsif ($pic eq "select") {
				$igname = $info{"igname"};
				$imagedir[$i] = ("images/$igname");
			}
			else {
				$imagedir[$i] = ("pics/$subfolder/$id");
			}
		}
		else {
			@imgd = split /\,/, $_;
			if (@imgd > 1) {
				@imgd = grep ! m/$name/, @imgd;
				$r = int(rand(@imgd));
				$_ = $imgd[$r];
				m/othergirls.(.+)/;
				$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/at/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/at/" . $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) {
	s/IGNAME/$igname/go;
	if (s/^\~\~\~/<p>/) {
		s/HERNAME/$othername/go;
		s/NAME/$name/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 (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/at");
	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;
}




