import pygrib, sys

if len(sys.argv) < 3:
    sys.stdout.write("""
cnvgrib2to1 <grib2 filename> <grib1 filename>\n\n""")
    raise SystemExit
   
grbs = pygrib.open(sys.argv[1])
f = open(sys.argv[2],'wb')

sys.stdout.write('converting %s from grib2 to grib1 (%s) ...\n' % (sys.argv[1],sys.argv[2]))

nmsg = 0
for grb in grbs:
    try:
        grb.editionNumber=1 
        nmsg = nmsg + 1
    except:
        sys.stdout.write('cannot convert message %s\n' % grb.messagenumber)
        continue
    f.write(grb.tostring())

sys.stdout.write('%s messages out of %s converted\n' % (nmsg,grbs.messages))
grbs.close()
f.close()
