#!/usr/bin/env python3

# This is an example of creating a summary of TMAX for several files.
#
# input: b.f006 .. b.f042
#
# output: text with fraction grid points with TMAX > 20C
# output: text with fraction area with TMAX > 20C (approximate)
#

import pywgrib2_s
import numpy
import math

# make a list of files to process


# files = ['b.f006', 'b.f012', 'b.f018', 'b.f024', 'b.f030', 'b.f036', 'b.f042']
files = []
for fhr in range(6, 43, 6):
    file = "b.f" "%03d" % fhr
    files.append(file)

print("list of files:", files)

# process the list of files

for file in files:
    # read TMAX
    nmatch = pywgrib2_s.inq(file,var="TMAX",Data=True, Latlon=True)
    # nmatch == 0 then not found, nmatch > 1 then found more than 1 TMAX, need to be more specific
    if nmatch == 1:
        count = 0
        wt = 0.0
        countwt = 0.0
        for j in range(pywgrib2_s.ny):
            coslat = math.cos(math.radians(pywgrib2_s.lat[0,j]))
#            print("j,lat,coslat=", j, pywgrib2_s.lat[0,j], coslat)
            for i in range(pywgrib2_s.nx):
                if pywgrib2_s.data[i,j] > 273.15 + 20.0:
                    count += 1
                    countwt += coslat
            wt += pywgrib2_s.nx * coslat
        print(file, "   fraction grid points TMAX above 20C=", float(count)/pywgrib2_s.nx/pywgrib2_s.ny)
        print(file, "   fraction area TMAX above 20C=", countwt/wt)


print("done")