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

print <<eND;
Content-type: text/html

eND

$cookieid = "atid";
$cookie = $ENV{"HTTP_COOKIE"};

$cookie =~ m/$cookieid\=([^;]+)/;
$id = $1;

$time = time;

$id = $time unless $id;

$subfolder = substr($id,0,3);

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




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

$event = param("event");
$fl = param("fl");

if ($event eq "change") {
	$target = param("msg");
	$target =~ s/\{/(/gm;
	$target =~ s/\{/)/gm;
	@newphrases = split /(\n\r\n\m)/, $target;
	open(DATA,">ids/$subfolder/$id/$fl.txt");
	foreach $newphrase (@newphrases) {
		if ($newphrase =~ m/\S/) {
			print DATA "$newphrase";
			push @phrases, "$newphrase";
		}
	}
	close(DATA);
	$event = "edit";
}

else {
	open(DATA,"ids/$subfolder/$id/$fl.txt");
	@phrases = <DATA>;
	close(DATA);
	push @togo, qq~<p>To delete a phrase, simply erase it. To add phrases, add it or insert it on its own line. You can also edit phrases. When you are done, click on "Change to These Phrases"~;
}

if ($event eq "edit") {
	push @togo, qq~<p>Your changes were made. You can keep making more changes or go back to your Modification Center~;
	push @togo, qq~<form method=post action="/cgi-bin/veryrare/editphrasesall.pl"><center><textarea name=msg rows=25 cols=60>~;
	foreach $phrase (@phrases) {
		push @togo, qq~$phrase~;
	}

	push @togo, qq~</textarea><br><input type=submit value="Change to These Phrases"></center><input type=hidden name=event value=change><input type=hidden name=fl value=$fl></form>~;
	push @togo, qq~<p><a href=/cgi-bin/atmain.pl>Return to Training</a>~;
	push @togo, qq~<p><a href=/cgi-bin/veryrare/editphrasesall.pl?event=edit;fl=nphrases>Edit Distractor Phrases instead</a>~ if $fl eq "yphrases";
	push @togo, qq~<p><a href=/cgi-bin/veryrare/editphrasesall.pl?event=edit;fl=yphrases>Edit Target Phrases instead</a>~ if $fl eq "nphrases";
	printonblankerpage(@togo);
}

exit;

sub printonblankerpage {
	@toprint = @_;
	chdir("/home12c/sub007/sc13648-GPVH/at");
	open(DATA,"cgi-bin/shells/atshell.htm") || open(DATA,"cgi-bin/atshell.htm")  || print "There was a problem reading body: $!";
	@lines = <DATA>;
	close(DATA);
	$contentmarker = "<!--content-->";

	foreach (@lines) {
		if (m/$contentmarker/o) {
			print @toprint;
		}
		else {
			print;
		}
	}
	exit;
}

sub savechangestomain {
	open(DATA,">ids/$subfolder/$id/main.txt") || open(DATA,">ids/$subfolder/$id/main.txt")  || print "problem writing to main for some reason: $!<BR>\n";
	@keys = keys(%info);
	foreach (@keys) {
		$i = $info{$_};
		print DATA "$_=$i\n";
	}
	close(DATA);
	return;
}

