#!/usr/bin/perl

# Perl script to print the list of students who have registered for a 
# course by a particular professor
# invoked as FindStudent.pl datafile1 datafile2 professor-name

# sample datafile1
# student course marks for quizzes.
# 00305001        CS201   5 23 54 2
# 00305002        CS201   3 38 12 5
# 00305003        CS201   9 43 4 0
# 00305008        CS208   10 22 94 2
# 00305005        CS296   5 10 22 7
# 00305006        CS201   5 2 67 2
# 00305001        CS221   7 03 89 1
# 00305008        CS201   8 29 15 5
# 00305009        CS299   0 55 10 2
# 00305001        CS205   1 33 77 0

# sample datafile2
# instructor course weightage of diff tests.
# aad     cs221   0.3 0.3 0.3 0.1
# siva    cs296   0.25 0.25 0.25 0.25
# dmd     cs201   0.2 0.15 0.5 0.15
# sak     cs299   0.1 0.4 0.1 0.4
# rkj     cs208   0.7 0.1 0.1 0.1
# ramesh  cs205   0.1 0.4 0.25 0.25

$numargs = @ARGV;

# Print Usage
unless ($numargs == 3){
	die ("Usage: FindStudent.pl datafile1 datafile2 professor-name");
}

$datafile1 = $ARGV[0];
$datafile2 = $ARGV[1];
$professor = $ARGV[2];

# Test for file open, quit on failure
unless (open(FILE1,$datafile1)) {
	die ("Cannot open input file $datafile1\n");
}

unless (open(FILE2,$datafile2)) {
	die("Cannot open input file $datafile2\n");
}

# Read datafile2 and create an index on course number
# use of associative arrays is recommended

$line = <FILE2>;
while ($line ne "") {
	# field separator is one or more whitespace(tab or space).
	@array = split(/[ 	]+/,$line);
	
	# use lower case to make key case insensitive.
	$Professor{lc($array[1])} = $array[0] ;
	$line = <FILE2>;
}	

close(FILE2);

# Read datafile1 and use the course number to find the professor. 

$line = <FILE1>;
while ($line ne "") {
	# field separator is one or more whitespace(tab or space).
	@array = split(/[ 	]+/,$line);

	# use lower case to make key case insensitive.
	if($Professor{lc($array[1])} eq $professor)	{

		# Add to list of students if there is a match on professor.
		push(@students,$array[0]);	
	}
	$line = <FILE1>;
}

close(FILE1);

# Print the output
$string = join("\n",@students);
print "$string \n";
