import pygrib, sys
pygrib.tolerate_badgrib_on()
if len(sys.argv) < 2:
    sys.stdout.write("'grib_list <grib_filename>' to get long listing\n")
    sys.stdout.write("'grib_list <grib_filename> -s' to get short listing\n")
    sys.stdout.write("'grib_list <grib_filename> -m' to get short listing plus data min/max\n")
    sys.exit(1)
fname = sys.argv[1]
short = False
medium = False
if len(sys.argv) > 2:
    if sys.argv[2] == '-s': short=True
    if sys.argv[2] == '-m': medium=True
grbs = pygrib.open(fname)
if short:
    for grb in grbs:
        sys.stdout.write(repr(grb)+'\n')
elif medium:
    for grb in grbs:
        try:
            grb.expand_grid(False); data = grb.values
            sys.stdout.write(repr(grb)+':min/max=%g/%g'%(data.min(), data.max())+'\n')
        except:
            sys.stdout.write(repr(grb)+':min/max=NO DATA'+'\n')
else:
    for grb in grbs:
        sys.stdout.write('------message %d------\n' % grb.messagenumber)
        for k in grb.keys():
            if k.startswith('mars'): continue
            if k in ['values','codedValues','packedValues','unpackedValues']: continue
            if grb.is_missing(k) and k not in ['analDate','validDate']:
                sys.stdout.write('%s = MISSING\n' % k)
            else:
                try:
                    v = getattr(grb,k)
                    sys.stdout.write('%s = %s\n'%(k,v))
                except:
                    sys.stdout.write('%s = NOT FOUND\n'%k)
sys.stdout.write('packing = %s\n' % grb.packingType)
grbs.close()
