# -------------------------------------------------------------
# Problem:
# We are given a text file containing
# daily measurements of outdoor temperatures
# on a particular meteorological stations.
# Find the coldest day 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 coldestDay 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 coldestDay( fileName ):
    # named constants do help
    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

    # 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]
        temper = int( lineVals[temperColumn] )
        quality = int( lineVals[qualityColumn] )

        # do not accept dubious data
        if quality != qualityValid:
            continue

        # just for amusement, temper/10 gives correct value in degrees Celsius
        if temper <= -200:
            print( " cold!", temper/10, date, getDate( date ) )

        if temper <= minTemper:
            minTemper = temper
            dateMinTemper = date
            print( temper, date )

    file.close()
    print("The lowest temperature ", minTemper/10, " was on ", \
          getDate( dateMinTemper ), ".", sep = "'" )
    #end of coldestDay




path ="d:\\Iskola\\PGE2019\\data\\"
fname = "TG_STAID000169.txt"
# fname = "TG_STAID000027.txt"

coldestDay( path + fname )
