stream_cgribex.c 62.2 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);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
87
static
88
size_t cgribexSection2Length(void *gribbuffer, size_t gribbuffersize)
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
{
  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;

111
  if (gribbuffersize && gribbuffer)
112 113 114 115
    {
      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);
116
      if (status >= 0)
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
        {
          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)
{
133
  if (gh) Free(gh);
134 135
}

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

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

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

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

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

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

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

183
  // clang-format off
Uwe Schulzweida's avatar
Uwe Schulzweida committed
184 185
  switch ( ISEC1_TimeUnit )
    {
186 187 188 189 190 191 192 193
    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
194 195 196
    default:
      if ( lprint )
	{
197
	  Message("GRIB time unit %d unsupported!", ISEC1_TimeUnit);
198
	  lprint = false;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
199
	}
Uwe Schulzweida's avatar
Uwe Schulzweida committed
200
      break;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
201
    }
202
  // clang-format on
Uwe Schulzweida's avatar
Uwe Schulzweida committed
203

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

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

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

219
  // clang-format off
220
  int tsteptype = TSTEP_INSTANT;
221 222 223 224 225 226 227 228 229 230 231 232
  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 )
	{
233
	  Message("Time range indicator %d unsupported, set to 0!", timerange);
234
	  lprint = false;
235
	}
Uwe Schulzweida's avatar
Uwe Schulzweida committed
236
      break;
237
    }
238
  // clang-format on
239

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

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

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

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

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

275 276 277
      const size_t nvalues = (size_t) ISEC4_NumValues;
      const size_t nlon = (size_t) ISEC2_NumLon;
      const size_t nlat = (size_t) ISEC2_NumLat;
278 279 280 281 282 283 284
      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;

285 286 287 288 289
      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
290
      {
291 292 293
        if ( grid->x.size > 1 )
          {
            bool recompinc = true;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
294

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

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

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

315 316 317 318 319 320 321 322 323 324 325 326 327 328
            /* 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
329
      }
330 331
      grid->y.flag = 0;
      /* if ( ISEC2_FirstLat != 0 || ISEC2_LastLat != 0 ) */
Uwe Schulzweida's avatar
Uwe Schulzweida committed
332
      {
333 334 335
        if ( grid->y.size > 1 && compyinc )
          {
            bool recompinc = true;
336
            if ( ijDirectionIncrementGiven && ISEC2_LatIncr > 0 )
337
              {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
338
                if ( labs(ISEC2_LastLat - (ISEC2_FirstLat+ISEC2_LatIncr*((long)grid->y.size-1))) <= 2 )
339 340 341 342 343 344 345 346 347 348 349 350
                  {
                    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
351
      }
352 353 354
    }
  else if ( gridtype == GRID_GAUSSIAN_REDUCED )
    {
355
      const bool ijDirectionIncrementGiven = gribbyte_get_bit(ISEC2_ResFlag, 1);
356
      uvRelativeToGrid = gribbyte_get_bit(ISEC2_ResFlag, 5);
357
      grid->np      = ISEC2_NumPar;
358
      grid->size    = (size_t)ISEC4_NumValues;
359
      grid->reducedPoints  = ISEC2_ReducedPointsPtr;
360
      grid->reducedPointsSize = (size_t)ISEC2_NumLat;
361
      grid->y.size  = (size_t)ISEC2_NumLat;
362 363 364 365
      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
366
      {
367 368 369 370
        if ( grid->x.size > 1 )
          {
            if ( ISEC2_LastLon < ISEC2_FirstLon && ISEC2_LastLon < 0 ) ISEC2_LastLon += 360000;

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

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

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

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

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

  return uvRelativeToGrid;
447 448
}

Uwe Schulzweida's avatar
Uwe Schulzweida committed
449 450 451 452 453 454 455 456 457 458
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;
}

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

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

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

478
  const int tsteptype = cgribexGetTsteptype(ISEC1_TimeRange);
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;
503 504 505
          int *reducedPoints = gridptr->reducedPoints;
          gridptr->reducedPoints = (int*) Malloc(reducedPointsSize * sizeof(int));
          memcpy(gridptr->reducedPoints, reducedPoints, 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,
556
	       datatype, &varID, &levelID, tsteptype, leveltype, -1,
557
               NULL, NULL, NULL, NULL);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
558

559
  record->varID = (short)varID;
560
  record->levelID = 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;
723
  int leveltype = 0, level1 = 0, level2 = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
724
  DateTime datetime0 = { .date = 10101, .time = 0 };
725
  unsigned recID;
726
  int nrecs_scanned = 0;
727 728 729
  bool warn_time = true;
  bool warn_numavg = true;
  bool fcast = false;
730
  char paramstr[32];
Uwe Schulzweida's avatar
Uwe Schulzweida committed
731 732

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

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

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

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

741
  const int fileID = streamptr->fileID;
742

743
  if (cdiSkipRecords) cgribexSkipRecords(fileID);
744

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

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

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

760 761 762
      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
763

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

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

      int *isec1 = cgribexp->sec1;
774

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

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

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

Uwe Schulzweida's avatar
Uwe Schulzweida committed
783 784
      int vdate, sdate;
      int vtime, stime;
785
      gribDateTimeX(isec1, &vdate, &vtime, &sdate, &stime);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
786
      DateTime datetime = { .date = vdate, .time = vtime };
Uwe Schulzweida's avatar
Uwe Schulzweida committed
787

Uwe Schulzweida's avatar
Uwe Schulzweida committed
788 789
      if ( nrecs == 0 )
	{
Uwe Schulzweida's avatar
Uwe Schulzweida committed
790
          datetime0 = datetime;
791
	  fcast = cgribexTimeIsFC(isec1);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
792 793 794 795 796 797 798
	  taxis->unit = cgribexGetTimeUnit(isec1);
	  taxis->rdate = gribRefDate(isec1);
	  taxis->rtime = gribRefTime(isec1);
          taxis->sdate = sdate;
          taxis->stime = stime;
          taxis->vdate = vdate;
          taxis->vtime = vtime;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
799 800 801
	}
      else
	{