#!/usr/bin/perl -w
#Title:  final_problem5.pl

use strict;

if ( @ARGV eq 0 ){
  die "Usage:\t$0\tdata_file\n";
}  

my $data_file = shift ;
my ( @dates,@mins, @maxs);
print "Check this file: $data_file\n";
# open data and populate 3 arrays (dates, mins, and maxs)
open (DATA,"<$data_file") 
	or die "Could not open $data_file: $!\n";
while (<DATA>){
  chomp( my ($date, $min, $max) =split (/\t/, $_));
  $date =~ tr/:/-/;
  push (@dates, $date );
  push (@mins, $min );
  push (@maxs, $max );
}

# 1. find the minimum temp in the file.
my ($min,$i)=ArrayMin( \@mins );
print "The lowest temperature of the year was $min Fahrenheight.\n";
print "The lowest temperature was recorded on $dates[$i].\n\n";

# 2. find the maximum temp in the file.
my ($max,$j)=ArrayMax( \@maxs );
print "The highest temperature of the year was $max Fahrenheight.\n";
print "The highest temperature was recorded on $dates[$j].\n\n";


# problem 4a
sub ArrayMin{
  my $ar_unsorted = shift;
  #get the min
  my @ArrayMinFellers = sort { $a <=> $b } @$ar_unsorted ;
  my $min = $ArrayMinFellers[0];
  #determin which element of the original array has it
  for ( $a=0; $a <= $#$ar_unsorted; $a++ ){
     if ( $ar_unsorted->[$a] =~ m/^$min$/ ){ 
        $i=$a;
	last;
     }
  }
  return ($min,$i); 
} 

# problem 4b
sub ArrayMax{
  my $ar_unsorted = shift;
  #get the min
  my @ArrayMaxFellers = sort { $a <=> $b } @$ar_unsorted ;
  my $max = $ArrayMaxFellers[-1];
  #determin which element of the original array has it
  for ( $a=0; $a <= $#$ar_unsorted; $a++ ){
     if ( $ar_unsorted->[$a] =~ m/^$max$/ ){ 
        $i=$a;
	last;
     }
  }
  return ($max,$i); 
} 
