#!/usr/bin/perl

use strict;
use warnings;
use Getopt::Long;  # include this to parse command line parameters

my $mergeFile;
my $line;

print "Enter the name of the directory containing all files to merge: ";
my $directoryName = <>;
chomp $directoryName;

my $pathname = $directoryName."/*";

my @rankFilenames = glob( "$pathname" );
my $numFiles = scalar( @rankFilenames );
# program exit conditions
if ( $numFiles <= 1 or $numFiles > 4 ){
	print "The number of files in the directory is not 2,3 or 4.\n";
	exit;
}

my %fileHash;
my $counter = 0; 
foreach my $i ( @rankFilenames ) {
	
	# open the input file for reading
	my $INPUT_FILE;
	open ( $INPUT_FILE , '<' , $i )
	or die "Cannot open the input file: $i: $!";

	while ( $line = <$INPUT_FILE> ) {
		chomp $line;
		my @currentLine = split( /\t/, $line );
		my $rank = $currentLine[ 0 ];
		my $name = $currentLine[ 1 ];
		my $amount = $currentLine[ 2 ];
		chomp $amount;
		
		if ( !exists $fileHash { $name } ) {
			
			@{ $fileHash{ $name } } = ( 0 ) x $numFiles;
			chomp @{ $fileHash{ $name } };
			splice( @{$fileHash{ $name }}, $counter, 1, $amount );
		} else {
			$fileHash{ $name }[ $counter ] = $amount;
		}
	}			
	close $INPUT_FILE;
	$counter++;
}

my $resultString = "";
foreach my $k ( keys %fileHash ){
	$resultString .= $k."\n".$fileHash{ $k }[ 0 ]."\n".$fileHash{ $k }[ 1 ]."\n".$fileHash{ $k }[ 2 ]."\n".$fileHash{ $k }[ 3 ]."\n";
}

my $OUTPUT_HANDLE;
my $outputFilename = "$directoryName/output.txt";
open( $OUTPUT_HANDLE, '>', $outputFilename )
or die "Cannot open the file: $outputFilename: $!";
printf $OUTPUT_HANDLE $resultString;
close $OUTPUT_HANDLE;

# open the input file for reading
my $INPUT_F;
my $second_input = "$directoryName/output.txt";
open ( $INPUT_F , '<' , $second_input )
or die "Cannot open the input file: $second_input: $!";

my $OUTPUT_F;
my $second_output = "$directoryName/output.xls";
open( $OUTPUT_F, '>', $second_output )
or die "Cannot open the file: $second_output: $!";


my $row = 0;
while ( $line = <$INPUT_F> ) {
	$row++;
	$line =~ tr/ \t\n\r//d;
	printf $OUTPUT_F $line."\t";
	if ( $row == 5 ){
		$row = 0;
		printf $OUTPUT_F "\n";
	}
}

close $OUTPUT_F;

system( "rm $directoryName/output.txt" );
