stream_cgribex.c 61 KB
Newer Older
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1
2
#if HAVE_CONFIG_H
#include "config.h"
Uwe Schulzweida's avatar
Uwe Schulzweida committed
3
4
#endif

5
#include <limits.h>
Uwe Schulzweida's avatar
Uwe Schulzweida committed
6
7
8
9
#include <stdio.h>

#include "dmemory.h"
#include "cdi.h"
10
#include "cdi_int.h"
Uwe Schulzweida's avatar
Uwe Schulzweida committed
11
12
13
#include "file.h"
#include "varscan.h"
#include "datetime.h"
14
#include "stream_scan.h"
Uwe Schulzweida's avatar
Uwe Schulzweida committed
15
#include "stream_grb.h"
16
#include "stream_cgribex.h"
Uwe Schulzweida's avatar
Uwe Schulzweida committed
17

18
#ifdef HAVE_LIBCGRIBEX
19

Uwe Schulzweida's avatar
Uwe Schulzweida committed
20
#include "cgribex.h"
21
22
23
24
25
26
27
28
29


typedef struct {
  int       sec0[2];
  int       sec1[1024];
  size_t    sec2len;
  int      *sec2;
  int       sec3[2];
  int       sec4[512];
30
31
  double   fsec2[512];
  double   fsec3[2];
32
33
34
}
cgribexrec_t;

Uwe Schulzweida's avatar
Uwe Schulzweida committed
35
36

typedef struct {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
37
  int param;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
38
39
40
  int level1;
  int level2;
  int ltype;
41
  int tsteptype;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
42
} compvar_t;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
43
44


45
46
47
48
49
50
51
52
53
54
55
typedef struct
{
  void *gribbuffer;
  size_t gribbuffersize;
  unsigned char *pds;
  unsigned char *gds;
  unsigned char *bms;
  unsigned char *bds;
} cgribex_handle;


56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

static
void cgribexInit(cgribexrec_t *cgribexp)
{
  cgribexp->sec2len = 4096;
  cgribexp->sec2 = (int *) Malloc(cgribexp->sec2len*sizeof(int));
}


void *cgribexNew()
{
  cgribexrec_t *cgribexp = (cgribexrec_t *) Malloc(sizeof(cgribexrec_t));
  cgribexInit(cgribexp);
  return (void*)cgribexp;
}


void cgribexDelete(void *cgribex)
{
  cgribexrec_t *cgribexp = (cgribexrec_t *) cgribex;
  if (cgribexp)
    {
      if (cgribexp->sec2) Free(cgribexp->sec2);
      Free(cgribexp);
    }
}


84
85
86
int grib1Sections(unsigned char *gribbuffer, long gribbufsize, unsigned char **pdsp,
		  unsigned char **gdsp, unsigned char **bmsp, unsigned char **bdsp, long *gribrecsize);

87
size_t cgribexSection2Length(void *gribbuffer, size_t gribbuffersize)
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
{
  long sec2len = 0;

  if ( gribbuffersize && gribbuffer )
    {
      unsigned char *pds = NULL, *gds = NULL, *bms = NULL, *bds = NULL;
      long gribrecsize;
      int status = grib1Sections((unsigned char *)gribbuffer, (long)gribbuffersize, &pds, &gds, &bms, &bds, &gribrecsize);
      if (status >= 0 && gds != NULL) sec2len = (unsigned) ((gds[0] << 16) + (gds[1] << 8)  + (gds[3]));
    }

  return sec2len;
}


void *cgribex_handle_new_from_meassage(void *gribbuffer, size_t gribbuffersize)
{
  cgribex_handle *gh = (cgribex_handle*) Malloc(sizeof(cgribex_handle));
  gh->gribbuffer = NULL;
  gh->gribbuffersize = 0;
  gh->pds = NULL;

110
  if (gribbuffersize && gribbuffer)
111
112
113
114
    {
      unsigned char *pds = NULL, *gds = NULL, *bms = NULL, *bds = NULL;
      long gribrecsize;
      int status = grib1Sections((unsigned char *)gribbuffer, (long)gribbuffersize, &pds, &gds, &bms, &bds, &gribrecsize);
115
      if (status >= 0)
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
        {
          gh->gribbuffer = gribbuffer;
          gh->gribbuffersize = gribbuffersize;
          gh->pds = pds;
          gh->gds = gds;
          gh->bms = bms;
          gh->bds = bds;
        }
    }

  return (void*)gh;
}


void cgribex_handle_delete(void *gh)
{
132
  if (gh) Free(gh);
133
134
}

Uwe Schulzweida's avatar
Uwe Schulzweida committed
135
static
Uwe Schulzweida's avatar
Uwe Schulzweida committed
136
int cgribexGetGridType(int *isec2)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
137
{
138
  int gridtype = GRID_GENERIC;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
139

140
  // clang-format off
Uwe Schulzweida's avatar
Uwe Schulzweida committed
141
142
  switch (ISEC2_GridType)
    {
143
    case  GRIB1_GTYPE_LATLON:     { gridtype = GRID_LONLAT;     break; }
144
    case  GRIB1_GTYPE_LATLON_ROT: { gridtype = GRID_PROJECTION; break; }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
145
    case  GRIB1_GTYPE_LCC:        { gridtype = CDI_PROJ_LCC;    break; }
146
    case  GRIB1_GTYPE_GAUSSIAN:   { gridtype = ISEC2_Reduced ? GRID_GAUSSIAN_REDUCED : GRID_GAUSSIAN; break; }
147
148
    case  GRIB1_GTYPE_SPECTRAL:   { gridtype = GRID_SPECTRAL;   break; }
    case  GRIB1_GTYPE_GME:        { gridtype = GRID_GME;        break; }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
149
    }
150
  // clang-format on
Uwe Schulzweida's avatar
Uwe Schulzweida committed
151

Uwe Schulzweida's avatar
Uwe Schulzweida committed
152
  return gridtype;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
153
154
}

Uwe Schulzweida's avatar
Uwe Schulzweida committed
155
static
156
bool cgribexGetIsRotated(int *isec2)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
157
{
158
  return (ISEC2_GridType == GRIB1_GTYPE_LATLON_ROT);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
159
160
}

Uwe Schulzweida's avatar
Uwe Schulzweida committed
161
static
162
bool cgribexGetZaxisHasBounds(int grb_ltype)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
163
{
164
  // clang-format off
165
  switch (grb_ltype)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
166
    {
167
    case GRIB1_LTYPE_SIGMA_LAYER:
Uwe Schulzweida's avatar
Uwe Schulzweida committed
168
    case GRIB1_LTYPE_HYBRID_LAYER:
169
    case GRIB1_LTYPE_LANDDEPTH_LAYER: return true;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
170
    }
171
  // clang-format on
Uwe Schulzweida's avatar
Uwe Schulzweida committed
172

173
  return false;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
174
175
}

Uwe Schulzweida's avatar
Uwe Schulzweida committed
176
static
Uwe Schulzweida's avatar
Uwe Schulzweida committed
177
int cgribexGetTimeUnit(int *isec1)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
178
{
179
  int timeunit = TUNIT_HOUR;
180
  static bool lprint = true;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
181

182
  // clang-format off
Uwe Schulzweida's avatar
Uwe Schulzweida committed
183
184
  switch ( ISEC1_TimeUnit )
    {
185
186
187
188
189
190
191
192
    case ISEC1_TABLE4_MINUTE:    timeunit = TUNIT_MINUTE;    break;
    case ISEC1_TABLE4_QUARTER:   timeunit = TUNIT_QUARTER;   break;
    case ISEC1_TABLE4_30MINUTES: timeunit = TUNIT_30MINUTES; break;
    case ISEC1_TABLE4_HOUR:      timeunit = TUNIT_HOUR;      break;
    case ISEC1_TABLE4_3HOURS:    timeunit = TUNIT_3HOURS;    break;
    case ISEC1_TABLE4_6HOURS:    timeunit = TUNIT_6HOURS;    break;
    case ISEC1_TABLE4_12HOURS:   timeunit = TUNIT_12HOURS;   break;
    case ISEC1_TABLE4_DAY:       timeunit = TUNIT_DAY;       break;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
193
194
195
    default:
      if ( lprint )
	{
196
	  Message("GRIB time unit %d unsupported!", ISEC1_TimeUnit);
197
	  lprint = false;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
198
	}
Uwe Schulzweida's avatar
Uwe Schulzweida committed
199
      break;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
200
    }
201
  // clang-format on
Uwe Schulzweida's avatar
Uwe Schulzweida committed
202

Uwe Schulzweida's avatar
Uwe Schulzweida committed
203
  return timeunit;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
204
205
}

206
static
207
bool cgribexTimeIsFC(int *isec1)
208
{
209
  bool isFC = (ISEC1_TimeRange == 10 && ISEC1_TimePeriod1 == 0 && ISEC1_TimePeriod2 == 0) ? false : true;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
210
  return isFC;
211
212
213
214
215
}

static
int cgribexGetTsteptype(int timerange)
{
216
  static bool lprint = true;
217

218
  // clang-format off
219
  int tsteptype = TSTEP_INSTANT;
220
221
222
223
224
225
226
227
228
229
230
231
  switch ( timerange )
    {
    case  0:  tsteptype = TSTEP_INSTANT;  break;
    case  1:  tsteptype = TSTEP_INSTANT2; break;
    case  2:  tsteptype = TSTEP_RANGE;    break;
    case  3:  tsteptype = TSTEP_AVG;      break;
    case  4:  tsteptype = TSTEP_ACCUM;    break;
    case  5:  tsteptype = TSTEP_DIFF;     break;
    case 10:  tsteptype = TSTEP_INSTANT3; break;
    default:
      if ( lprint )
	{
232
	  Message("Time range indicator %d unsupported, set to 0!", timerange);
233
	  lprint = false;
234
	}
Uwe Schulzweida's avatar
Uwe Schulzweida committed
235
      break;
236
    }
237
  // clang-format on
238

Uwe Schulzweida's avatar
Uwe Schulzweida committed
239
  return tsteptype;
240
241
}

Uwe Schulzweida's avatar
Uwe Schulzweida committed
242
static
243
bool cgribexGetGrid(stream_t *streamptr, int *isec2, int *isec4, grid_t *grid, int iret)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
244
{
245
  bool uvRelativeToGrid = false;
246
  bool compyinc = true;
247
  int gridtype = cgribexGetGridType(isec2);
248
  int projtype = (gridtype == GRID_PROJECTION && cgribexGetIsRotated(isec2)) ? CDI_PROJ_RLL : CDI_UNDEFID;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
249
  if ( gridtype == CDI_PROJ_LCC )
250
    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
251
      projtype = gridtype;
252
253
      gridtype = GRID_PROJECTION;
    }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
254

255
  if ( streamptr->unreduced && gridtype == GRID_GAUSSIAN_REDUCED && iret != -801 )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
256
    {
257
258
      int nlon = 0;
      for ( int ilat = 0; ilat < ISEC2_NumLat; ++ilat )
259
        if ( ISEC2_RowLon(ilat) > nlon ) nlon = ISEC2_RowLon(ilat);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
260
      gridtype = GRID_GAUSSIAN;
261
262
      ISEC2_NumLon = nlon;
      ISEC4_NumValues = nlon*ISEC2_NumLat;
263
      compyinc = false;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
264
265
    }

266
  grid_init(grid);
267
  cdiGridTypeInit(grid, gridtype, 0);
268

269
  if ( gridtype == GRID_LONLAT || gridtype == GRID_GAUSSIAN || projtype == CDI_PROJ_RLL )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
270
    {
271
      const bool ijDirectionIncrementGiven = gribbyte_get_bit(ISEC2_ResFlag, 1);
272
      uvRelativeToGrid = gribbyte_get_bit(ISEC2_ResFlag, 5);
273

274
275
276
      const size_t nvalues = (size_t) ISEC4_NumValues;
      const size_t nlon = (size_t) ISEC2_NumLon;
      const size_t nlat = (size_t) ISEC2_NumLat;
277
278
279
280
281
282
283
      if ( nvalues != nlon*nlat )
        Error("numberOfPoints (%zu) and gridSize (%zu) differ!", nvalues, nlon*nlat);

      grid->size   = nvalues;
      grid->x.size = nlon;
      grid->y.size = nlat;

284
285
286
287
288
      if ( gridtype == GRID_GAUSSIAN ) grid->np = ISEC2_NumPar;
      grid->x.inc  = 0;
      grid->y.inc  = 0;
      grid->x.flag = 0;
      /* if ( ISEC2_FirstLon != 0 || ISEC2_LastLon != 0 ) */
Uwe Schulzweida's avatar
Uwe Schulzweida committed
289
      {
290
291
292
        if ( grid->x.size > 1 )
          {
            bool recompinc = true;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
293

294
295
296
297
298
299
300
            if ( ISEC2_LastLon < ISEC2_FirstLon )
              {
                if ( ISEC2_FirstLon >= 180000 )
                  ISEC2_FirstLon -= 360000;
                else
                  ISEC2_LastLon += 360000;
              }
301

302
            if ( ijDirectionIncrementGiven && ISEC2_LonIncr > 0 )
303
              {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
304
                if ( labs(ISEC2_LastLon - (ISEC2_FirstLon+ISEC2_LonIncr*((long)grid->x.size-1))) <= 2 )
305
                  {
306
307
                    recompinc = false;
                    grid->x.inc = ISEC2_LonIncr * 0.001;
308
                  }
309
              }
310

311
312
            /* recompute xinc if necessary */
            if ( recompinc ) grid->x.inc = (ISEC2_LastLon - ISEC2_FirstLon) * 0.001 / (grid->x.size-1);
313

314
315
316
317
318
319
320
321
322
323
324
325
326
327
            /* correct xinc if necessary */
            if ( ISEC2_FirstLon == 0 && ISEC2_LastLon > 354000 && ISEC2_LastLon < 360000 )
              {
                double xinc = 360. / grid->x.size;
                if ( fabs(grid->x.inc-xinc) > 0.0 )
                  {
                    grid->x.inc = xinc;
                    if ( CDI_Debug ) Message("set xinc to %g", grid->x.inc);
                  }
              }
          }
        grid->x.first = ISEC2_FirstLon * 0.001;
        grid->x.last  = ISEC2_LastLon  * 0.001;
        grid->x.flag  = 2;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
328
      }
329
330
      grid->y.flag = 0;
      /* if ( ISEC2_FirstLat != 0 || ISEC2_LastLat != 0 ) */
Uwe Schulzweida's avatar
Uwe Schulzweida committed
331
      {
332
333
334
        if ( grid->y.size > 1 && compyinc )
          {
            bool recompinc = true;
335
            if ( ijDirectionIncrementGiven && ISEC2_LatIncr > 0 )
336
              {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
337
                if ( labs(ISEC2_LastLat - (ISEC2_FirstLat+ISEC2_LatIncr*((long)grid->y.size-1))) <= 2 )
338
339
340
341
342
343
344
345
346
347
348
349
                  {
                    recompinc = false;
                    grid->y.inc = ISEC2_LatIncr * 0.001;
                  }
              }

            /* recompute yinc if necessary */
            if ( recompinc ) grid->y.inc = (ISEC2_LastLat - ISEC2_FirstLat) * 0.001 / (grid->y.size - 1);
          }
        grid->y.first = ISEC2_FirstLat * 0.001;
        grid->y.last  = ISEC2_LastLat  * 0.001;
        grid->y.flag  = 2;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
350
      }
351
352
353
    }
  else if ( gridtype == GRID_GAUSSIAN_REDUCED )
    {
354
      const bool ijDirectionIncrementGiven = gribbyte_get_bit(ISEC2_ResFlag, 1);
355
      uvRelativeToGrid = gribbyte_get_bit(ISEC2_ResFlag, 5);
356
      grid->np      = ISEC2_NumPar;
357
      grid->size    = (size_t)ISEC4_NumValues;
358
      grid->rowlon  = ISEC2_RowLonPtr;
359
      grid->reducedPointsSize = (size_t)ISEC2_NumLat;
360
      grid->y.size  = (size_t)ISEC2_NumLat;
361
362
363
364
      grid->x.inc   = 0;
      grid->y.inc   = 0;
      grid->x.flag  = 0;
      /* if ( ISEC2_FirstLon != 0 || ISEC2_LastLon != 0 ) */
Uwe Schulzweida's avatar
Uwe Schulzweida committed
365
      {
366
367
368
369
        if ( grid->x.size > 1 )
          {
            if ( ISEC2_LastLon < ISEC2_FirstLon && ISEC2_LastLon < 0 ) ISEC2_LastLon += 360000;

370
            if ( ijDirectionIncrementGiven && ISEC2_LonIncr > 0 )
371
372
373
374
375
376
377
              grid->x.inc = ISEC2_LonIncr * 0.001;
            else
              grid->x.inc = (ISEC2_LastLon - ISEC2_FirstLon) * 0.001 / (grid->x.size - 1);
          }
        grid->x.first = ISEC2_FirstLon * 0.001;
        grid->x.last  = ISEC2_LastLon  * 0.001;
        grid->x.flag  = 2;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
378
      }
379
380
      grid->y.flag = 0;
      /* if ( ISEC2_FirstLat != 0 || ISEC2_LastLat != 0 ) */
Uwe Schulzweida's avatar
Uwe Schulzweida committed
381
      {
382
383
        if ( grid->y.size > 1 )
          {
384
            if ( ijDirectionIncrementGiven && ISEC2_LatIncr > 0 )
385
386
387
388
389
390
391
              grid->y.inc = ISEC2_LatIncr * 0.001;
            else
              grid->y.inc = (ISEC2_LastLat - ISEC2_FirstLat) * 0.001 / (grid->y.size - 1);
          }
        grid->y.first = ISEC2_FirstLat * 0.001;
        grid->y.last  = ISEC2_LastLat  * 0.001;
        grid->y.flag  = 2;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
392
393
      }
    }
394
  else if ( projtype == CDI_PROJ_LCC )
395
    {
396
      uvRelativeToGrid = gribbyte_get_bit(ISEC2_ResFlag, 5);
397

398
399
400
      const size_t nvalues = (size_t) ISEC4_NumValues;
      const size_t nlon = (size_t) ISEC2_NumLon;
      const size_t nlat = (size_t) ISEC2_NumLat;
401
402
      if ( nvalues != nlon*nlat )
        Error("numberOfPoints (%zu) and gridSize (%zu) differ!", nvalues, nlon*nlat);
403

404
405
406
      grid->size   = nvalues;
      grid->x.size = nlon;
      grid->y.size = nlat;
407

408
409
410
411
412
413
414
415
      grid->x.first = 0;
      grid->x.last  = 0;
      grid->x.inc   = ISEC2_Lambert_dx;
      grid->y.first = 0;
      grid->y.last  = 0;
      grid->y.inc   = ISEC2_Lambert_dy;
      grid->x.flag  = 2;
      grid->y.flag  = 2;
416
417
418
    }
  else if ( gridtype == GRID_SPECTRAL )
    {
419
      grid->size  = (size_t) ISEC4_NumValues;
420
      grid->trunc = ISEC2_PentaJ;
421
422
      grid->lcomplex = (ISEC2_RepMode == 2) ? 1 : 0;
   }
423
424
  else if ( gridtype == GRID_GME )
    {
425
      grid->size  = (size_t) ISEC4_NumValues;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
426
427
428
429
      grid->gme.nd  = ISEC2_GME_ND;
      grid->gme.ni  = ISEC2_GME_NI;
      grid->gme.ni2 = ISEC2_GME_NI2;
      grid->gme.ni3 = ISEC2_GME_NI3;
430
431
432
    }
  else if ( gridtype == GRID_GENERIC )
    {
433
      grid->size  = (size_t) ISEC4_NumValues;
434
435
436
437
438
439
440
      grid->x.size = 0;
      grid->y.size = 0;
    }
  else
    {
      Error("Unsupported grid type: %s", gridNamePtr(gridtype));
    }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
441

442
443
  grid->type = gridtype;
  grid->projtype = projtype;
444
445

  return uvRelativeToGrid;
446
447
}

Uwe Schulzweida's avatar
Uwe Schulzweida committed
448
449
450
451
452
453
454
455
456
457
static
void cgribexGetLevel(int *isec1, int *leveltype, int *level1, int *level2)
{
  *leveltype = ISEC1_LevelType;
  *level1 = ISEC1_Level1;
  *level2 = ISEC1_Level2;
  if ( *leveltype == GRIB1_LTYPE_ISOBARIC ) *level1 *= 100;
  else if ( *leveltype == GRIB1_LTYPE_99 || *leveltype == GRIB1_LTYPE_ISOBARIC_PA ) *leveltype = GRIB1_LTYPE_ISOBARIC;
}

458
static
459
void cgribexAddRecord(stream_t *streamptr, cgribexrec_t *cgribexp, int param, size_t recsize,
460
                      off_t position, int comptype, int lmv, int iret)
461
{
462
  int *isec1 = cgribexp->sec1;
463
  int *isec2 = cgribexp->sec2;
464
  int *isec4 = cgribexp->sec4;
465
466
467
  double *fsec2 = cgribexp->fsec2;
  double *fsec3 = cgribexp->fsec3;

468
  int datatype = (ISEC4_NumBits > 0 && ISEC4_NumBits <= 32) ? ISEC4_NumBits : CDI_DATATYPE_PACK;
469
470
  if ( datatype > 32 ) datatype = CDI_DATATYPE_PACK32;
  if ( datatype <  0 ) datatype = CDI_DATATYPE_PACK;
471

472
473
474
  const int vlistID = streamptr->vlistID;
  const int tsID    = streamptr->curTsID;
  const int recID   = recordNewEntry(streamptr, tsID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
475
  record_t *record = &streamptr->tsteps[tsID].records[recID];
476

477
478
  const int tsteptype = cgribexGetTsteptype(ISEC1_TimeRange);
  const int numavg    = ISEC1_AvgNum;
479

Uwe Schulzweida's avatar
Uwe Schulzweida committed
480
481
  int leveltype, level1, level2;
  cgribexGetLevel(isec1, &leveltype, &level1, &level2);
482

Uwe Schulzweida's avatar
Uwe Schulzweida committed
483
  /* fprintf(stderr, "param %d %d %d %d\n", param, level1, level2, leveltype); */
484

485
  record->size      = recsize;
486
487
488
489
  record->position  = position;
  record->param     = param;
  record->ilevel    = level1;
  record->ilevel2   = level2;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
490
  record->ltype     = leveltype;
Thomas Jahns's avatar
Thomas Jahns committed
491
  record->tsteptype = (short)tsteptype;
492

Uwe Schulzweida's avatar
Uwe Schulzweida committed
493
  grid_t *gridptr = (grid_t*) Malloc(sizeof(*gridptr));
494
  const bool uvRelativeToGrid = cgribexGetGrid(streamptr, isec2, isec4, gridptr, iret);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
495

Uwe Schulzweida's avatar
Uwe Schulzweida committed
496
  struct addIfNewRes gridAdded = cdiVlistAddGridIfNew(vlistID, gridptr, 0);
497
  int gridID = gridAdded.Id;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
498
499
  if ( gridAdded.isNew )
    {
500
      if ( gridptr->reducedPointsSize )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
501
        {
502
          const size_t reducedPointsSize = (size_t) gridptr->reducedPointsSize;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
503
          int *rowlon = gridptr->rowlon;
504
505
          gridptr->rowlon = (int*) Malloc(reducedPointsSize * sizeof(int));
          memcpy(gridptr->rowlon, rowlon, reducedPointsSize * sizeof(int));
Uwe Schulzweida's avatar
Uwe Schulzweida committed
506
        }
507
508
      else if ( gridptr->projtype == CDI_PROJ_RLL )
        {
509
510
511
          const double xpole =   ISEC2_LonSP*0.001 - 180;
          const double ypole = - ISEC2_LatSP*0.001;
          const double angle = - FSEC2_RotAngle;
512
          gridDefParamRLL(gridID, xpole, ypole, angle);
513
        }
514
515
      else if ( gridptr->projtype == CDI_PROJ_LCC )
        {
516
517
518
          const bool earthIsOblate = gribbyte_get_bit(ISEC2_ResFlag, 2);
          const double a = earthIsOblate ? 6378160. : 6367470.;
          const double rf = earthIsOblate ? 297.0 : 0;
519
520
521
          const double xval_0 = ISEC2_FirstLon * 0.001;
          const double yval_0 = ISEC2_FirstLat * 0.001;
          const double lon_0  = ISEC2_Lambert_Lov * 0.001;
522
523
          double lat_1  = ISEC2_Lambert_LatS1 * 0.001;
          double lat_2  = ISEC2_Lambert_LatS2 * 0.001;
524
          const bool lsouth = gribbyte_get_bit(ISEC2_Lambert_ProjFlag, 1);
525
          if ( lsouth ) { lat_1 = -lat_1; lat_2 = -lat_2; }
526

527
          const double lat_0 = lat_2;
528
529
          double x_0 = CDI_grid_missval;
          double y_0 = CDI_grid_missval;
530
531
532
533

          if ( proj_lonlat_to_lcc_func )
            {
              x_0 = xval_0; y_0 = yval_0;
534
535
              proj_lonlat_to_lcc_func(CDI_grid_missval, lon_0, lat_0, lat_1, lat_2, a, rf, (size_t)1, &x_0, &y_0);
              if ( IS_NOT_EQUAL(x_0, CDI_grid_missval) && IS_NOT_EQUAL(y_0, CDI_grid_missval) )
536
537
                { x_0 = -x_0; y_0 = -y_0; }
            }
538
          gridDefParamLCC(gridID, CDI_grid_missval, lon_0, lat_0, lat_1, lat_2, a, rf, xval_0, yval_0, x_0, y_0);
539
        }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
540
541
542
    }
  else
    Free(gridptr);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
543

544
  const int zaxistype = grib1ltypeToZaxisType(leveltype);
545
  if ( zaxistype == ZAXIS_HYBRID || zaxistype == ZAXIS_HYBRID_HALF )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
546
    {
547
      const size_t vctsize = (size_t)ISEC2_NumVCP;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
548
549
550
551
      double *vctptr = &fsec2[10];
      varDefVCT(vctsize, vctptr);
    }

552
  const bool lbounds = cgribexGetZaxisHasBounds(leveltype);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
553

554
  int varID = 0, levelID = 0;
555
  varAddRecord(recID, param, gridID, zaxistype, lbounds, level1, level2, 0, 0,
Uwe Schulzweida's avatar
Uwe Schulzweida committed
556
	       datatype, &varID, &levelID, tsteptype, numavg, leveltype, -1,
557
               NULL, NULL, NULL, NULL, NULL, NULL, NULL);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
558

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

562
  varDefCompType(varID, comptype);
563

564
565
  if ( uvRelativeToGrid ) varDefKeyInt(varID, CDI_KEY_UVRELATIVETOGRID, 1);

566
567
568
  if ( ISEC1_LocalFLag )
    {
      if      ( ISEC1_CenterID == 78  && isec1[36] == 253 ) // DWD local extension
569
570
571
572
573
        {
          varDefKeyInt(varID, CDI_KEY_TYPEOFENSEMBLEFORECAST, isec1[52]);
          varDefKeyInt(varID, CDI_KEY_NUMBEROFFORECASTSINENSEMBLE, isec1[53]);
          varDefKeyInt(varID, CDI_KEY_PERTURBATIONNUMBER, isec1[54]);
        }
574
      else if ( ISEC1_CenterID == 252 && isec1[36] ==   1 ) // MPIM local extension
575
576
577
578
579
        {
          varDefKeyInt(varID, CDI_KEY_TYPEOFENSEMBLEFORECAST, isec1[37]);
          varDefKeyInt(varID, CDI_KEY_NUMBEROFFORECASTSINENSEMBLE, isec1[39]);
          varDefKeyInt(varID, CDI_KEY_PERTURBATIONNUMBER, isec1[38]);
        }
580
    }
581

582
583
  if ( lmv ) varDefMissval(varID, FSEC3_MissVal);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
584
  if ( varInqInst(varID) == CDI_UNDEFID )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
585
    {
586
      const int center = ISEC1_CenterID;
587
      const int subcenter = ISEC1_SubCenterID;
588
      int instID = institutInq(center, subcenter, NULL, NULL);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
589
      if ( instID == CDI_UNDEFID )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
590
591
592
593
	instID = institutDef(center, subcenter, NULL, NULL);
      varDefInst(varID, instID);
    }

Uwe Schulzweida's avatar
Uwe Schulzweida committed
594
  if ( varInqModel(varID) == CDI_UNDEFID )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
595
    {
596
      int modelID = modelInq(varInqInst(varID), ISEC1_ModelID, NULL);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
597
      if ( modelID == CDI_UNDEFID )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
598
599
600
601
	modelID = modelDef(varInqInst(varID), ISEC1_ModelID, NULL);
      varDefModel(varID, modelID);
    }

Uwe Schulzweida's avatar
Uwe Schulzweida committed
602
  if ( varInqTable(varID) == CDI_UNDEFID )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
603
    {
604
      int tableID = tableInq(varInqModel(varID), ISEC1_CodeTable, NULL);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
605
      if ( tableID == CDI_UNDEFID )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
606
607
608
609
	tableID = tableDef(varInqModel(varID), ISEC1_CodeTable, NULL);
      varDefTable(varID, tableID);
    }

Uwe Schulzweida's avatar
Uwe Schulzweida committed
610
611
  streamptr->tsteps[tsID].nallrecs++;
  streamptr->nrecs++;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
612
613
}

614
615
616
617
static
void MCH_get_undef(int *isec1, double *undef_pds, double *undef_eps)
{
  /* 2010-01-13: Oliver Fuhrer */
618
619
620
621
622
623
624
625
626
627
628
629
630
631
  if ( ISEC1_CenterID == 215 )
    {
      if (isec1[34] != 0 && isec1[34] != 255)
        {
          if (isec1[34] & 2)
            {
              *undef_pds = ((isec1[34] & 1) ? -0.99 : +0.99) * pow(10.0,-isec1[35]);
              *undef_eps = pow(10.0,-isec1[35]-1);
            }
          else
            {
              *undef_pds = ((isec1[34] & 1) ? -0.99 : +0.99) * pow(10.0,+isec1[35]);
              *undef_eps = pow(10.0,isec1[35]-1);
            }
632
633
634
635
636
        }
    }
}

static
637
void cgribexDecodeHeader(cgribexrec_t *cgribexp, int *gribbuffer, int recsize, int *lmv, int *iret)
638
{
639
  int *isec0 = cgribexp->sec0;
640
  int *isec1 = cgribexp->sec1;
641
  int *isec2 = cgribexp->sec2;
642
  int *isec3 = cgribexp->sec3;
643
  int *isec4 = cgribexp->sec4;
644
645
646
  double *fsec2 = cgribexp->fsec2;
  double *fsec3 = cgribexp->fsec3;

647
  int ipunp = 0, iword = 0;
648

649
  memset(isec1, 0, 256*sizeof(int));
650
  memset(isec2, 0, 32*sizeof(int));
651

652
  double *fsec4 = NULL;
653
  gribExDP(isec0, isec1, isec2, fsec2, isec3, fsec3, isec4, fsec4,
654
	   ipunp, (int *) gribbuffer, recsize, &iword, "J", iret);
655

Uwe Schulzweida's avatar
Uwe Schulzweida committed
656
657
  if ( !(ISEC1_Sec2Or3Flag & 128) ) isec2[0] = -1; // default generic grid

658
659
660
661
662
663
664
665
666
667
  *lmv = 0;

  if ( ISEC1_CenterID == 215 && (isec1[34] != 0 && isec1[34] != 255) )
    {
      double undef_pds, undef_eps;
      MCH_get_undef(isec1, &undef_pds, &undef_eps);
      FSEC3_MissVal = undef_pds;
      *lmv = 1;
    }
}
668
669

static
670
compvar_t cgribexVarSet(int param, int level1, int level2, int leveltype, int trange)
671
{
672
  int tsteptype = cgribexGetTsteptype(trange);
673

674
  compvar_t compVar;
675
676
677
678
679
  compVar.param     = param;
  compVar.level1    = level1;
  compVar.level2    = level2;
  compVar.ltype     = leveltype;
  compVar.tsteptype = tsteptype;
680

Uwe Schulzweida's avatar
Uwe Schulzweida committed
681
  return compVar;
682
683
}

684
685
static inline
int cgribexVarCompare(compvar_t compVar, record_t record, int flag)
686
{
687
688
689
690
  bool vinst = compVar.tsteptype == TSTEP_INSTANT || compVar.tsteptype == TSTEP_INSTANT2 || compVar.tsteptype == TSTEP_INSTANT3;
  bool rinst = record.tsteptype == TSTEP_INSTANT || record.tsteptype == TSTEP_INSTANT2 || record.tsteptype == TSTEP_INSTANT3;
  int tstepDiff = (!((flag == 0) & (vinst && rinst)))
                & (compVar.tsteptype != record.tsteptype);
Thomas Jahns's avatar
Thomas Jahns committed
691
692
693
694
695
  int rstatus = (compVar.param != record.param)
    |           (compVar.level1 != record.ilevel)
    |           (compVar.level2 != record.ilevel2)
    |           (compVar.ltype != record.ltype)
    |           tstepDiff;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
696
  return rstatus;
697
}
Uwe Schulzweida's avatar
Uwe Schulzweida committed
698

699
700
701
#define gribWarning(text, nrecs, timestep, paramstr, level1, level2) \
            Warning("Record %2d (id=%s lev1=%d lev2=%d) timestep %d: %s", nrecs, paramstr, level1, level2, timestep, text)

702

703
704
705
706
707
708
709
710
711
712
713
714
715
static
void cgribexSkipRecords(const int fileID)
{
  int nskip = cdiSkipRecords;
  while (nskip-- > 0)
    {
      const size_t recsize = gribGetSize(fileID);
      if (recsize == 0) Error("Skipping of %d records failed!", cdiSkipRecords);

      const off_t recpos = fileGetPos(fileID);
      fileSetPos(fileID, recpos, SEEK_CUR);
    }
}
716

Uwe Schulzweida's avatar
Uwe Schulzweida committed
717
int cgribexScanTimestep1(stream_t *streamptr)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
718
{
719
  int lmv = 0, iret = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
720
  off_t recpos = 0;
721
  void *gribbuffer = NULL;
722
  size_t buffersize = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
723
  int leveltype = 0, level1 = 0, level2 = 0, vdate = 0, vtime = 0;
724
  DateTime datetime, datetime0 = { LONG_MIN, LONG_MIN };
725
  unsigned recID;
726
  int nrecs_scanned = 0;
727
728
729
730
  bool warn_time = true;
  bool warn_numavg = true;
  int rdate = 0, rtime = 0, tunit = 0;
  bool fcast = false;
731
  char paramstr[32];
Uwe Schulzweida's avatar
Uwe Schulzweida committed
732
733

  streamptr->curTsID = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
734

735
  cgribexrec_t *cgribexp = (cgribexrec_t *) streamptr->record->cgribexp;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
736

737
  const int tsID = tstepsNewEntry(streamptr);
738
  if (tsID != 0) Error("Internal problem! tstepsNewEntry returns %d", tsID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
739

740
  taxis_t *taxis = &streamptr->tsteps[tsID].taxis;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
741

742
  const int fileID = streamptr->fileID;
743

744
  if (cdiSkipRecords) cgribexSkipRecords(fileID);
745

746
  unsigned nrecs = 0;
747
  while (true)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
748
    {
749
      size_t recsize = gribGetSize(fileID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
750
751
752
753
      recpos  = fileGetPos(fileID);

      if ( recsize == 0 )
	{
754
	  if ( nrecs == 0 ) Error("No GRIB records found!");
Uwe Schulzweida's avatar
Uwe Schulzweida committed
755
	  streamptr->ntsteps = 1;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
756
757
	  break;
	}
758

759
      ensureBufferSize(recsize, &buffersize, &gribbuffer);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
760

761
762
763
      size_t readsize = recsize;
      // Search for next 'GRIB', read the following record, and position file offset after it.
      if (gribRead(fileID, gribbuffer, &readsize)) break;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
764

765
      const int comptype = grbDecompress(recsize, &buffersize, &gribbuffer);
766

767
      const size_t sec2len = cgribexSection2Length(gribbuffer, buffersize);
768
769
770
771
772
773
774
      if (sec2len > cgribexp->sec2len)
        {
          cgribexp->sec2len = sec2len;
          cgribexp->sec2 = (int *) Realloc(cgribexp->sec2, sec2len*sizeof(int));
        }

      int *isec1 = cgribexp->sec1;
775

776
      nrecs_scanned++;
777
      cgribexDecodeHeader(cgribexp, (int *) gribbuffer, (int)recsize, &lmv, &iret);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
778

779
      const int param = cdiEncodeParam(ISEC1_Parameter, ISEC1_CodeTable, 255);
780
781
      cdiParamToString(param, paramstr, sizeof(paramstr));

Uwe Schulzweida's avatar
Uwe Schulzweida committed
782
      cgribexGetLevel(isec1, &leveltype, &level1, &level2);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
783

Uwe Schulzweida's avatar
Uwe Schulzweida committed
784
785
      gribDateTime(isec1, &vdate, &vtime);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
786
787
788
789
790
791
      if ( nrecs == 0 )
	{
	  datetime0.date = vdate;
	  datetime0.time = vtime;
	  rdate = gribRefDate(isec1);
	  rtime = gribRefTime(isec1);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
792
	  tunit = cgribexGetTimeUnit(isec1);
793
	  fcast = cgribexTimeIsFC(isec1);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
794
795
796
	}
      else
	{
797
798
	  datetime.date = vdate;
	  datetime.time = vtime;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
799
	  compvar_t compVar = cgribexVarSet(param, level1, level2, leveltype, ISEC1_TimeRange);
800
          record_t *records = streamptr->tsteps[tsID].records;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
801
802
	  for ( recID = 0; recID < nrecs; recID++ )
	    {
803
	      if ( cgribexVarCompare(compVar, records[recID], 0) == 0 ) break;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
804
	    }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
805

806
	  if ( CDI_inventory_mode == 1 )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
807
808
809
	    {
	      if ( recID < nrecs ) break;
	      if ( warn_time )
810
		if ( datetimeCmp(datetime, datetime0) != 0 )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
811
		  {
812
                    gribWarning("Inconsistent verification time!", nrecs_scanned, tsID+1, paramstr, level1, level2);
813
		    warn_time = false;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
814
815
816
817
		  }
	    }
	  else
	    {
818
	      if ( datetimeCmp(datetime, datetime0) != 0 ) break;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
819
820
821

	      if ( recID < nrecs )
		{
822
		  gribWarning("Parameter already exist, skipped!", nrecs_scanned, tsID+1, paramstr, level1, level2);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
823
824
825
		  continue;
		}
	    }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
826
827
828
829
830
831
	}

      if ( ISEC1_AvgNum )
	{
	  if (  taxis->numavg && warn_numavg && (taxis->numavg != ISEC1_AvgNum) )
	    {
832
	      Warning("Changing numavg from %d to %d not supported!", taxis->numavg, ISEC1_AvgNum);
833
	      warn_numavg = false;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
834
835
836
837
838
839
840
841
842
843
	    }
	  else
	    {
	      taxis->numavg = ISEC1_AvgNum;
	    }
	}

      nrecs++;

      if ( CDI_Debug )
844
	Message("Read record %2d (id=%s lev1=%d lev2=%d) %8d %6d", nrecs_scanned, paramstr, level1, level2, vdate, vtime);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
845

846
      cgribexAddRecord(streamptr, cgribexp, param, recsize, recpos, comptype, lmv, iret);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
847
848
    }

Uwe Schulzweida's avatar
Uwe Schulzweida committed
849
  streamptr->rtsteps = 1;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
850

Uwe Schulzweida's avatar
Uwe Schulzweida committed
851
  if ( nrecs == 0 ) return CDI_EUFSTRUCT;
852

853
  cdi_generate_vars(streamptr);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
854

855
856
  taxis->unit = tunit;
  taxis->type = fcast ? TAXIS_RELATIVE : TAXIS_ABSOLUTE;
857
  int taxisID = taxisCreate(taxis->type);
858
859
  taxis->rdate = rdate;
  taxis->rtime = rtime;
860
  taxis->vdate = (int64_t)datetime0.date;
861
  taxis->vtime = (int)datetime0.time;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
862

863
  const int vlistID = streamptr->vlistID;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
864
865
  vlistDefTaxis(vlistID, taxisID);

866
  streamScanResizeRecords1(streamptr);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
867

Uwe Schulzweida's avatar
Uwe Schulzweida committed
868
  streamptr->record->buffer     = gribbuffer;
869
  streamptr->record->buffersize = buffersize;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
870

871
  streamScanTsFixNtsteps(streamptr, recpos);
872
  streamScanTimeConstAdjust(streamptr, taxis);
873

Uwe Schulzweida's avatar
Uwe Schulzweida committed
874
  return 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
875
876
}

Uwe Schulzweida's avatar
Uwe Schulzweida committed
877

878
int cgribexScanTimestep2(stream_t * streamptr)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
879
{
880
  int lmv = 0, iret = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
881
  off_t recpos = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
882
  int leveltype = 0, level1 = 0, level2 = 0, vdate = 0, vtime = 0;