# -------------------------------------------------------------
# Problem:
# We are given a text file containing
# daily measurements of outdoor temperatures
# on a particular meteorological stations.
# Find the coldest year on record.


# Simple helper formatting function
# turns date format YYYYMMDD into DD.MM.YYYY
def getDate( dateStr ):
    # Date YYYYMMDD
    year = dateStr[0:4]
    month = dateStr[4:6]
    day = dateStr[6:8]
    return day + "." + month + "." + year

# -------------------------------------------------------------
# The coldestYear funcion depends in all details
# on the exact format of the data.
# Check the data file visually to see how the data are organized.

def coldestYear( fileName ):
    # named constants do help
    # columns 0 and 1 are not essential here
    dateColumn = 2
    temperColumn = 3
    qualityColumn = 4

    qualityValid = 0
    qualitySuspect = 1
    qualityMissing = 9


    # start reading
    file = open( fileName, "r" )

    # skip the file header
    while True:
        line = file.readline()
        if line[0:5] == "STAID": break

    minTemper = 10000 # start with big temperature
    dateMinTemper = 0

    totalTemper = 0
    noOfDays = 0

    # process all lines
    while True:
        line = file.readline()
        # detect possible empty lines to stop
        if line == None or line.strip(" ") == "":
            break

        # extract info from a text line
        lineVals = line.split(",")
        date =  lineVals[dateColumn]
        #date =  lineVals[2]

        dayTemper = int( lineVals[temperColumn] )
        quality = int( lineVals[qualityColumn] )

        # do not accept dubious data
        if quality != qualityValid:
            continue

        # Finding the coldest year on record
        # if date is 0101 that is Jan 1  start registering the current year
        # if date is 1231 that is Dec 31  end registering the current year
        #                             and compare its avg temperature
        # if date is other than those two just add the temperature to current year

        if date[4:] == "0101":  # Jan 1
            totalTemper = dayTemper
            noOfDays = 1
            continue

        if date[4:] == "1231":  # Dec 31
            if noOfDays < 365:
                continue    # skip incomplete years

            avgTemper = totalTemper / noOfDays
            if avgTemper < minTemper:
                minTemper = avgTemper
                print( "min avg in year", date[0:4], "is ", minTemper/10, "degrees" )
            continue

        # remaining other days
        totalTemper += dayTemper
        noOfDays += 1

    file.close()


path ="d:\\Iskola\\PGE2019\\data\\"
#fname = "TG_STAID000169.txt"
fname = "TG_STAID000027.txt"

coldestYear( path + fname )

