#!/usr/local/bin/perl

# COMS3101 Perl Fall 2013
# HW3
# cup_match.pl

# Call sub to read file
%games = &read_games($ARGV[0]);

# Request user input
&prompt_user;
chomp($request = <STDIN>);

# Continue until user types 'q' or 'Q'
while (lc($request) ne "q") {
  # Process request
  ($ctry, $team) = split(/,/,lc($request)); 

  # Check if request is valid
  if (exists $games{$ctry}{$team}) {
     &print_match($_) for (@{$games{$ctry}{$team}}); 
  }
  else  {
     print "WRONG FLAG/TEAM, TRY AGAIN!";
  }

  # Request input
  &prompt_user;
  chomp($request = <STDIN>);
}


# Code to test for output
print "-" x 50; print "\n";
&print_match($_) for (@{$games{"sco"}{"celtic"}});
print "-" x 50; print "\n"; 
&print_match($_) for (@{$games{"sui"}{"fc-sion"}}); 


# Sub to build the structure
sub read_games {
   # Initialize  
   my %games = ();
   my @match_fds = ("team","flag","game1","game2");

   # Read from file
   my $fname = shift;
   open(UEFA,$fname);
   while (<UEFA>) { 
      chomp $_;
      my ($team1,$flag1,$team2,$flag2,$res1,$res2) 
         = split(/\t/,$_);
      
      # Initialize two hashes
      my (%match1, %match2);
      # Store the match for both teams  
      @match1{@match_fds} = ($team2,$flag2,$res1,$res2); 
      @match2{@match_fds} = ($team1,$flag1,$res1,$res2);  

      # Insert match into the games structure
      push @{ $games{lc($flag1)}{lc($team1)} }, \%match1;
      push @{ $games{lc($flag2)}{lc($team2)} }, \%match2;

   }
   close(UEFA);    
   return %games;
}

# Sub to print one match
sub print_match {
   my $href = shift;
   print "Match:\t";
   print "$href->{team},$href->{flag},";
   print "$href->{game1},$href->{game2}\n\n";
}

# Prompt for user to enter input
sub prompt_user {
     print"\n"; print "*" x 50;
     print "\nPlease enter a flag,team pair ";
     print "or type q/Q to quit: \n\n";
}

