#Michael Giarrizzo, Deshawn Williams, Steven Vascellaro
print "content-type:text/html; charset=utf-8\n\n";
use strict;
use CGI qw/:standard/;
my $search = param("input")||"";

print <<ENDTAG;
<html>
<title>Catalog System</title>
<body>

<a href="table_1.txt">Click here to view the Game Characters</a>
<br>
<a href="table_2.txt">Click here to view the Games associated with the characters</a>
<br>
<a href="table_3.txt">Click here to view the association table</a>
<br><br>
Enter a Character to search for:<br>

<form method="POST" action="testsr.pl">
<input type="text" name="input"><br>
  <input type="submit" name="Submit">
</form>
ENDTAG

if ($search)
{
	chomp($search);
	print qq(<br>The search word is $search. <br>);
	search();
}
else
{
	print qq(<br>No search word was entered<br>);
}
print <<ENDTAG;
</body>
</html>
ENDTAG

sub search
{
	#print "Please enter a character name to see what game's they are associated with. \n"; 
	#my $search  = <STDIN> ;
	#chomp($search);
	my $file = "/home/st21077/public_html/software_1/perl_catalog_nov_23/table_1.txt";
	my $targetfile = "/home/st21077/public_html/software_1/perl_catalog_nov_23/table_2.txt";
	my $keyfile = "/home/st21077/public_html/software_1/perl_catalog_nov_23/table_3.txt";


	############READ IN TABLE 1 TO AN ARRAY CALLED @linerray
	open (FH, '<', "$file") or die "Can't open $file for read: $!";
	my @lines;
	my @linearray;
	while (my $lines = <FH>)
	{
		#@linearray = split(",", $lines);
		push(@linearray, $lines);   
	}
	close FH or die "Cannot close $file: $!";

	print "\n";


	############READ IN TABLE 2 TO AN ARRAY CALLED @targetlinerray
	open (FH, '<', "$targetfile") or die "Can't open $targetfile for read: $!";
	my @targetlines;
	my @targetlinearray;
	while (my $targetlines = <FH>)
	{
		push(@targetlinearray, $targetlines);
	}
	close FH or die "Cannot close $targetfile: $!";

	#print @targetlinearray; for testing to see contents of array

	############READ IN TABLE 3 TO AN ARRAY CALLED @keylinerray
	open (FH, "< $keyfile") or die "Can't open $keyfile for read: $!";
	my @keylines;
	my $ckey;
	my @keylinearray;
	while (my $keylines = <FH>)
	{
		push(@keylinearray, $keylines);
	}
	close FH or die "Cannot close $keyfile: $!";

	#print @keylinearray; for testing to see contents of array

	############### FOR LOOP TO GO THROUGH ARRAY 1 LINE AT A TIME
	my $kkey;
	foreach my $row (@targetlinearray)
	{
		chomp($row);
		#my $lin = split(",", $row);
		#print join(':', split(',', $row)), "\n";
		#print $lin;
		if ($row =~ m/$search/)
		{
			## reggex matcher
			#print $row;
			my @key = split(",", $row); 
			print "\n";
			#print $key[0];
			$ckey = $key[0];
		}
		else
		{

		}
	}
	#print $ckey;

	foreach my$row (@keylinearray)
	{
		chomp ($row);
		if ($row =~ m/(\d),$ckey/)
		{
			my @key = split(",", $row);
			$kkey = $key[0];
			foreach my $row2 (@linearray)
			{
				chomp ($row2);
				if ($row2 =~ m/$kkey/)
				{
					print $row2;
					print "<br/>";
				}
			}
		}
	}

}


