<?php 


function display_progress() {
	$task_completed = 0;
	$total_completed = 0;
	$total_time = 0;
	
	$line = file("judgements");
	for($i=0;$i<count($line);$i++) {
		list($t,$j,$assignmentid,$type,$judgment,$time) = split(" \|\|\| ",chop($line[$i]));
		if ($j == $_POST["ANNOTATOR"]) {
			$total_completed++;
			if ($t == $_POST["TASK"]) {
				$task_completed++;	
			}
			$total_time+=$time;
		}

	}
	
	if ($total_completed > 0) {
		print("<FONT COLOR=#800000>You have judged ".$task_completed." sentences for <B>".$_POST["TASK"]."</B>, ".$total_completed." sentences total");
		if ($total_time> 0) {
			print (" taking ".number_format($total_time/$total_completed,1)." seconds per sentence");
		}
		print(".</FONT><BR><HR><BR>");
	}

	
	
}

function display_sentence() {
	global $translation,$translation_file,$translation_name,$source,$constituent,$reference,$task_type,$assignments;

	$assignment_id = get_next_assignment();
	
	list($assignment_type,$assignment_number,$assignment_info_string) = split("-",$assignment_id);
	$system_id_list = split(",",$assignment_info_string);
	
	display_head($assignment_type);
	
	//TODO: disable this for MT Workshop to stop server overloading?
	display_progress();
	
	//common header form info
	
	?>
	<FORM ACTION="" METHOD=POST>
	<INPUT TYPE=HIDDEN NAME=ASSIGNMENTID VALUE="<?php print($assignment_id);?>">
	<INPUT TYPE=HIDDEN NAME=ASSIGNMENTS VALUE="<?php print(join(";",$assignments));?>">
	<INPUT TYPE=HIDDEN NAME=TIME VALUE="<?php print(time());?>">
	<?php
	
		if ($assignment_type == "N") {
				
			print "<B>Source:</B> ".display_one_line($source,$assignment_number);
			
			for($i=0;$i<count($reference);$i++) {
				print "<P><B>Reference:</B> <FONT COLOR=#008000>".display_one_line($reference[$i],$assignment_number)."</FONT>\n";
			}
			?>
			<TABLE BORDER=1>
			<TR><TD><B>Translation</B></TD><TD><B>Adequacy</B></TD><TD><B>Fluency</B></TD></TR>
			<?php
			foreach($system_id_list as $system_id) {
				if (file_exists($translation_file[$system_id])) {
					print "<TR BGCOLOR=#F0F0FF><TD><FONT COLOR=#000080>".display_one_line($translation_file[$system_id],$assignment_number);
					//print ($GLOBALS["translation_file"][$system_id]." ".$GLOBALS["translation_id"][$system_id]);
					?>
					</FONT></TD><TD NOWRAP>
					<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=0><TR>
					<?php
					for($j=1;$j<=5;$j++) {
						print "<TD><INPUT TYPE=RADIO NAME=ADEQUACY_$system_id VALUE=$j></TD>\n";
					}
					print "</TR>\n<TR>";
					for($j=1;$j<=5;$j++) {
						print "<TD ALIGN=CENTER>$j</TD>\n";
					}
					?>
					</TR></TABLE>
					</TD><TD NOWRAP>
					<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=0><TR>
					<?php
					for($j=1;$j<=5;$j++) {
						print "<TD><INPUT TYPE=RADIO NAME=FLUENCY_$system_id VALUE=$j></TD>\n";
					}
					?>
					</TR>
					<TR>
					<?php
					for($j=1;$j<=5;$j++) {
						print "<TD ALIGN=CENTER>$j</TD>\n";
					}
					?>
					</TR></TABLE>
					</TD></TR>
					<?php
				}
			}
	
		} elseif ($assignment_type == "R") {
				
			print "<B>Source:</B> ".display_one_line($source,$assignment_number);
			
			for($i=0;$i<count($reference);$i++) {
				print "<P><B>Reference:</B> <FONT COLOR=#008000>".display_one_line($reference[$i],$assignment_number)."</FONT>\n";
			}
			?>
			<TABLE BORDER=1>
			<TR><TD><B>Translation</B></TD><TD><B>Rank</B></TD></TR>
			<?php
			foreach($system_id_list as $system_id) {
				if (file_exists($translation_file[$system_id])) {
					print "<TR BGCOLOR=#F0F0FF><TD><FONT COLOR=#000080>".display_one_line($translation_file[$system_id],$assignment_number);
					//print ($GLOBALS["translation_file"][$system_id]." ".$GLOBALS["translation_id"][$system_id]);
					?>
					</FONT></TD><TD NOWRAP>
					<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=0><TR>
					<?php
					for($j=1;$j<=5;$j++) {
						print "<TD WIDTH=75 ALIGN=CENTER><INPUT TYPE=RADIO NAME=RANK_$system_id VALUE=$j></TD>\n";
					}
					print "</TR>\n<TR>";
					for($j=1;$j<=5;$j++) {
						print "<TD TD WIDTH=75 VALIGN=TOP ALIGN=CENTER>$j";
						if ($j==1) print"<BR>Worst";
						if ($j==5) print"<BR>Best";
						print "</TD>\n";
					}
					?>
					</TR></TABLE>
					</TD>
					</TD></TR>
					<?php
				}
			}
			
		} elseif ($assignment_type == "C") {
			
			$constituent_info_string = display_one_line($constituent,$assignment_number);
			
			list($sentence_number,$constituent_type) = split(" \|\|\| ",$constituent_info_string);
			
			//TODO: the sentence numbers stored in the constituent file start at 1, not 0
			$sentence_number--;
			
			$constituent_map = load_constituent_locations($system_id_list,$constituent_info_string);

			//print_r($constituent_map);
			
			print "<B>Source:</B> ".display_one_phrase($source,$sentence_number,$constituent_map["src"]["start_word"],$constituent_map["src"]["end_word"]);

			//for($i=0;$i<count($reference);$i++) {
			//	print "<P><B>Reference:</B> <FONT COLOR=#008000>".display_one_phrase($reference[$i],$assignment_number)."</FONT>\n";
			//}
			
			//only 1 ref for constituents
			print "<P><B>Reference:</B> <FONT COLOR=#008000>".display_one_phrase($reference[0],$sentence_number,$constituent_map["ref"]["start_word"],$constituent_map["ref"]["end_word"])."</FONT>\n";

			?>
			<TABLE BORDER=1>
			<TR><TD><B>Translation</B></TD><TD><B>Rank</B></TD></TR>
			<?php
			foreach($system_id_list as $system_id) {
				$system_name = $GLOBALS["translation_id"][$system_id];
				if (file_exists($translation_file[$system_id]) && array_key_exists($system_name,$constituent_map)) {
					print "<TR BGCOLOR=#F0F0FF><TD><FONT COLOR=#000080>".display_one_phrase($translation_file[$system_id],$sentence_number,$constituent_map[$system_name]["start_word"],$constituent_map[$system_name]["end_word"]);
					//print ($GLOBALS["translation_file"][$system_id]." ".$GLOBALS["translation_id"][$system_id]);
					?>
					</FONT></TD><TD NOWRAP>
					<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=0><TR>
					<?php
					for($j=1;$j<=5;$j++) {
						print "<TD WIDTH=75 ALIGN=CENTER><INPUT TYPE=RADIO NAME=C_RANK_$system_id VALUE=$j></TD>\n";
					}
					print "</TR>\n<TR>";
					for($j=1;$j<=5;$j++) {
						print "<TD TD WIDTH=75 VALIGN=TOP ALIGN=CENTER>$j";
						if ($j==1) print"<BR>Worst";
						if ($j==5) print"<BR>Best";
						print "</TD>\n";
					}
					?>
					</TR></TABLE>
					</TD>
					</TD></TR>
					<?php
				}
			}
			
		}
	
	//common end task info
	?>
	<TR><TD><P><FONT COLOR=#800000><B>Annotator:</B> <?php print($_POST[ANNOTATOR]);?></B>
	<INPUT TYPE=HIDDEN NAME=ANNOTATOR VALUE="<?php print($_POST[ANNOTATOR]);?>">
	<INPUT TYPE=HIDDEN NAME=PWD VALUE="<?php print($_POST[PWD]);?>">
	<B>Task:</B> <?php print($_POST[TASK]);?></B>
	<INPUT TYPE=HIDDEN NAME=TASK VALUE="<?php print($_POST[TASK]);?>"></FONT>
	</TD><TD COLSPAN=2 ALIGN=RIGHT><INPUT TYPE=SUBMIT VALUE="Annotate"></TD></TR>
	
	<?
	
	display_instructions($assignment_type);
	
	?>

	</TABLE>
	</FORM>
	<?php
}

function load_constituent_locations($system_id_list,$constituent_info_string) {
	$constituent_info_list = split(" \|\|\| ",chop($constituent_info_string));
	$constituent_map = array();
	for($i=2;$i<sizeof($constituent_info_list);$i++) {
		list($system_name,$coverage_string) = split(":",$constituent_info_list[$i]);
		list($start_word,$end_word) = split("-",$coverage_string);
		$constituent_map[$system_name] = array();
		$constituent_map[$system_name]['start_word'] = $start_word;
		$constituent_map[$system_name]['end_word'] = $end_word;
	}
	
	return $constituent_map;
}


function display_instructions($assignment_type) {
	if ($assignment_type == "N") {
		
		?>
		<TR><TD VALIGN=TOP>Instructions</TD><TD>
		5= All Meaning<BR>
		4= Most Meaning<BR>
		3= Much Meaning<BR>
		2= Little Meaning<BR>
		1= None
		</TD><TD>
		5= Flawless English<BR>
		4= Good English<BR>
		3= Non-native English<BR>
		2= Disfluent English<BR>
		1= Incomprehensible
		</TD></TR>	
		<?php
		
	} elseif ($assignment_type == "R") {
		?>
		<TR><TD VALIGN=TOP>Instructions: <BR>Rank each <b>whole sentence</b> translation from Best to Worst relative to the other choices (ties are allowed).</TD><TD>
		&nbsp;
		</TD><TD>
		
		<?php
		
	} elseif ($assignment_type == "C") {
		?>
		<TR><TD VALIGN=TOP>Instructions: <BR>Rank each constituent translation from Best to Worst relative to the other choices (ties are allowed). Grade <FONT style='BACKGROUND-COLOR: yellow'><b>only the highlighted part</b></FONT> of each translation.<BR>
		<I>Please note that segments are selected automatically, and they should be taken as an approximate guide.  They might include extra words, or miss words on either end that are not in the actual alignment.</I></TD><TD>
		&nbsp;
		</TD><TD>
		
		<?php
		
	}	
	
}

function display_head($assignment_type) {
	if ($assignment_type == "N") {
		head("Judge Sentences");	
	} elseif ($assignment_type == "R") {
		head("Rank Whole Sentences");	
	}  elseif ($assignment_type == "C") {
		head("Rank Segments");	
	}
}

function display_one_line($file,$n) {
	$line = file($file);
	return $line[$n];
}

//try for tokenized version of the file, fail silently if not found
function display_one_line_tokenized($file,$n) {
	if (file_exists($file.".tok")) {
		$line = file($file.".tok");
	} else {
		$line = file($file);
	}
	return $line[$n];	
}

function display_one_phrase($file, $n, $start_word, $end_word) {
	$sentence = display_one_line_tokenized($file,$n);
	$word_list = split(" ",chop($sentence));
	$word_list[$start_word] = "<FONT style='BACKGROUND-COLOR: yellow'><B>".$word_list[$start_word];
	$word_list[$end_word-1] = $word_list[$end_word-1]."</B></FONT>";
	return(join(" ",$word_list));
	
}

function process_judgements() {
	
	global $translation_id, $assignments;
	
	
	if ($_POST["ASSIGNMENTID"]) {
		$success = false;
		
		
		list($assignment_type,$sentence_number,$assignment_info_string) = split("-",$_POST["ASSIGNMENTID"]);
		
		
		///NIST-Style
		
		if ($assignment_type == "N") {
			$types = array("ADEQUACY","FLUENCY");
			$score_hash = array();
			while (list($key, $value) = each($_POST)) {
				foreach ($types as $type) {
					if (preg_match("/${type}_(.+)/",$key,$reg)) {
						//at least one judgement is present, mark as a successful attempt
						$success = true;
						$score_hash[$translation_id[$reg[1]]][$type]=$value;
					}
				}
			}
			$nist_scores = array();
			foreach($score_hash as $system => $score_list) {
				$nist_scores[] = $system.":".($score_list["ADEQUACY"] ? $score_list["ADEQUACY"] : "-").",".($score_list["FLUENCY"] ? $score_list["FLUENCY"] : "-");
			}	
			if ($success) {
				$f = fopen("judgements","a");
				fputs($f,"$_POST[TASK] ||| $_POST[ANNOTATOR] ||| $_POST[ASSIGNMENTID] ||| NIST ||| ".join(" ",$nist_scores)." ||| ".(time()-$_POST[TIME])."\n");
				fclose($f);
			}
			
		//RANK
		} elseif ($assignment_type == "R") {
			$ranks = array();
			$systems = array();
			
			while (list($key, $value) = each($_POST)) {
				if (preg_match("/RANK_(.+)/",$key,$reg)) {
					//at least one judgement is present, mark as a successful attempt
					$success = true;
					$ranks[] = $translation_id[$reg[1]].":".$value;
				}
			}
			
			if ($success) {
				$f = fopen("judgements","a");
				fputs($f,"$_POST[TASK] ||| $_POST[ANNOTATOR] ||| $_POST[ASSIGNMENTID] ||| RANK ||| ".join(" ",$ranks)." ||| ".(time()-$_POST[TIME])."\n");
				fclose($f);
			}
		
		//CONSTITUENT RANK
		
		} elseif ($assignment_type == "C") {
			$ranks = array();
			$systems = array();
			
			while (list($key, $value) = each($_POST)) {
				if (preg_match("/C_RANK_(.+)/",$key,$reg)) {
					//at least one judgement is present, mark as a successful attempt
					$success = true;
					$ranks[] = $translation_id[$reg[1]].":".$value;
				}
			}
			
			if ($success) {
				$f = fopen("judgements","a");
				fputs($f,"$_POST[TASK] ||| $_POST[ANNOTATOR] ||| $_POST[ASSIGNMENTID] ||| CONSTITUENT ||| ".join(" ",$ranks)." ||| ".(time()-$_POST[TIME])."\n");
				fclose($f);
			}
			
		}
		
	
		if($_POST["ASSIGNMENTID"] == $assignments[0] && $success) {
			//remove element 0, they finished it
			array_shift($assignments);	
		} else {
			//LAZY BASTARD!
			print("<FONT color=red><B>No judgements scored. Please try again.</B></FONT><BR>");
		}
	}                           
}


function get_next_assignment() {
	global $assignments;
	return $assignments[0];	
}


function load_task_info() {
	global $annotator_conflict;
	
	$line = file("task");
	$index = 0;
	for($i=0;$i<count($line);$i++) {
		list($t,$key,$value,$value2) = split(" \|\|\| ",chop($line[$i]));
		if ($t == $_POST["TASK"]) {
			if ($key == "reference") {
				$GLOBALS[$key][] = $value;
			}
			else if ($key == "translation") {
				$GLOBALS["translation_file"][] = $value;
				$GLOBALS["translation_id"][] = $value2;
			} else if ($key == "test_types") {
				$GLOBALS["test_types"] = array();
				$ttypes = split(" ",$value);
				foreach($ttypes as $test_type) {
					$GLOBALS["test_types"][$test_type] = 1;		
				}
			} else if ($key == "repeat_list") {
				$GLOBALS["repeat_list"][$value] = split(" ",$value2);
			} else {
				$GLOBALS[$key] = $value;
			}
		}
	}

}



function load_assignment_list() {
	global $assignments;
	
	$assignment_string = $_POST["ASSIGNMENTS"];
	if (strlen($assignment_string) > 0) {
		$assignments = split(";",$assignment_string);
		if (count($assignments) > 0) {
			return true;
		}
	}
	else {
		//look through finished tasks, remember tasks as we find them
		
		$line = file("judgements");
		for($i=0;$i<count($line);$i++) {
			list($t,$j,$assignment_id,$system,$type,$judgment,$time) = split(" \|\|{2,3} ",$line[$i]);
			if ($t == $_POST["TASK"] && $j == $_POST["ANNOTATOR"]) {
				$already[$assignment_id] = $already[$assignment_id] + 1;
				if ($time>0) { 
					$total_time += $time; $count_time++;
				}
			}
		}
		
		$line = file("assignments");
		$index = 0;
		for($i=0;$i<count($line);$i++) {
			list($task,$annotator,$assignment_list_string) = split(" \|\|\| ",chop($line[$i]));
			if ($task == $_POST["TASK"] && $annotator == $_POST["ANNOTATOR"]) {
				$assignment_list_temp = split(";",$assignment_list_string);				
				foreach ($assignment_list_temp as $assignment_id) {
					if (!$already[$assignment_id]) {
						$assignments[] = $assignment_id;
					} else {
						$already[$assignment_id]--;
					}
				}
			}			
		}
		if (count($assignments) == 0) {
			return false;
		} else {
			return true;
		}

	}
	
}

function generate_new_assignments() {
	global $assignments,$annotator_conflict,$test_types;
	
	//how many randomly selected tasks in a work unit
	$NIST_RANDOM = 5;
	$RANK_RANDOM = 5;
	$CONSTITUENT_RANDOM = 10;
	
	//how many items from the global repeat set (if present, else random)
	$NIST_GLOBAL_REPEAT = 4;
	$RANK_GLOBAL_REPEAT = 4;
	$CONSTITUENT_GLOBAL_REPEAT = 9;
	
	//how many items from the previous 2 sets to randomly double-up within the work unit	
	$NIST_LOCAL_REPEAT = 1;
	$RANK_LOCAL_REPEAT = 1;
	$CONSTITUENT_LOCAL_REPEAT = 1;
	
	//This determines if test switching will be done
	$TEST_SWITCHING = true;
	
	//values for test switching
	$NIST_SWITCH_SIZE = 5;
	$RANK_SWITCH_SIZE = 5;
	$CONSTITUENT_SWITCH_SIZE = 10;

	
	if (!$test_types["CONSTITUENT"]) {
		//nevermind those units

		$CONSTITUENT_RANDOM = 0;
		$CONSTITUENT_GLOBAL_REPEAT = 0;
		$CONSTITUENT_LOCAL_REPEAT = 0;
	}

	//change max per page to the number of systems that are valid for us
	$max_per_page = $GLOBALS["max_per_page"];
	$allowed_systems = 0;
	foreach($GLOBALS["translation_id"] as $possible_system) {
		if (!$annotator_conflict[$_POST["ANNOTATOR"]][$possible_system]) $allowed_systems++;
	}
	if ($allowed_systems < $max_per_page) $max_per_page = $allowed_systems;
	
	if ($max_per_page == 0) {
		//ERROR: no valid systems for this user to grade
		print_r($GLOBALS);
		print("ERROR: no valid systems for this user to grade");
		return;
	}
	
	$task_setup = array("N" => array("random"=>$NIST_RANDOM,
					 "global_repeat"=>$NIST_GLOBAL_REPEAT,
					 "local_repeat"=>$NIST_LOCAL_REPEAT,
					 "switch_size"=>$NIST_SWITCH_SIZE,
					 "long_name"=>"NIST"),
		
			   "R" =>  array("random"=>$RANK_RANDOM,
					 "global_repeat"=>$RANK_GLOBAL_REPEAT,
					 "local_repeat"=>$RANK_LOCAL_REPEAT,
					 "switch_size"=>$RANK_SWITCH_SIZE,
					 "long_name"=>"RANK"),
			   
			   "C" => array("random"=>$CONSTITUENT_RANDOM,
					 "global_repeat"=>$CONSTITUENT_GLOBAL_REPEAT,
					 "local_repeat"=>$CONSTITUENT_LOCAL_REPEAT,
					 "switch_size"=>$CONSTITUENT_SWITCH_SIZE,
					 "long_name"=>"CONSTITUENT"));
	
	$task_order = array_keys($task_setup);
	shuffle($task_order);
	
	$toAssign = array();
	$new_assignment_count = 0;
	
	foreach($task_order as $task_type) {
		
		$type_assignments = array();
		
		$num_non_local_repeat = $task_setup[$task_type]["random"]+$task_setup[$task_type]["global_repeat"];
		
		//load the repeat list and shuffle it
		$repeat_list = $GLOBALS["repeat_list"][$task_setup[$task_type]["long_name"]];
		shuffle($repeat_list);
		
		//First assign all the tasks that require randomly pulling from the whole list or just the repeats
		for ($i=0;$i<$num_non_local_repeat;$i++) {	
			
			$n = 0;
			//Random first
			if ($i<$task_setup[$task_type]["random"]) {
				$max_number = 0;
				if ($task_type == "N" || $task_type == "R") {
					$max_number = $GLOBALS["max_sentence_number"]-1;
				} elseif ($task_type == "C") {
					$max_number = $GLOBALS["max_constituent_number"]-1;
				}
				$n = rand(0,$max_number);
			
			//Then repeat list
			} else  {
				//load the list of repeatable sentences
				#$repeat_list = $GLOBALS["repeat_list"][$task_setup[$task_type]["long_name"]];
				
				//randomly choose one
				#$max_number = sizeof($repeat_list)-1;
				#$index_n = rand(0,$max_number);

				//get its sentence number
				if (count($repeat_list > 0)) {
					$n = array_pop($repeat_list);
				} else {
					//not enough repeats!
					continue;
				}
				
			}
			
			//generate the new task
			$assignmentid = $task_type."-".$n;
			$systems = array();
			$already = array();
			do {
				$sys = rand(0,sizeof($GLOBALS["translation_id"])-1);
				if (!$already[$sys] && !$annotator_conflict[$_POST["ANNOTATOR"]][$GLOBALS["translation_id"][$sys]]) {
					$already[$sys] = 1;
					$systems[] = $sys;	
				}
			} while (sizeof($systems) < $max_per_page);
			
			$sysList=join(",",$systems);
			$assignmentid = $assignmentid."-".$sysList;
			$type_assignments[] = $assignmentid;
		}
				
		//OK, shuffle up this list, then tack local repeats onto the end
		shuffle($type_assignments);
		
		$type_assignments_size = sizeof($type_assignments);
		
		for ($i=0;$i<$task_setup[$task_type]["local_repeat"];$i++) {
			$n = rand(0,$type_assignments_size-1);
			$type_assignments[] = $type_assignments[$n];
		}
		
		//Instead of just appending to global array in this way, place each type alternating
		$toAssign[$task_type]= $type_assignments;
		$new_assignment_count += sizeof($type_assignments);
		
	}
	
	$new_assignments = array();
	
	
	//assign things in groups
	if (!$TEST_SWITCHING) {
		foreach($task_order as $task_type) {
			$new_assignments = array_merge($new_assignments,$toAssign[$task_type]);
		}	
	} else {
		while(sizeof($new_assignments) < $new_assignment_count) {
			foreach($task_order as $task_type) {
				for($i=0;$i<$task_setup[$task_type]["switch_size"] && sizeof($toAssign[$task_type]) > 0;$i++) {
					$new_assignments[] = array_shift($toAssign[$task_type]);
				}
			}
		}
	}
	
	$assignments = $new_assignments;
	$assignment_list = join(";",$assignments);
	
	$f = fopen("assignments","a");
	fputs($f,$_POST["TASK"]." ||| ".$_POST["ANNOTATOR"]." ||| ".$assignment_list."\n");
	fclose($f);
}

if (check_password()) {

	load_task_info();

	if ($_POST["GENERATEASSIGNMENT"]) {
		//user has requested a new work unit
		generate_new_assignments();

		if (sizeof($assignments) == 0) {
			//nothing to generate for this task
			print("You have completed all required judgements for task $_POST[TASK]. Please choose another task.");	
			include("select_task_contents.php");
			tail();
			exit;
		}
		
	} else {
		load_assignment_list();
		process_judgements();
	}
	
	if (sizeof($assignments) == 0) {		
		//Decide if this assignments = 0 is because they've never done anything for this task
		
		head("Choose Next Task");
		?>
		You have completed your current assignments for the task <b><?php print($_POST[TASK]);?></b>. Please choose your next task (or continue with your current task):
		<P>
		
		<?php
		include("select_task_contents.php");
	} else {
		//we have tasks remaining

		display_sentence(); 
	}

}
tail();
