# Metview Macro

lat = 32.7
lon = -82

# read the original data file with accumulated precipitation
precip = read("precip.grib")

# compute the 'period' precipitation - the difference between steps
n = count(precip) # the number of fields in the fieldset
precip_diff = precip[2, n] - precip[1, n-1]
precip_diff = precip_diff+0

# extract the dates and times from the original fields and put into a list
dates = nil
for i = 1 to n do
    d  = grib_get_long(precip[i], 'validityDate')
    t  = grib_get_long(precip[i], 'validityTime') # ASSUME it's going to be in hours
    dt = date(d) + hour(t/100)
    dates = dates & [dt]
end for

# compute the differences between the valid times
date_diffs          = dates[2, n] - dates[1, n-1]
date_diffs_in_hours = date_diffs*24

print('Date differences in hours: ', date_diffs_in_hours)

# extract the values for the given point
vals = nearest_gridpoint(precip_diff, lat, lon)
vals = vals * 1000 # remember to scale up from m to mm!
print('Point values: ', vals)

# compute precipitation rate in mm/h
precip_rates_per_hour = vals / (date_diffs_in_hours)
print("Precipitation per hour: ", precip_rates_per_hour)
