stream_gribapi.c 99.7 KB
Newer Older
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1
2
3
4
#if defined (HAVE_CONFIG_H)
#  include "config.h"
#endif

5
#if  defined  (HAVE_LIBGRIB_API)
6
#include <limits.h>
Uwe Schulzweida's avatar
Uwe Schulzweida committed
7
8
#include <stdio.h>

Uwe Schulzweida's avatar
Uwe Schulzweida committed
9
#include "dmemory.h"
Uwe Schulzweida's avatar
Uwe Schulzweida committed
10
#include "cdi.h"
11
#include "cdi_int.h"
Uwe Schulzweida's avatar
Uwe Schulzweida committed
12
#include "file.h"
13
14
#include "gribapi_utilities.h"
#include "stream_grb.h"
15
#include "stream_gribapi.h"
Uwe Schulzweida's avatar
Uwe Schulzweida committed
16
17
18
#include "varscan.h"
#include "datetime.h"
#include "vlist.h"
Uwe Schulzweida's avatar
Uwe Schulzweida committed
19
#include "stream_grb.h"
20
#include "calendar.h"
21
#include "subtype.h"
Uwe Schulzweida's avatar
Uwe Schulzweida committed
22
23


24
25
#include "cgribex.h"      /* gribGetSize, gribRead, gribGetZip, GRIB1_LTYPE_99 */
#include "gribapi.h"
26

27
#include <grib_api.h>
Uwe Schulzweida's avatar
Uwe Schulzweida committed
28
29
30

extern int cdiInventoryMode;

31
static const var_tile_t dummy_tiles = { 0, -1, -1, -1, -1, -1 };
32

Uwe Schulzweida's avatar
Uwe Schulzweida committed
33
typedef struct {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
34
  int param;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
35
36
37
  int level1;
  int level2;
  int ltype;
38
  int tsteptype;
39
40
41
42
43
44
45
46
#ifdef HIRLAM_EXTENSIONS
    // NOTE: tsteptype MUST be part of attributes used to compare variables!
    // Modern NWP models (HARMONIE, HIRLAM) use timeRangeIndicator to specify
    // if the field is instantanous or accumulated.
    // Both types are typically in the same GRIB-file.
    // (181; 105, 0, timeRangeIndicator=0) .. instantanous rain
    // (181; 105, 0, timeRangeIndicator=4) .. accumulated rain  .. both can be in the same grib file
#endif // HIRLAM_EXTENSIONS
47
  char name[32];
48
49
50

  var_tile_t tiles;

51
} compvar2_t;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
52
53


54
55
56
int scanModeIN; // global variable


Uwe Schulzweida's avatar
Uwe Schulzweida committed
57
static
58
int gribapiGetZaxisType(long editionNumber, int grib_ltype)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
59
{
Uwe Schulzweida's avatar
Uwe Schulzweida committed
60
61
62
  int zaxistype = ZAXIS_GENERIC;

  if ( editionNumber <= 1 )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
63
    {
64
      zaxistype = grib1ltypeToZaxisType(grib_ltype);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
65
66
67
    }
  else
    {
68
      zaxistype = grib2ltypeToZaxisType(grib_ltype);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
69
70
    }

71
  return zaxistype;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
72
73
}

74
static
75
int getTimeunits(long unitsOfTime)
76
77
{
  int timeunits = -1;
78
79
80
81
82
83
84
85
86
87
88
89
90

  switch (unitsOfTime)
    {
    case 13:  timeunits = TUNIT_SECOND;  break;
    case  0:  timeunits = TUNIT_MINUTE;  break;
    case  1:  timeunits = TUNIT_HOUR;    break;
    case 10:  timeunits = TUNIT_3HOURS;  break;
    case 11:  timeunits = TUNIT_6HOURS;  break;
    case 12:  timeunits = TUNIT_12HOURS; break;
    case  2:  timeunits = TUNIT_DAY;     break;
    default:  timeunits = TUNIT_HOUR;    break;
    }

91
  return timeunits;
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
}

static
double timeunit_factor(int tu1, int tu2)
{
  double factor = 1;

  if ( tu2 == TUNIT_HOUR )
    {
      switch (tu1)
        {
        case TUNIT_SECOND:  factor = 3600;   break;
        case TUNIT_MINUTE:  factor = 60;     break;
        case TUNIT_HOUR:    factor = 1;      break;
        case TUNIT_3HOURS:  factor = 1./3;   break;
        case TUNIT_6HOURS:  factor = 1./6;   break;
        case TUNIT_12HOURS: factor = 1./12;  break;
        case TUNIT_DAY:     factor = 1./24;  break;
        }
    }

113
  return factor;
114
115
116
117
118
119
}

static
int gribapiGetTimeUnits(grib_handle *gh)
{
  int timeunits = -1;
120
  long unitsOfTime = -1;
121

122
  grib_get_long(gh, "indicatorOfUnitOfTimeRange", &unitsOfTime);
123

124
  GRIB_CHECK(my_grib_set_long(gh, "stepUnits", unitsOfTime), 0);
125

126
  timeunits = getTimeunits(unitsOfTime);
127

128
  return timeunits;
129
130
}

131
static
132
void gribapiGetSteps(grib_handle *gh, int timeunits, int *startStep, int *endStep)
133
{
134
  int timeunits2 = timeunits;
135
136
  long unitsOfTime;
  int status = grib_get_long(gh, "stepUnits", &unitsOfTime);
137
138
  if ( status == 0 ) timeunits2 = getTimeunits(unitsOfTime);
  //timeunits2 = gribapiGetTimeUnits(gh);
139

140
  long lpar;
141
142
143
144
145
146
147
148
  status = grib_get_long(gh, "forecastTime", &lpar);
  if ( status == 0 ) *startStep = (int) lpar;
  else
    {
      status = grib_get_long(gh, "startStep", &lpar);
      if ( status == 0 )
        *startStep = (int) (((double)lpar * timeunit_factor(timeunits, timeunits2)) + 0.5);
    }
149

150
151
  *endStep = *startStep;
  status = grib_get_long(gh, "endStep", &lpar);
152
  if ( status == 0 )
153
154
    *endStep = (int) (((double)lpar * timeunit_factor(timeunits, timeunits2)) + 0.5);
  // printf("%d %d %d %d %d %g\n", *startStep, *endStep, lpar, timeunits, timeunits2, timeunit_factor(timeunits, timeunits2));
155
156
}

157
158
159
160
161
162
163
static
void gribapiGetDataDateTime(grib_handle *gh, int *datadate, int *datatime)
{
  long lpar;

  GRIB_CHECK(grib_get_long(gh, "dataDate", &lpar), 0);
  *datadate = (int) lpar;
164
  GRIB_CHECK(grib_get_long(gh, "dataTime", &lpar), 0);  //FIXME: This looses the seconds in GRIB2 files.
165
166
167
  *datatime = (int) lpar*100;
}

168
169
170
static
void gribapiSetDataDateTime(grib_handle *gh, int datadate, int datatime)
{
171
172
  GRIB_CHECK(my_grib_set_long(gh, "dataDate", datadate), 0);
  GRIB_CHECK(my_grib_set_long(gh, "dataTime", datatime/100), 0);
173
174
}

175
static
176
int gribapiGetValidityDateTime(grib_handle *gh, int *vdate, int *vtime)
177
{
178
  int rdate, rtime;
179
  int timeUnits, startStep = 0, endStep;
180
181
  int tstepRange = 0;
  int range;
182
183
  long sigofrtime = 3;

184
  if ( gribEditionNumber(gh) > 1 )
185
186
187
    {
      GRIB_CHECK(grib_get_long(gh, "significanceOfReferenceTime", &sigofrtime), 0);
    }
188
189
190
191
  else
    {
      GRIB_CHECK(grib_get_long(gh, "timeRangeIndicator", &sigofrtime), 0);
    }
192

193
  if ( sigofrtime == 3 )        //XXX: This looks like a bug to me, because timeRangeIndicator == 3 does not seem to have the same meaning as significanceOfReferenceTime == 3. I would recommend replacing this condition with `if(!gribapiTimeIsFC())`.
194
    {
195
      gribapiGetDataDateTime(gh, vdate, vtime);
196
197
198
    }
  else
    {
199
200
      gribapiGetDataDateTime(gh, &rdate, &rtime);

201
      timeUnits = gribapiGetTimeUnits(gh);
202
      gribapiGetSteps(gh, timeUnits, &startStep, &endStep);
203
204
205
206
207
208
209
210
211

      range = endStep - startStep;

      if ( range > 0 )
	{
	  if ( startStep == 0 ) tstepRange = -1;
	  else                  tstepRange =  1;
	}

212
213
214
215
      {
	static int lprint = TRUE;
	extern int grib_calendar;
	int ryear, rmonth, rday, rhour, rminute, rsecond;
216
217
218
	int julday, secofday;
	int64_t time_period = endStep;
        int64_t addsec;
219
220
221
222

	cdiDecodeDate(rdate, &ryear, &rmonth, &rday);
	cdiDecodeTime(rtime, &rhour, &rminute, &rsecond);

223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
        if ( rday > 0 )
          {
            encode_caldaysec(grib_calendar, ryear, rmonth, rday, rhour, rminute, rsecond, &julday, &secofday);

            addsec = 0;
            switch ( timeUnits )
              {
              case TUNIT_SECOND:  addsec =         time_period; break;
              case TUNIT_MINUTE:  addsec =    60 * time_period; break;
              case TUNIT_HOUR:    addsec =  3600 * time_period; break;
              case TUNIT_3HOURS:  addsec = 10800 * time_period; break;
              case TUNIT_6HOURS:  addsec = 21600 * time_period; break;
              case TUNIT_12HOURS: addsec = 43200 * time_period; break;
              case TUNIT_DAY:     addsec = 86400 * time_period; break;
              default:
                if ( lprint )
                  {
                    Warning("Time unit %d unsupported", timeUnits);
                    lprint = FALSE;
                  }
                break;
              }

            julday_add_seconds(addsec, &julday, &secofday);

            decode_caldaysec(grib_calendar, julday, secofday, &ryear, &rmonth, &rday, &rhour, &rminute, &rsecond);
          }
250

251
252
253
	*vdate = cdiEncodeDate(ryear, rmonth, rday);
	*vtime = cdiEncodeTime(rhour, rminute, rsecond);
      }
254
    }
255

256
  return tstepRange;
257
258
}

259
static
260
void grib1GetLevel(grib_handle *gh, int *leveltype, int *lbounds, int *level1, int *level2)
261
{
262
  *leveltype = 0;
263
264
265
  *lbounds   = 0;
  *level1    = 0;
  *level2    = 0;
266

267
  long lpar;
268
  if ( !grib_get_long(gh, "indicatorOfTypeOfLevel", &lpar) )       //1 byte
269
    {
270
      *leveltype = (int) lpar;
271

272
      switch (*leveltype)
273
274
275
276
	{
	case GRIB1_LTYPE_SIGMA_LAYER:
	case GRIB1_LTYPE_HYBRID_LAYER:
	case GRIB1_LTYPE_LANDDEPTH_LAYER:
277
	  { *lbounds = 1; break; }
278
	}
279

280
281
282
283
284
285
286
287
      if ( *lbounds )
	{
	  GRIB_CHECK(grib_get_long(gh, "topLevel", &lpar), 0);  //1 byte
	  *level1 = (int)lpar;
	  GRIB_CHECK(grib_get_long(gh, "bottomLevel", &lpar), 0);       //1 byte
	  *level2 = (int)lpar;
	}
      else
288
	{
289
          double dlevel;
290
	  GRIB_CHECK(grib_get_double(gh, "level", &dlevel), 0); //2 byte
291
	  if ( *leveltype == GRIB1_LTYPE_ISOBARIC ) dlevel *= 100;
292
	  if ( dlevel < -2.e9 || dlevel > 2.e9 ) dlevel = 0;
293
	  if ( *leveltype == GRIB1_LTYPE_99 || *leveltype == GRIB1_LTYPE_ISOBARIC_PA ) *leveltype = GRIB1_LTYPE_ISOBARIC;
294

295
296
297
	  *level1 = (int) dlevel;
	  *level2 = 0;
	}
298
    }
299
300
}

301
302
303
static
double grib2ScaleFactor(long factor)
{
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
  switch(factor)
    {
      case GRIB_MISSING_LONG: return 1;
      case 0: return 1;
      case 1: return 0.1;
      case 2: return 0.01;
      case 3: return 0.001;
      case 4: return 0.0001;
      case 5: return 0.00001;
      case 6: return 0.000001;
      case 7: return 0.0000001;
      case 8: return 0.00000001;
      case 9: return 0.000000001;
      default: return 0;
    }
}

static
int calcLevel(int level_sf, long factor, long level)
{
  double result = 0;
Thomas Jahns's avatar
Thomas Jahns committed
325
  if(level != GRIB_MISSING_LONG) result = (double)level*grib2ScaleFactor(factor);
326
327
  if(level_sf) result *= level_sf;
  return (int)result;
328
329
}

330
static
331
void grib2GetLevel(grib_handle *gh, int *leveltype1, int *leveltype2, int *lbounds, int *level1,
332
                   int *level2, int *level_sf, int *level_unit)
333
{
334
335
336
  int status;
  long lpar;
  long factor;
337

338
339
  *leveltype1 = 0;
  *leveltype2 = -1;
340
341
342
343
344
  *lbounds    = 0;
  *level1     = 0;
  *level2     = 0;
  *level_sf   = 0;
  *level_unit = 0;
345

346
  status = grib_get_long(gh, "typeOfFirstFixedSurface", &lpar); //1 byte
347
  if ( status == 0 )
348
    {
349
      long llevel;
350

351
      *leveltype1 = (int) lpar;
352

353
      status = grib_get_long(gh, "typeOfSecondFixedSurface", &lpar); //1 byte
354
      /* FIXME: assert(lpar >= INT_MIN && lpar <= INT_MAX) */
355
      if ( status == 0 ) *leveltype2 = (int)lpar;
356

357
      if ( *leveltype1 != 255 && *leveltype2 != 255 && *leveltype2 > 0 ) *lbounds = 1;
358
      switch(*leveltype1)
359
        {
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
          case GRIB2_LTYPE_REFERENCE:
            if(*leveltype2 == 1) *lbounds = 0;
            break;

          case GRIB2_LTYPE_LANDDEPTH:
            *level_sf = 1000;
            *level_unit = CDI_UNIT_M;
            break;

          case GRIB2_LTYPE_ISOBARIC:
            *level_sf = 1000;
            *level_unit = CDI_UNIT_PA;
            break;

          case GRIB2_LTYPE_SIGMA:
            *level_sf = 1000;
            *level_unit = 0;
            break;
378
        }
379

380
381
382
      GRIB_CHECK(grib_get_long(gh, "scaleFactorOfFirstFixedSurface", &factor), 0);      //1 byte
      GRIB_CHECK(grib_get_long(gh, "scaledValueOfFirstFixedSurface", &llevel), 0);      //4 byte
      *level1 = calcLevel(*level_sf, factor, llevel);
383

384
385
386
387
388
      if ( *lbounds )
        {
          GRIB_CHECK(grib_get_long(gh, "scaleFactorOfSecondFixedSurface", &factor), 0); //1 byte
          GRIB_CHECK(grib_get_long(gh, "scaledValueOfSecondFixedSurface", &llevel), 0); //4 byte
          *level2 = calcLevel(*level_sf, factor, llevel);
389
        }
390
391
    }
}
392

393
static
394
void gribGetLevel(grib_handle *gh, int* leveltype1, int* leveltype2, int* lbounds, int* level1, int* level2, int* level_sf, int* level_unit, var_tile_t* tiles)
395
396
397
398
399
400
401
402
403
404
405
{
  if ( gribEditionNumber(gh) <= 1 )
    {
      grib1GetLevel(gh, leveltype1, lbounds, level1, level2);
      *leveltype2 = -1;
      *level_sf = 0;
      *level_unit = 0;
    }
  else
    {
      grib2GetLevel(gh, leveltype1, leveltype2, lbounds, level1, level2, level_sf, level_unit);
406
407

      /* read in tiles attributes (if there are any) */
Thomas Jahns's avatar
Thomas Jahns committed
408
409
410
411
412
413
      tiles->tileindex = (int)gribGetLongDefault(gh, cdiSubtypeAttributeName[SUBTYPE_ATT_TILEINDEX], -1);
      tiles->totalno_of_tileattr_pairs = (int)gribGetLongDefault(gh, cdiSubtypeAttributeName[SUBTYPE_ATT_TOTALNO_OF_TILEATTR_PAIRS], -1);
      tiles->tileClassification = (int)gribGetLongDefault(gh, cdiSubtypeAttributeName[SUBTYPE_ATT_TILE_CLASSIFICATION], -1);
      tiles->numberOfTiles = (int)gribGetLongDefault(gh, cdiSubtypeAttributeName[SUBTYPE_ATT_NUMBER_OF_TILES], -1);
      tiles->numberOfAttributes = (int)gribGetLongDefault(gh, cdiSubtypeAttributeName[SUBTYPE_ATT_NUMBER_OF_ATTR], -1);
      tiles->attribute = (int)gribGetLongDefault(gh, cdiSubtypeAttributeName[SUBTYPE_ATT_TILEATTRIBUTE], -1);
414
    }
415
416
}

417
418
419
420
421
static
void gribapiGetString(grib_handle *gh, const char *key, char *string, size_t length)
{
  string[0] = 0;

422
423
424
425
426
427
  int ret = grib_get_string(gh, key, string, &length);
  if (ret != 0)
    {
      fprintf(stderr, "grib_get_string(gh, \"%s\", ...) failed!\n", key);
      GRIB_CHECK(ret, 0);
    }
428
429
430
431
  if      ( length == 8 && memcmp(string, "unknown", length) == 0 ) string[0] = 0;
  else if ( length == 2 && memcmp(string, "~", length)       == 0 ) string[0] = 0;
}

432
static
433
void gribapiAddRecord(stream_t * streamptr, int param, grib_handle *gh,
434
                      size_t recsize, off_t position, int datatype, int comptype, const char *varname,
435
                      int leveltype1, int leveltype2, int lbounds, int level1, int level2, int level_sf, int level_unit,
436
                      const var_tile_t *tiles, int lread_additional_keys)
437
438
{
  int levelID = 0;
439
  char stdname[CDI_MAX_NAME], longname[CDI_MAX_NAME], units[CDI_MAX_NAME];
440
  long ens_index = 0, ens_count = 0, ens_forecast_type = 0;
441

442
443
444
  int vlistID = streamptr->vlistID;
  int tsID    = streamptr->curTsID;
  int recID   = recordNewEntry(streamptr, tsID);
445
  record_t *record = &streamptr->tsteps[tsID].records[recID];
446

447
  int tsteptype = gribapiGetTsteptype(gh);
448
  // numavg  = ISEC1_AvgNum;
449
  int numavg = 0;
450

451
  // fprintf(stderr, "param %d %d %d %d\n", param, level1, level2, leveltype1);
452

Thomas Jahns's avatar
Thomas Jahns committed
453
454
455
456
457
458
  record->size      = recsize;
  record->position  = position;
  record->param     = param;
  record->ilevel    = level1;
  record->ilevel2   = level2;
  record->ltype     = leveltype1;
Thomas Jahns's avatar
Thomas Jahns committed
459
  record->tsteptype = (short)tsteptype;
Thomas Jahns's avatar
Thomas Jahns committed
460
  record->tiles = tiles ? *tiles : dummy_tiles;
461
462
463
464
465
466
467
468
469
470
471
472

  //FIXME: This may leave the variable name unterminated (which is the behavior that I found in the code).
  //       I don't know precisely how this field is used, so I did not change this behavior to avoid regressions,
  //       but I think that it would be better to at least add a line
  //
  //           record->varname[sizeof(record->varname) - 1] = 0;`
  //
  //       after the `strncpy()` call.
  //
  //       I would consider using strdup() (that requires POSIX-2008 compliance, though), or a similar homebrew approach.
  //       I. e. kick the fixed size array and allocate enough space, whatever that may be.
  strncpy(record->varname, varname, sizeof(record->varname));
473

474
  grid_t *grid = (grid_t *)Malloc(sizeof(*grid));
475
  gribapiGetGrid(gh, grid);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
476

Uwe Schulzweida's avatar
Uwe Schulzweida committed
477
  struct addIfNewRes gridAdded = cdiVlistAddGridIfNew(vlistID, grid, 0);
478
  int gridID = gridAdded.Id;
479
480
481
482
483
484
485
486
487
488
489
  if ( !gridAdded.isNew ) Free(grid);
  else if ( grid->projtype == CDI_PROJ_RLL )
    {
      double xpole = 0, ypole = 0, angle = 0;
      grib_get_double(gh, "latitudeOfSouthernPoleInDegrees",  &ypole);
      grib_get_double(gh, "longitudeOfSouthernPoleInDegrees", &xpole);
      grib_get_double(gh, "angleOfRotation", &angle);
      xpole =  xpole - 180;
      if ( fabs(ypole) > 0 ) ypole = -ypole; // change from south to north pole
      if ( fabs(angle) > 0 ) angle = -angle;

490
      gridDefParamRLL(gridID, xpole, ypole, angle);
491
    }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
492

493
  int zaxistype = gribapiGetZaxisType(gribEditionNumber(gh), leveltype1);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
494

495
  switch (zaxistype)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
496
    {
497
498
499
    case ZAXIS_HYBRID:
    case ZAXIS_HYBRID_HALF:
      {
500
        long lpar;
501
        GRIB_CHECK(grib_get_long(gh, "NV", &lpar), 0);
Thomas Jahns's avatar
Thomas Jahns committed
502
        /* FIXME: assert(lpar >= 0) */
Thomas Jahns's avatar
Thomas Jahns committed
503
        size_t vctsize = (size_t)lpar;
504
505
        if ( vctsize > 0 )
          {
Thomas Jahns's avatar
Thomas Jahns committed
506
507
            double *vctptr = (double *) Malloc(vctsize*sizeof(double));
            size_t dummy = vctsize;
508
            GRIB_CHECK(grib_get_double_array(gh, "pv", vctptr, &dummy), 0);
Thomas Jahns's avatar
Thomas Jahns committed
509
            varDefVCT(vctsize, vctptr);
510
            Free(vctptr);
511
512
513
514
515
          }
        break;
      }
    case ZAXIS_REFERENCE:
      {
516
        unsigned char uuid[CDI_UUID_SIZE];
517
        long lpar;
518
        GRIB_CHECK(grib_get_long(gh, "NV", &lpar), 0);
519
        if ( lpar != 6 ) fprintf(stderr, "Warning ...\n");
520
521
522
523
        GRIB_CHECK(grib_get_long(gh, "nlev", &lpar), 0);
        int nhlev = (int)lpar;
        GRIB_CHECK(grib_get_long(gh, "numberOfVGridUsed", &lpar), 0);
        int nvgrid = (int)lpar;
524
        size_t len = (size_t)CDI_UUID_SIZE;
525
526
        memset(uuid, 0, CDI_UUID_SIZE);
        GRIB_CHECK(grib_get_bytes(gh, "uuidOfVGrid", uuid, &len), 0);
527
        varDefZAxisReference(nhlev, nvgrid, uuid);
528
529
        break;
      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
530
    }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
531

532
533
  // if ( datatype > 32 ) datatype = CDI_DATATYPE_PACK32;
  if ( datatype <  0 ) datatype = CDI_DATATYPE_PACK;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
534

535
  stdname[0] = 0;
536
537
538
  longname[0] = 0;
  units[0] = 0;

539
  if ( varname[0] != 0 )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
540
    {
541
      size_t vlen = CDI_MAX_NAME;
542
      gribapiGetString(gh, "name", longname, vlen);
543
      vlen = CDI_MAX_NAME;
544
      gribapiGetString(gh, "units", units, vlen);
Thomas Jahns's avatar
Thomas Jahns committed
545
546
547
548
      vlen = CDI_MAX_NAME;
      int status = grib_get_string(gh, "cfName", stdname, &vlen);
      if ( status != 0 || vlen <= 1 || strncmp(stdname, "unknown", 7) == 0 )
        stdname[0] = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
549
    }
550
  // fprintf(stderr, "param %d name %s %s %s\n", param, name, longname, units);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
551

552
  /* add the previously read record data to the (intermediate) list of records */
553
  int tile_index = 0, varID;
554
  varAddRecord(recID, param, gridID, zaxistype, lbounds, level1, level2, level_sf, level_unit,
555
	       datatype, &varID, &levelID, tsteptype, numavg, leveltype1, leveltype2,
556
	       varname, stdname, longname, units, tiles, &tile_index);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
557

Thomas Jahns's avatar
Thomas Jahns committed
558
559
  record->varID   = (short)varID;
  record->levelID = (short)levelID;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
560

561
  varDefCompType(varID, comptype);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
562

563
564
  /*
    Get the ensemble Info from the grib-2 Tables and update the intermediate datastructure.
565
    Further update to the "vlist" is handled in the same way as for GRIB-1 by "cdi_generate_vars"
566
  */
567
  if ( grib_get_long(gh, "typeOfEnsembleForecast", &ens_forecast_type) == 0 )
568
569
570
571
572
    {
      GRIB_CHECK(grib_get_long(gh, "numberOfForecastsInEnsemble", &ens_count ), 0);
      GRIB_CHECK(grib_get_long(gh, "perturbationNumber", &ens_index ), 0);
    }

573
574
575
  if ( ens_index > 0 )
    varDefEnsembleInfo(varID, (int)ens_index, (int)ens_count, (int)ens_forecast_type);

576
  long typeOfGeneratingProcess = 0;
577
  if ( grib_get_long(gh, "typeOfGeneratingProcess", &typeOfGeneratingProcess) == 0 )
578
579
    varDefTypeOfGeneratingProcess(varID, (int) typeOfGeneratingProcess);

580
  long productDefinitionTemplate = 0;
581
  if ( grib_get_long(gh, "productDefinitionTemplateNumber", &productDefinitionTemplate) == 0 )
582
583
    varDefProductDefinitionTemplate(varID, (int) productDefinitionTemplate);

584
585
586
  long   lval;
  double dval;

587
  if (lread_additional_keys)
588
    for ( int i = 0; i < cdiNAdditionalGRIBKeys; i++ )
589
590
591
592
593
594
595
      {
        /* note: if the key is not defined, we do not throw an error! */
        if ( grib_get_long(gh, cdiAdditionalGRIBKeys[i], &lval) == 0 )
          varDefOptGribInt(varID, tile_index, lval, cdiAdditionalGRIBKeys[i]);
        if ( grib_get_double(gh, cdiAdditionalGRIBKeys[i], &dval) == 0 )
          varDefOptGribDbl(varID, tile_index, dval, cdiAdditionalGRIBKeys[i]);
      }
596

Uwe Schulzweida's avatar
Uwe Schulzweida committed
597
598
  if ( varInqInst(varID) == CDI_UNDEFID )
    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
599
600
601
      long center, subcenter;
      GRIB_CHECK(grib_get_long(gh, "centre", &center), 0);
      GRIB_CHECK(grib_get_long(gh, "subCentre", &subcenter), 0);
602
      int instID = institutInq((int)center, (int)subcenter, NULL, NULL);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
603
      if ( instID == CDI_UNDEFID )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
604
	instID = institutDef((int)center, (int)subcenter, NULL, NULL);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
605
606
607
608
609
      varDefInst(varID, instID);
    }

  if ( varInqModel(varID) == CDI_UNDEFID )
    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
610
      long processID;
611
      if ( grib_get_long(gh, "generatingProcessIdentifier", &processID) == 0 )
612
	{
613
          /* FIXME: assert(processID >= INT_MIN && processID <= INT_MAX) */
614
	  int modelID = modelInq(varInqInst(varID), (int)processID, NULL);
615
	  if ( modelID == CDI_UNDEFID )
616
	    modelID = modelDef(varInqInst(varID), (int)processID, NULL);
617
618
	  varDefModel(varID, modelID);
	}
Uwe Schulzweida's avatar
Uwe Schulzweida committed
619
620
621
622
    }

  if ( varInqTable(varID) == CDI_UNDEFID )
    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
623
      int pdis, pcat, pnum;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
624
      cdiDecodeParam(param, &pnum, &pcat, &pdis);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
625

Uwe Schulzweida's avatar
Uwe Schulzweida committed
626
627
628
      if ( pdis == 255 )
	{
	  int tabnum = pcat;
629
	  int tableID = tableInq(varInqModel(varID), tabnum, NULL);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
630
631
632
	  if ( tableID == CDI_UNDEFID )
	    tableID = tableDef(varInqModel(varID), tabnum, NULL);
	  varDefTable(varID, tableID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
633
634
635
636
637
638
639
	}
    }

  streamptr->tsteps[tsID].nallrecs++;
  streamptr->nrecs++;

  if ( CDI_Debug )
640
    Message("varID = %d  param = %d  zaxistype = %d  gridID = %d  levelID = %d",
Uwe Schulzweida's avatar
Uwe Schulzweida committed
641
	    varID, param, zaxistype, gridID, levelID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
642
}
643

644
static compvar2_t gribapiVarSet(int param, int level1, int level2, int leveltype,
645
                                int tsteptype, char *name, var_tile_t tiles_data)
646
647
{
  compvar2_t compVar;
648
649
650
  size_t maxlen = sizeof(compVar.name);
  size_t len = strlen(name);
  if ( len > maxlen ) len = maxlen;
651

652
653
654
655
656
  compVar.param     = param;
  compVar.level1    = level1;
  compVar.level2    = level2;
  compVar.ltype     = leveltype;
  compVar.tsteptype = tsteptype;
657
658
  memset(compVar.name, 0, maxlen);
  memcpy(compVar.name, name, len);
659
  compVar.tiles = tiles_data;
Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
660

661
  return compVar;
662
663
664
}

static
665
int gribapiVarCompare(compvar2_t compVar, record_t record, int flag)
666
667
{
  compvar2_t compVar0;
668
669
670
671
672
  compVar0.param     = record.param;
  compVar0.level1    = record.ilevel;
  compVar0.level2    = record.ilevel2;
  compVar0.ltype     = record.ltype;
  compVar0.tsteptype = record.tsteptype;
Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
673
  memcpy(compVar0.name, record.varname, sizeof(compVar.name));
674

675
676
677
678
679
680
  if ( flag == 0 )
    {
      if ( compVar0.tsteptype == TSTEP_INSTANT  && compVar.tsteptype == TSTEP_INSTANT3 ) compVar0.tsteptype = TSTEP_INSTANT3;
      if ( compVar0.tsteptype == TSTEP_INSTANT3 && compVar.tsteptype == TSTEP_INSTANT  ) compVar0.tsteptype = TSTEP_INSTANT;
    }

681
682
  compVar0.tiles = record.tiles;

Thomas Jahns's avatar
Thomas Jahns committed
683
  return memcmp(&compVar0, &compVar, sizeof(compvar2_t));
684
}
Uwe Schulzweida's avatar
Uwe Schulzweida committed
685

686
687
688
static
void ensureBufferSize(size_t requiredSize, size_t *curSize, void **buffer)
{
689
690
691
  if ( *curSize < requiredSize )
    {
      *curSize = requiredSize;
692
      *buffer = Realloc(*buffer, *curSize);
693
694
695
    }
}

696
static
Uwe Schulzweida's avatar
Uwe Schulzweida committed
697
grib_handle *gribapiGetDiskRepresentation(size_t recsize, size_t *buffersize, void **gribbuffer, int *outDatatype, int *outCompressionType, size_t *outUnzipsize)
698
{
699
  bool lieee = false;
700

701
  grib_handle *gh = grib_handle_new_from_message(NULL, *gribbuffer, recsize);
702
703
704
705
706
707
708
709
  if(gribEditionNumber(gh) > 1)
    {
      size_t len = 256;
      char typeOfPacking[256];

      if ( grib_get_string(gh, "packingType", typeOfPacking, &len) == 0 )
        {
          // fprintf(stderr, "packingType %d %s\n", len, typeOfPacking);
710
711
          if      ( strncmp(typeOfPacking, "grid_jpeg", len) == 0 ) *outCompressionType = CDI_COMPRESS_JPEG;
          else if ( strncmp(typeOfPacking, "grid_ccsds", len) == 0 ) *outCompressionType = CDI_COMPRESS_SZIP;
712
          else if ( strncmp(typeOfPacking, "grid_ieee", len) == 0 ) lieee = true;
713
714
715
716
        }
    }
  else
    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
717
      if( gribGetZip(recsize, *gribbuffer, outUnzipsize) > 0 )
718
        {
719
          *outCompressionType = CDI_COMPRESS_SZIP;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
720
          ensureBufferSize(*outUnzipsize + 100, buffersize, gribbuffer);
721
722
723
        }
      else
        {
724
          *outCompressionType = CDI_COMPRESS_NONE;
725
726
727
728
729
        }
    }

  if ( lieee )
    {
730
      *outDatatype = CDI_DATATYPE_FLT64;
731
732
      long precision;
      int status = grib_get_long(gh, "precision", &precision);
733
      if ( status == 0 && precision == 1 ) *outDatatype = CDI_DATATYPE_FLT32;
734
735
736
    }
  else
    {
737
      *outDatatype = CDI_DATATYPE_PACK;
738
739
740
741
742
743
744
745
746
747
748
      long bitsPerValue;
      if ( grib_get_long(gh, "bitsPerValue", &bitsPerValue) == 0 )
        {
          if ( bitsPerValue > 0 && bitsPerValue <= 32 ) *outDatatype = (int)bitsPerValue;
        }
    }
  return gh;
}

typedef enum { CHECKTIME_OK, CHECKTIME_SKIP, CHECKTIME_STOP, CHECKTIME_INCONSISTENT } checkTimeResult;
static checkTimeResult checkTime(stream_t* streamptr, compvar2_t compVar, const DateTime* verificationTime, const DateTime* expectedVTime) {
Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
749
  // First determine whether the current record exists already.
750
751
752
753
754
755
756
  int recID = 0;
  for ( ; recID < streamptr->nrecs; recID++ )
    {
      if ( gribapiVarCompare(compVar, streamptr->tsteps[0].records[recID], 1) == 0 ) break;
    }
  int recordExists = recID < streamptr->nrecs;

Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
757
  // Then we need to know whether the verification time is consistent.
758
759
  int consistentTime = !memcmp(verificationTime, expectedVTime, sizeof(*verificationTime));

Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
760
  // Finally, we make a decision.
761
762
763
764
765
766
767
768
769
770
  if ( cdiInventoryMode == 1 )
    {
      if ( recordExists ) return CHECKTIME_STOP;
      if ( !consistentTime ) return CHECKTIME_INCONSISTENT;
    }
  else
    {
      if ( !consistentTime ) return CHECKTIME_STOP;
      if ( recordExists ) return CHECKTIME_SKIP;
    }
Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
771

772
773
774
775
776
777
778
779
780
781
  return CHECKTIME_OK;
}

#define gribWarning(text, nrecs, timestep, varname, param, level1, level2) do \
  { \
    char paramstr[32]; \
    cdiParamToString(param, paramstr, sizeof(paramstr)); \
    Warning("Record %2d (name=%s id=%s lev1=%d lev2=%d) timestep %d: %s", nrecs, varname, paramstr, level1, level2, timestep, text); \
  } \
while(0)
782

783
int gribapiScanTimestep1(stream_t * streamptr)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
784
785
{
  off_t recpos = 0;
786
  void *gribbuffer = NULL;
787
  size_t buffersize = 0;
788
789
  DateTime datetime0 = { .date = 10101, .time = 0 };
  int nrecs_scanned = 0;        //Only used for debug output.
Uwe Schulzweida's avatar
Uwe Schulzweida committed
790
  int warn_time = TRUE;
791
  // int warn_numavg = TRUE;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
792
793
794
795
796
  int rdate = 0, rtime = 0, tunit = 0, fcast = 0;
  grib_handle *gh = NULL;

  streamptr->curTsID = 0;

797
798
  int tsID  = tstepsNewEntry(streamptr);
  taxis_t *taxis = &streamptr->tsteps[tsID].taxis;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
799
800

  if ( tsID != 0 )
801
    Error("Internal problem! tstepsNewEntry returns %d", tsID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
802

803
  int fileID = streamptr->fileID;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
804

Thomas Jahns's avatar
Thomas Jahns committed
805
  unsigned nrecs = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
806
807
  while ( TRUE )
    {
808
      int level1 = 0, level2 = 0;
809
810
      size_t recsize = gribGetSize(fileID);
      recpos = fileGetPos(fileID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
811
812

      if ( recsize == 0 )
813
814
815
816
817
        {
          streamptr->ntsteps = 1;
          break;
        }
      ensureBufferSize(recsize, &buffersize, &gribbuffer);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
818

819
      size_t readsize = recsize;
820
      int rstatus = gribRead(fileID, gribbuffer, &readsize); //Search for next 'GRIB', read the following record, and position file offset after it.
Uwe Schulzweida's avatar
Uwe Schulzweida committed
821
      if ( rstatus ) break;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
822

823
      int datatype, comptype = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
824
      size_t unzipsize;
825
      gh = gribapiGetDiskRepresentation(recsize, &buffersize, &gribbuffer, &datatype, &comptype, &unzipsize);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
826

827
      nrecs_scanned++;
828
      GRIB_CHECK(my_grib_set_double(gh, "missingValue", cdiDefaultMissval), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
829

830
831
      int param = gribapiGetParam(gh);
      int leveltype1 = -1, leveltype2 = -1, lbounds, level_sf, level_unit;
832
      var_tile_t tiles = dummy_tiles;
833
      gribGetLevel(gh, &leveltype1, &leveltype2, &lbounds, &level1, &level2, &level_sf, &level_unit, &tiles);
834

835
      char varname[256];
836
837
      varname[0] = 0;
      gribapiGetString(gh, "shortName", varname, sizeof(varname));
838

839
      int tsteptype = gribapiGetTsteptype(gh);
Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
840

841
      int vdate = 0, vtime = 0;
842
      gribapiGetValidityDateTime(gh, &vdate, &vtime);
843
      DateTime datetime = { .date = vdate, .time = vtime };
844
      /*
845
      printf("%d %d %d\n", vdate, vtime, leveltype1);
846
      */
847

Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
848
      if ( datetime0.date == 10101 && datetime0.time == 0 )
849
        {
850
          if( datetimeCmp(datetime, datetime0) || !nrecs )       //Do we really need this condition? I have included it in order not to change the number of times gribapiGetDataDateTime() etc. get called. But if those are sideeffect-free, this condition should be removed.
851
852
853
854
855
856
857
858
            {
              datetime0 = datetime;

              gribapiGetDataDateTime(gh, &rdate, &rtime);

              fcast = gribapiTimeIsFC(gh);
              if ( fcast ) tunit = gribapiGetTimeUnits(gh);
            }
859
        }
860

Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
861
      if ( nrecs )
862
        {
863
          checkTimeResult result = checkTime(streamptr, gribapiVarSet(param, level1, level2, leveltype1, tsteptype, varname, tiles), &datetime, &datetime0);
Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
864
          if ( result == CHECKTIME_STOP )
865
            {
866
              break;
867
            }
Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
868
          else if ( result == CHECKTIME_SKIP )
869
            {
870
871
              gribWarning("Parameter already exist, skipped!", nrecs_scanned, tsID+1, varname, param, level1, level2);
              continue;
872
            }
Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
873
          else if ( result == CHECKTIME_INCONSISTENT && warn_time )
874
875
876
877
878
            {
              gribWarning("Inconsistent verification time!", nrecs_scanned, tsID+1, varname, param, level1, level2);
              warn_time = FALSE;
            }
          assert(result == CHECKTIME_OK || result == CHECKTIME_INCONSISTENT);
879
        }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
880
881
      /*
      if ( ISEC1_AvgNum )
882
883
884
885
886
887
888
889
890
891
892
893
        {
          if (  taxis->numavg && warn_numavg && (taxis->numavg != ISEC1_AvgNum) )
            {
              Message("Change numavg from %d to %d not allowed!",
                      taxis->numavg, ISEC1_AvgNum);
              warn_numavg = FALSE;
            }
          else
            {
              taxis->numavg = ISEC1_AvgNum;
            }
        }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
894
895
896
897
      */
      nrecs++;

      if ( CDI_Debug )
898
899
900
        {
          char paramstr[32];
          cdiParamToString(param, paramstr, sizeof(paramstr));
Thomas Jahns's avatar
Thomas Jahns committed
901
          Message("%4u %8d name=%s id=%s ltype=%d lev1=%d lev2=%d vdate=%d vtime=%d",
902
                nrecs, (int)recpos, varname, paramstr, leveltype1, level1, level2, vdate, vtime);