#!/usr/bin/env python3

# this version uses wgrib2 to regrid the files to a set of  lat/lon points
# see  https://www.cpc.ncep.noaa.gov/products/wesley/wgrib2/new_grid.html
# for more details
#
# wgrib2 -new_grid can interpolate to a list of locations
#  (default: bilinear interpolation)
#
# interpolate mean sea level pressure to 3 grid points and save as grib file
# and make csv file

import pywgrib2_s
import os.path
in_file='a.grb'
in_file_ordered='a_order.grb'
in_file_reject='a_missing.grb'
out='a_regrid_2.grb'
out_csv='a_regrid_2.csv'
UID='0'


# make sure file is order for -new_grid
if not os.path.isfile(in_file_ordered) :
  err=pywgrib2_s.wgrib2([in_file,'-new_grid_order',in_file_ordered,in_file_reject,'-inv','/dev/null'])
  print("put file in order for -new_grid err=", err)

# values for lon[i] and lat[i]
lon = [ 10.1, 20.2, 350.9 ]
lat = [ -1.9, 22.2, -33.3 ]

# make list of locations
for i in range(len(lon)):
  if i == 0:
    loc=str(lon[0]) + ":" + str(lat[0])
  else:
    loc=loc + ':' + str(lon[i]) + ":" + str(lat[i])

print(loc)

#pywgrib2_s.debug=True
err = pywgrib2_s.wgrib2( [in_file_ordered, '-rewind_init', in_file_ordered, '-new_grid_winds', 'earth',
   '-match', ':PRATE:surface:', '-set_grib_type' , 'c3', '-new_grid', 'location', loc,  UID, out] )
print("regrid err=", err)

# out has lat/lon in first two grib messages, use -grid_def to define lat/lon for following grib messages
# make a csv file, ignore first and second fields
err = pywgrib2_s.wgrib2([ out, '-grid_def', '-not_if', '(^(1|2):)', '-csv', out_csv, '-endif' ])
print('make csv error=', err)