#!/usr/bin/perl -w

print "content-type:text/html; charset=utf-8\n\n";
print "<p>hello world!</p>";
print "<p>you searched for $search</p>"

use CGI qw(:cgi-lib :standard);  # Use CGI modules that let people read data passed from a form
&ReadParse(%in);                 # This grabs the data passed by the form and puts it in an array
$search = $in{"search"};         # Get the user's name and assign to variable
chomp($search);

my $file = "table_1.txt";
my $targetfile = "table_2.txt";
my $keyfile = "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";
#print @lines; 

############### FOR LOOP TO GO THROUGH ARRAY 1 LINE AT A TIME 
#foreach my $row (@linearray)
#{
	#chomp($row);
	#my $lin = split(",", $row);
	#print join(':', split(',', $row)), "\n";
	#print $lin;
	#if ($row =~ m/$search/) {## reggex matcher
	#print $row;
	#}
	#else
	#{

	#}
#}

############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 "\n";
			print $row2;
			print"\n";
		}


		#print $kkey;
		#print $row;
		}
	}
}