#!/usr/bin/perl

# Perl Script which calculates the total marks scored by a student in
# a given course.
# Invoked as FindTotal.pl datafile1 datafile2 roll-number course-number

# 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 == 4){
	die ("Usage: FindStudent.pl datafile1 datafile2 roll-number course-number");
}

$datafile1 = $ARGV[0];
$datafile2 = $ARGV[1];
$roll = $ARGV[2];
$course = $ARGV[3];

# 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 record the weighing scheme for that course.
# 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.
	if(lc($array[1]) eq lc($course)) {
		@weights = ($array[2],$array[3],$array[4],$array[5]);
		# we are done ; need not read any more input.
		last;
	}
	$line = <FILE2>;
}	

close(FILE2);

# The array @weights stores the weights we require.

# Now read  datafile1 and use the course-number and roll-number to find 
# the absolute marks we are interested in.

$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((lc($array[1]) eq lc($course)) && (lc($array[0]) eq lc($roll))){
		@marks = ($array[2],$array[3],$array[4],$array[5]);
		# we are done ; need not read any more input.
		last;
	}
	$line = <FILE1>;
}

close(FILE1);

# Calculate total marks and print the output
for ($i=0 ; $i < 4 ; $i++) {
	$total += $weights[$i] * $marks[$i];
}

print "The total is : $total \n";

