#!/usr/bin/env python

import sys

# this version returns the maximum temperature value for each 
# station, year and month
# the output is comparable to merge.py

#NOTE this is an executable file (set permissions accordingly)

#echo "G049;2003;2009;1;2003,2004,2005,2006,2007,2008,2009" | ./mapper.py | sort -k1,3 | ./reducer.py

#do not print out stuff except the \t separated ouput
#comment out reamining print statements

#maybe monthly averages are less extreme

#monthly maximum values 
#for the first 5 years and for second 5 years could be directoy returned
#instead of monthly maximum for every year, 
#keep this way because it allows more detailed view at the data

currentStation = None
currentYear = None
currentMonth = None
currentMaximum = -200

maxTempAllowed = 55

for line in sys.stdin:
  #trailing or leading spaces are not expect but keep for safety
  line = line.strip()
  #print line
  tmp = line.split('\t')
    
  try:
    temp = float(tmp[3])    
  except ValueError:
    # omit current 'line' if it does not contain a number
    # e.g., it will be the case with missing values stored as '-'
    continue
  
  if temp > maxTempAllowed:
    continue
  
  station = tmp[0]
  year = tmp[1]
  month = tmp[2]  
  
  if currentStation == station and currentYear == year and currentMonth == month:  
    currentMaximum = max(currentMaximum, temp)
  else:
    if currentStation != None:
      print "%s\t%s\t%s\t%s" % (currentStation, currentYear, currentMonth, currentMaximum)    
    currentStation = station
    currentYear = year
    currentMonth = month
    currentMaximum = temp

# in principle it will always be the case that currentStation == station
# and same for the other variables, but just in case keep the if statement;
# try: catch failure if 'station' does not exist because it was not created above
try:
  if currentStation == station and currentYear == year and currentMonth == month:
    print "%s\t%s\t%s\t%s" % (currentStation, currentYear, currentMonth, currentMaximum)
  else:
    #print "last station was not printed out"
    pass
except NameError:
  pass
