stream_gribapi.c 52.6 KB
Newer Older
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1
2
3
4
5
6
7
8
9
10
11
12
#if defined (HAVE_CONFIG_H)
#  include "config.h"
#endif

#include <stdio.h>

#include "cdi.h"
#include "stream_int.h"
#include "file.h"
#include "varscan.h"
#include "datetime.h"
#include "vlist.h"
Uwe Schulzweida's avatar
Uwe Schulzweida committed
13
#include "stream_grb.h"
Uwe Schulzweida's avatar
Uwe Schulzweida committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

#include "gribapi.h"

#if  defined  (HAVE_LIBGRIB_API)
#  if  defined  (HAVE_LIBCGRIBEX)
#  include "cgribex.h"      /* gribGetSize, gribRead, gribGetZip */
#  endif
#  include "grib_api.h"
#endif


extern int cdiInventoryMode;

typedef struct {
  int code;
  int table;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
30
  int discipline;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
  int level1;
  int level2;
  int ltype;
} compvar2_t; 


#if  defined  (HAVE_LIBGRIB_API)
static
int gribapiGetGridType(grib_handle *gh)
{
  /*  static char func[] = "gribapiGetGridType"; */
  int gridtype = 0;
  int gribgridtype;
  long lpar;

  GRIB_CHECK(grib_get_long(gh, "gridDefinitionTemplateNumber", &lpar), 0);
  gribgridtype = (int) lpar;

  switch (gribgridtype)
    {
    case  GRIBAPI_GTYPE_LATLON:
    case  GRIBAPI_GTYPE_LATLON_ROT:
      {
	gridtype = GRID_LONLAT;
	break;
      }
    case  GRIBAPI_GTYPE_LCC:
      {
	gridtype = GRID_LCC;
	break;
      }
    case  GRIBAPI_GTYPE_GAUSSIAN:
      {
	/*
	if ( ISEC2_Reduced )
	  gridtype = GRID_GAUSSIAN_REDUCED;
	else
	*/
	  gridtype = GRID_GAUSSIAN;
	break;
      }
    case  GRIBAPI_GTYPE_SPECTRAL:
      {
	gridtype = GRID_SPECTRAL;
	break;
      }
    case  GRIBAPI_GTYPE_GME:
      {
	gridtype = GRID_GME;
	break;
      }
    default:
      {
	gridtype = GRID_GENERIC;
	break;
      }
    }

  return (gridtype);
}
#endif

#if  defined  (HAVE_LIBGRIB_API)
static
int gribapiGetZaxisType(int grb_ltype)
{
  int zaxistype = 0;

  switch ( grb_ltype )
    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
101
    case GRIBAPI_LTYPE_SURFACE:
Uwe Schulzweida's avatar
Uwe Schulzweida committed
102
103
104
105
      {
	zaxistype = ZAXIS_SURFACE;
	break;
      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
106
    case GRIBAPI_LTYPE_MEANSEA:
Uwe Schulzweida's avatar
Uwe Schulzweida committed
107
108
109
110
      {
	zaxistype = ZAXIS_MEANSEA;
	break;
      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
111
    case GRIBAPI_LTYPE_ISOBARIC:
Uwe Schulzweida's avatar
Uwe Schulzweida committed
112
113
114
115
      {
	zaxistype = ZAXIS_PRESSURE;
	break;
      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
116
    case GRIBAPI_LTYPE_HEIGHT:
Uwe Schulzweida's avatar
Uwe Schulzweida committed
117
118
119
120
      {
	zaxistype = ZAXIS_HEIGHT;
	break;
      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
121
    case GRIBAPI_LTYPE_ALTITUDE:
Uwe Schulzweida's avatar
Uwe Schulzweida committed
122
123
124
125
      {
	zaxistype = ZAXIS_ALTITUDE;
	break;
      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
126
    case GRIBAPI_LTYPE_SIGMA:
Uwe Schulzweida's avatar
Uwe Schulzweida committed
127
128
129
130
      {
	zaxistype = ZAXIS_SIGMA;
	break;
      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
131
132
    case GRIBAPI_LTYPE_HYBRID:
      //case GRIBAPI_LTYPE_HYBRID_LAYER:
Uwe Schulzweida's avatar
Uwe Schulzweida committed
133
134
135
136
      {
	zaxistype = ZAXIS_HYBRID;
	break;
      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
137
138
    case GRIBAPI_LTYPE_LANDDEPTH:
      //case GRIBAPI_LTYPE_LANDDEPTH_LAYER:
Uwe Schulzweida's avatar
Uwe Schulzweida committed
139
140
141
142
      {
	zaxistype = ZAXIS_DEPTH_BELOW_LAND;
	break;
      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
143
    case GRIBAPI_LTYPE_ISENTROPIC:
Uwe Schulzweida's avatar
Uwe Schulzweida committed
144
145
146
147
      {
	zaxistype = ZAXIS_ISENTROPIC;
	break;
      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
148
    case GRIBAPI_LTYPE_SEADEPTH:
Uwe Schulzweida's avatar
Uwe Schulzweida committed
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
      {
	zaxistype = ZAXIS_DEPTH_BELOW_SEA;
	break;
      }
    default:
      {
	zaxistype = ZAXIS_GENERIC;
	break;
      }
    }

  return (zaxistype);
}
#endif

#if  defined  (HAVE_LIBGRIB_API)
static
void gribapiAddRecord(int streamID, int code, grib_handle *gh,
		      long recsize, off_t position, int prec, int ztype)
{
  static char func[] = "gribapiAddRecord";
  int gridtype;
  int zaxistype;
  int gridID = CDI_UNDEFID, varID;
  int levelID = 0;
  int tsID, recID;
  int level1, level2;
  int numavg;
  int lbounds = 0;
  RECORD *record;
  grid_t grid;
  int vlistID;
  stream_t *streamptr;
  int leveltype;
  double dlevel;
  long lpar;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
185
  int table_num;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
186
  int status;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
187
188
  long numberOfPoints;
  size_t datasize;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
189
190
191
192
193
194
195
196

  streamptr = stream_to_pointer(streamID);

  vlistID = streamInqVlist(streamID);
  tsID    = streamptr->curTsID;
  recID   = recordNewEntry(streamID, tsID);
  record  = &streamptr->tsteps[tsID].records[recID];

Uwe Schulzweida's avatar
Uwe Schulzweida committed
197
198
199
  GRIB_CHECK(grib_get_long(gh, "parameterCategory", &lpar), 0);
  table_num = (int) lpar;

Uwe Schulzweida's avatar
Uwe Schulzweida committed
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
  // numavg  = ISEC1_AvgNum;
  numavg  = 0;
  /*
  level1  = ISEC1_Level1;
  level2  = ISEC1_Level2;
  */
  status = grib_get_long(gh, "typeOfFirstFixedSurface", &lpar);
  if ( status == 0 )
    {
      leveltype = (int) lpar;
      GRIB_CHECK(grib_get_double(gh, "level", &dlevel), 0);
      if ( leveltype == 100 ) dlevel *= 100;
      if ( dlevel < -2.e9 || dlevel > 2.e9 ) dlevel = 0;
    }
  else 
    {
      leveltype = 0;
      dlevel = 0;
    }

  level1 = (int) dlevel;
  level2 = 0;

  /* fprintf(stderr, "code %d %d %d %d\n", code, level1, level2, ISEC1_LevelType); */

  (*record).size     = recsize;
  (*record).position = position;
  (*record).code     = code;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
228
  (*record).table    = table_num;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
  (*record).ilevel   = level1;
  (*record).ilevel2  = level2;
  (*record).ltype    = leveltype;

  gridtype = gribapiGetGridType(gh);
  /*
  if ( streamptr->unreduced && gridtype == GRID_GAUSSIAN_REDUCED )
    {
      gridtype = GRID_GAUSSIAN;
      ISEC2_NumLon = 2*ISEC2_NumLat;
      ISEC4_NumValues = ISEC2_NumLon*ISEC2_NumLat;
    }
  */
  memset(&grid, 0, sizeof(grid_t));

Uwe Schulzweida's avatar
Uwe Schulzweida committed
244
245
246
  GRIB_CHECK(grib_get_size(gh, "values", &datasize), 0);
  GRIB_CHECK(grib_get_long(gh, "numberOfPoints", &numberOfPoints), 0);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
  switch (gridtype)
    {
    case GRID_LONLAT:
    case GRID_GAUSSIAN:
      {
	int nlon, nlat;

	GRIB_CHECK(grib_get_long(gh, "Ni", &lpar), 0);
	nlon = lpar;
	GRIB_CHECK(grib_get_long(gh, "Nj", &lpar), 0);
	nlat = lpar;

	if ( numberOfPoints != nlon*nlat )
	  Error(func, "wrong datasize! isec4len = %d isec2len = %d",
		(int)numberOfPoints, nlon*nlat);
	grid.size  = numberOfPoints;
	grid.xsize = nlon;
	grid.ysize = nlat;
	grid.xinc  = 0;
	grid.yinc  = 0;
	grid.xdef  = 0;
	/* if ( ISEC2_FirstLon != 0 || ISEC2_LastLon != 0 ) */
	  {
	    if ( grid.xsize > 1 )
	      {
		/*
		if ( ISEC2_ResFlag && ISEC2_LonIncr > 0 )
		  grid.xinc = ISEC2_LonIncr * 0.001;
		else
		  grid.xinc = (ISEC2_LastLon - ISEC2_FirstLon) * 0.001 / (grid.xsize - 1);
		*/
		/* correct xinc if necessary */
		/*
		if ( ISEC2_FirstLon == 0 && ISEC2_LastLon > 354000 )
		  {
		    double xinc = 360. / grid.xsize;

		    if ( fabs(grid.xinc-xinc) > 0.0 )
		      {
			grid.xinc = xinc;
			if ( CDI_Debug ) Message(func, "set xinc to %g", grid.xinc);
		      }
		  }
		*/
	      }
	    /*
	    grid.xfirst = ISEC2_FirstLon * 0.001;
	    grid.xlast  = ISEC2_LastLon  * 0.001;
	    */
	    grid.xdef   = 2;	    
	  }
	grid.ydef  = 0;
	/* if ( ISEC2_FirstLat != 0 || ISEC2_LastLat != 0 ) */
	  {
	    if ( grid.ysize > 1 )
	      {
		/*
		if ( ISEC2_ResFlag && ISEC2_LatIncr > 0 )
		  grid.yinc = ISEC2_LatIncr * 0.001;
		else
		  grid.yinc = (ISEC2_LastLat - ISEC2_FirstLat) * 0.001 / (grid.ysize - 1);
		*/
	      }
	    /*
	    grid.yfirst = ISEC2_FirstLat * 0.001;
	    grid.ylast  = ISEC2_LastLat  * 0.001;
	    */
	    grid.ydef   = 2;	    
	  }
	break;
      }
      /*
    case GRID_GAUSSIAN_REDUCED:
      {
	grid.size   = ISEC4_NumValues;
        grid.rowlon = ISEC2_RowLonPtr;
	grid.ysize  = ISEC2_NumLat;
	grid.xinc  = 0;
	grid.yinc  = 0;
	grid.xdef  = 0;
	  {
	    if ( grid.xsize > 1 )
	      {
		if ( ISEC2_ResFlag && ISEC2_LonIncr > 0 )
		  grid.xinc = ISEC2_LonIncr * 0.001;
		else
		  grid.xinc = (ISEC2_LastLon - ISEC2_FirstLon) * 0.001 / (grid.xsize - 1);
	      }
	    grid.xfirst = ISEC2_FirstLon * 0.001;
	    grid.xlast  = ISEC2_LastLon  * 0.001;
	    grid.xdef   = 2;	    
	  }
	grid.ydef  = 0;
	  {
	    if ( grid.ysize > 1 )
	      {
		if ( ISEC2_ResFlag && ISEC2_LatIncr > 0 )
		  grid.yinc = ISEC2_LatIncr * 0.001;
		else
		  grid.yinc = (ISEC2_LastLat - ISEC2_FirstLat) * 0.001 / (grid.ysize - 1);
	      }
	    grid.yfirst = ISEC2_FirstLat * 0.001;
	    grid.ylast  = ISEC2_LastLat  * 0.001;
	    grid.ydef   = 2;	    
	  }
	break;
      }
    case GRID_LCC:
      {
	if ( ISEC4_NumValues != ISEC2_NumLon*ISEC2_NumLat )
	  Error(func, "wrong datasize! isec4len = %d isec2len = %d",
		ISEC4_NumValues, ISEC2_NumLon*ISEC2_NumLat);

	grid.size  = ISEC4_NumValues;
	grid.xsize = ISEC2_NumLon;
	grid.ysize = ISEC2_NumLat;

	grid.lcc_xinc      = ISEC2_Lambert_dx;
	grid.lcc_yinc      = ISEC2_Lambert_dy;
	grid.lcc_originLon = ISEC2_FirstLon * 0.001;
	grid.lcc_originLat = ISEC2_FirstLat * 0.001;
	grid.lcc_lonParY   = ISEC2_Lambert_Lov * 0.001;
	grid.lcc_lat1      = ISEC2_Lambert_LatS1 * 0.001;
	grid.lcc_lat2      = ISEC2_Lambert_LatS2 * 0.001;
	grid.lcc_projflag  = ISEC2_Lambert_ProjFlag;
	grid.lcc_scanflag  = ISEC2_ScanFlag;

	grid.xdef   = 0;	    
	grid.ydef   = 0;

	break;
      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
379
      */
Uwe Schulzweida's avatar
Uwe Schulzweida committed
380
381
    case GRID_SPECTRAL:
      {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
382
383
384
	grid.size  = datasize;
	GRIB_CHECK(grib_get_long(gh, "J", &lpar), 0);
	grid.trunc = lpar;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
385
386
	break;
      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
387
      /*
Uwe Schulzweida's avatar
Uwe Schulzweida committed
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
    case GRID_GME:
      {
	grid.size  = ISEC4_NumValues;
	grid.nd    = ISEC2_GME_ND;
	grid.ni    = ISEC2_GME_NI;
	grid.ni2   = ISEC2_GME_NI2;
	grid.ni3   = ISEC2_GME_NI3;
	break;
      }
    case GRID_GENERIC:
      {
	grid.size  = ISEC4_NumValues;
	grid.xsize = 0;
	grid.ysize = 0;
	break;
      }
      */
    default:
      {
	Error(func, "%s grid unsupported", gridNamePtr(gridtype));
	break;
      }
    }

  grid.isRotated = FALSE;
  /*
  if ( cgribexGetIsRotated(isec2) )
    {
      grid.isRotated = TRUE;
      grid.ypole     = - ISEC2_LatSP * 0.001;
      grid.xpole     =   ISEC2_LonSP * 0.001 - 180;
      grid.angle     = 0;
    }
  */
  grid.xvals = NULL;
  grid.yvals = NULL;
  grid.type  = gridtype;

  gridID = varDefGrid(vlistID, grid, 0);

  zaxistype = gribapiGetZaxisType(leveltype);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
429

Uwe Schulzweida's avatar
Uwe Schulzweida committed
430
431
  if ( zaxistype == ZAXIS_HYBRID )
    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
432
      int vctsize;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
433
      size_t dummy;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
434
      double *vctptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
435

Uwe Schulzweida's avatar
Uwe Schulzweida committed
436
437
438
      GRIB_CHECK(grib_get_long(gh, "NV", &lpar), 0);
      vctsize = lpar;
      vctptr = (double *) malloc(vctsize*sizeof(double));
Uwe Schulzweida's avatar
Uwe Schulzweida committed
439
440
      dummy = vctsize;
      GRIB_CHECK(grib_get_double_array(gh, "pv", vctptr, &dummy), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
441
      varDefVCT(vctsize, vctptr);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
442
      free(vctptr);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
443
    }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
444

Uwe Schulzweida's avatar
Uwe Schulzweida committed
445
446
447
448
449
450
  //lbounds = cgribexGetZaxisHasBounds(ISEC1_LevelType);

  if ( prec > 32 ) prec = DATATYPE_PACK32;
  if ( prec <  0 ) prec = DATATYPE_PACK;

  varAddRecord(recID, code, gridID, zaxistype, lbounds, level1, level2,
Uwe Schulzweida's avatar
Uwe Schulzweida committed
451
	       prec, &varID, &levelID, numavg, table_num, leveltype);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
452
453
454
455
456
457
458
459

  (*record).varID   = varID;
  (*record).levelID = levelID;

  varDefZtype(varID, ztype);

  if ( varInqInst(varID) == CDI_UNDEFID )
    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
460
461
462
463
464
      long center, subcenter;
      int instID;
      GRIB_CHECK(grib_get_long(gh, "centre", &center), 0);
      GRIB_CHECK(grib_get_long(gh, "subCentre", &subcenter), 0);
      instID    = institutInq((int)center, (int)subcenter, NULL, NULL);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
465
      if ( instID == CDI_UNDEFID )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
466
	instID = institutDef((int)center, (int)subcenter, NULL, NULL);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
467
468
469
470
471
472
      varDefInst(varID, instID);
    }

  if ( varInqModel(varID) == CDI_UNDEFID )
    {
      int modelID;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
473
474
475
      long processID;
      GRIB_CHECK(grib_get_long(gh, "generatingProcessIdentifier", &processID), 0);
      modelID = modelInq(varInqInst(varID), processID, NULL);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
476
      if ( modelID == CDI_UNDEFID )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
477
	modelID = modelDef(varInqInst(varID), processID, NULL);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
478
479
480
481
482
483
484
      varDefModel(varID, modelID);
    }

  if ( varInqTable(varID) == CDI_UNDEFID )
    {
      int tableID;

Uwe Schulzweida's avatar
Uwe Schulzweida committed
485
      tableID = tableInq(varInqModel(varID), table_num, NULL);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
      /*
      if ( tableID == CDI_UNDEFID && cdiPartabPath )
	{
	  char line[8192];
	  char command[4096];
	  FILE *pfp;
	  int nfiles;
	  int max_partab = 4096;
	  char *fnames[4096];
	  int cen, sub, ver, tab, nf, fi;
	  int icen, isub, iver, itab;

	  icen = ISEC1_CenterID;
          isub = ISEC1_SubCenterID;
          iver = ISEC1_ModelID;
          itab = ISEC1_CodeTable;
	  
	  sprintf(command, "cd %s 2> /dev/null; ls * 2> /dev/null", cdiPartabPath);

	  pfp = popen(command, "r");
	  if ( pfp == NULL )
	    SysError(func, "popen %s failed", command);
	  
	  nfiles = 0;
	  while ( _readline_(pfp, line, 8192) )
	    {
	      cen = -1; sub = -1; ver = -1; tab = -1;
	      nf = sscanf(line, "Cen%d_Sub%d_Ver%d_Tab%d", &cen, &sub, &ver, &tab);
	      printf("%d %d %d %d %d\n", nf, cen, sub, ver, tab);
	      if ( nfiles >= max_partab )
		{
		  Warning(func, "Too many parameter tables (limit: %d)", max_partab);
		  break;
		}
	      fnames[nfiles++] = strdupx(line);
	      printf("test: %s\n", line);
	    }

	  pclose(pfp);

	  if ( nfiles )
	    {
	      cen = -1; sub = -1; ver = -1; tab = -1;
	      for ( fi = 0; fi < nfiles; ++fi )
		{
		  nf = sscanf(fnames[fi], "Cen%d_Sub%d_Ver%d_Tab%d", &cen, &sub, &ver, &tab);
		  if ( nf == 4 && cen == icen && sub == isub && ver == iver && tab == itab ) goto END_LABEL;
		}
	      for ( fi = 0; fi < nfiles; ++fi )
		{
		  nf = sscanf(fnames[fi], "Cen%d_Sub%d_Tab%d", &cen, &sub, &tab);
		  if ( nf == 3 && cen == icen && sub == isub && tab == itab ) goto END_LABEL;
		}

	    END_LABEL:

	      if ( fi < nfiles )
		{
		  printf("found table %s\n", fnames[fi]);
		}
	    }
	}
      */
      if ( tableID == CDI_UNDEFID )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
550
	tableID = tableDef(varInqModel(varID), table_num, NULL);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
      varDefTable(varID, tableID);
    }

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

  if ( CDI_Debug )
    Message(func, "varID = %d  code = %d  zaxistype = %d  gridID = %d  levelID = %d",
	    varID, code, zaxistype, gridID, levelID);
}
#endif

void gribapiScanTimestep1(int streamID)
{
  static char func [] = "gribapiScanTimestep1";
#if  defined  (HAVE_LIBGRIB_API)
  off_t recpos = 0;
  unsigned char *gribbuffer = NULL;
  long buffersize = 0;
  int iret = 0, ipunp = 0, iword = 0;
  int status;
  int fileID;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
573
  int table_num = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
  int rcode = 0, level1 = 0, level2 = 0, vdate = 0, vtime = 0;
  DateTime datetime, datetime0;
  int tsID;
  int varID;
  size_t readsize;
  int nrecords, nrecs, recID;
  int prec;
  long recsize = 0;
  int warn_time = TRUE;
  int warn_numavg = TRUE;
  int taxisID = -1;
  int rdate = 0, rtime = 0, tunit = 0, fcast = 0;
  TAXIS *taxis;
  int vlistID;
  int ztype;
  long unzipsize;
  compvar2_t compVar, compVar0;
  stream_t *streamptr;
  grib_handle *gh = NULL;
  int leveltype;
  long editionNumber;
  long lpar;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
596
  int bitsPerValue;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
597
  double dlevel = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
598
  int warn_lpar = TRUE;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671

  streamptr = stream_to_pointer(streamID);

  stream_check_ptr(func, streamptr);

  streamptr->curTsID = 0;

  tsID  = tstepsNewEntry(streamID);
  taxis = &streamptr->tsteps[tsID].taxis;

  if ( tsID != 0 )
    Error(func, "Internal problem! tstepsNewEntry returns %d", tsID);

  fileID = streamInqFileID(streamID);

  nrecs = 0;
  while ( TRUE )
    {
      recsize = gribGetSize(fileID);
      recpos  = fileGetPos(fileID);

      if ( recsize == 0 )
	{
	  streamptr->ntsteps = 1;
	  break;
	}
      if ( recsize > buffersize )
	{
	  buffersize = recsize;
	  gribbuffer = (unsigned char *) realloc(gribbuffer, buffersize);
	}

      readsize = recsize;
      status = gribRead(fileID, gribbuffer, &readsize);
      if ( status ) break;

      ztype = COMPRESS_NONE;
      if ( gribGetZip(recsize, gribbuffer, &unzipsize) > 0 )
	{
	  ztype = COMPRESS_SZIP;
	  unzipsize += 100; /* need 0 to 1 bytes for rounding of bds */
	  if ( (long) buffersize < unzipsize )
	    {
	      buffersize = unzipsize;
	      gribbuffer = (unsigned char *) realloc(gribbuffer, buffersize);
	    }
	}

      gh = grib_handle_new_from_message(NULL, (void *) gribbuffer, recsize);
      GRIB_CHECK(grib_set_double(gh, "missingValue", GRIB_MISSVAL), 0);

      GRIB_CHECK(grib_get_long(gh, "editionNumber", &editionNumber), 0);

      if ( editionNumber <= 1 )
	{
	  GRIB_CHECK(grib_get_long(gh, "indicatorOfParameter", &lpar), 0);
	  rcode = (int) lpar;
	  status = grib_get_long(gh, "indicatorOfTypeOfLevel", &lpar);
	  if ( status == 0 )
	    {
	      leveltype = (int) lpar;
	      GRIB_CHECK(grib_get_double(gh, "level", &dlevel), 0);
	      if ( leveltype == 100 ) dlevel *= 100;
	      if ( dlevel < -2.e9 || dlevel > 2.e9 ) dlevel = 0;
	    }
	  else 
	    {
	      leveltype = 0;
	      dlevel = 0;
	    }
	}
      else
	{
Uwe Schulzweida's avatar
Uwe Schulzweida committed
672
673
674
675
676
677
678
679
680
	  GRIB_CHECK(grib_get_long(gh, "discipline", &lpar), 0);
	  if ( lpar != 255 && warn_lpar )
	    {
	      Warning(func, "GRIB2 discipline %ld unsupported!", lpar);
	      warn_lpar = FALSE;
	    }
	  GRIB_CHECK(grib_get_long(gh, "parameterCategory", &lpar), 0);
	  table_num = (int) lpar;

Uwe Schulzweida's avatar
Uwe Schulzweida committed
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
	  GRIB_CHECK(grib_get_long(gh, "parameterNumber", &lpar), 0);
	  rcode = (int) lpar;
	  status = grib_get_long(gh, "typeOfFirstFixedSurface", &lpar);
	  if ( status == 0 )
	    {
	      leveltype = (int) lpar;
	      GRIB_CHECK(grib_get_double(gh, "level", &dlevel), 0);
	      if ( leveltype == 100 ) dlevel *= 100;
	      if ( dlevel < -2.e9 || dlevel > 2.e9 ) dlevel = 0;
	    }
	  else 
	    {
	      leveltype = 0;
	      dlevel = 0;
	    }
	}

      level1 = (int) dlevel;
      level2 = 0;

      GRIB_CHECK(grib_get_long(gh, "dataDate", &lpar), 0);
      vdate = (int) lpar;
      GRIB_CHECK(grib_get_long(gh, "dataTime", &lpar), 0);
      vtime = (int) lpar*100;

Uwe Schulzweida's avatar
Uwe Schulzweida committed
706
707
708
709
      GRIB_CHECK(grib_get_long(gh,"bitsPerValue", &lpar),0);
      bitsPerValue = (int) lpar;
      if ( bitsPerValue > 0 && bitsPerValue <= 32 )
	prec = bitsPerValue;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
710
711
      else
        prec = DATATYPE_PACK;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
712

Uwe Schulzweida's avatar
Uwe Schulzweida committed
713
714
715
716
      if ( nrecs == 0 )
	{
	  datetime0.date = vdate;
	  datetime0.time = vtime;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
717
718
719
720
	  rdate = 0;
	  rtime = 0;
	  tunit = 0;
	  fcast = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
721
722
723
724
725
726
727
728
729
730
731
732
	  /*
	  rdate = gribRefDate(isec1);
	  rtime = gribRefTime(isec1);
	  tunit = cgribexGetTimeUnit(isec1);
	  fcast = gribTimeIsFC(isec1);
	  */
	}
      else
	{
	  datetime.date  = vdate;
	  datetime.time  = vtime;
	  compVar.code   = rcode;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
733
734
	  compVar.table  = table_num;
	  compVar.discipline = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
735
736
          compVar.level1 = level1;
          compVar.level2 = level2;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
737
738
	  compVar.ltype  = leveltype;

Uwe Schulzweida's avatar
Uwe Schulzweida committed
739
740
741
742
	  for ( recID = 0; recID < nrecs; recID++ )
	    {
	      compVar0.code   = streamptr->tsteps[0].records[recID].code;
	      compVar0.table  = streamptr->tsteps[0].records[recID].table;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
743
	      compVar0.discipline  = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
	      compVar0.level1 = streamptr->tsteps[0].records[recID].ilevel;
	      compVar0.level2 = streamptr->tsteps[0].records[recID].ilevel2;
	      compVar0.ltype  = streamptr->tsteps[0].records[recID].ltype;

	      if ( memcmp(&compVar0, &compVar, sizeof(compvar2_t)) == 0 ) break;
	    }

	  if ( cdiInventoryMode == 1 )
	    {
	      if ( recID < nrecs ) break;
	      if ( warn_time )
		if ( memcmp(&datetime, &datetime0, sizeof(DateTime)) != 0 )
		  {
		    Warning(func, "Inconsistent verification time (code %d level %d)", rcode, level1);
		    warn_time = FALSE;
		  }
	    }
	  else
	    {
	      if ( memcmp(&datetime, &datetime0, sizeof(DateTime)) != 0 ) break;

	      if ( recID < nrecs )
		{
		  Warning(func, "Code %d level %d already exist, skipped!", rcode, level1);
		  continue;
		}
	    }
	}
      /*
      if ( ISEC1_AvgNum )
	{
	  if (  taxis->numavg && warn_numavg && (taxis->numavg != ISEC1_AvgNum) )
	    {
	      Message(func, "Change numavg from %d to %d not allowed!",
		      taxis->numavg, ISEC1_AvgNum);
	      warn_numavg = FALSE;
	    }
	  else
	    {
	      taxis->numavg = ISEC1_AvgNum;
	    }
	}
      */
      nrecs++;

      if ( CDI_Debug )
	Message(func, "%4d %8d %4d  %8d %8d %6d", nrecs, (int)recpos, rcode, level1, vdate, vtime);

      gribapiAddRecord(streamID, rcode, gh, recsize, recpos, prec, ztype);
    }

  streamptr->rtsteps = 1;

  cdiGenVars(streamID);

  if ( fcast )
    {
      taxisID = taxisCreate(TAXIS_RELATIVE);
      taxis->type  = TAXIS_RELATIVE;
      taxis->rdate = rdate;
      taxis->rtime = rtime;
      taxis->unit  = tunit;
    }
  else
    {
      taxisID = taxisCreate(TAXIS_ABSOLUTE);
      taxis->type  = TAXIS_ABSOLUTE;
      taxis->unit  = tunit;
    }

  taxis->vdate = datetime0.date;
  taxis->vtime = datetime0.time;

  vlistID = streamInqVlist(streamID);
  vlistDefTaxis(vlistID, taxisID);

  nrecords = streamptr->tsteps[0].nallrecs;
  if ( nrecords < streamptr->tsteps[0].recordSize )
    {
      streamptr->tsteps[0].recordSize = nrecords;
      streamptr->tsteps[0].records =
      (RECORD *) realloc(streamptr->tsteps[0].records, nrecords*sizeof(RECORD));
    }

  streamptr->tsteps[0].recIDs = (int *) malloc(nrecords*sizeof(int));
  streamptr->tsteps[0].nrecs = nrecords;
  for ( recID = 0; recID < nrecords; recID++ )
    streamptr->tsteps[0].recIDs[recID] = recID;

  streamptr->record->buffer     = gribbuffer;
  streamptr->record->buffersize = buffersize;

  if ( streamptr->ntsteps == -1 )
    {
      tsID = tstepsNewEntry(streamID);
      if ( tsID != streamptr->rtsteps )
	Error(func, "Internal error. tsID = %d", tsID);

      streamptr->tsteps[tsID-1].next   = TRUE;
      streamptr->tsteps[tsID].position = recpos;
    }

  if ( streamptr->ntsteps == 1 )
    {
      if ( taxis->vdate == 0 && taxis->vtime == 0 )
	{
	  streamptr->ntsteps = 0;
	  for ( varID = 0; varID < streamptr->nvars; varID++ )
	    {
	      vlistDefVarTime(vlistID, varID, TIME_CONSTANT);
	    }
	}
    }
#else
  Error(func, "GRIB_API support not compiled in!");
#endif
}


int gribapiScanTimestep2(int streamID)
{
  static char func [] = "gribapiScanTimestep2";
  int status = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
867
868
869
870
871
872
#if  defined  (HAVE_LIBGRIB_API)
  off_t recpos = 0;
  unsigned char *gribbuffer = NULL;
  long buffersize = 0;
  int iret = 0, ipunp = 0, iword = 0;
  int fileID;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
873
  int table_num = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
  int rcode = 0, level1 = 0, level2 = 0, vdate = 0, vtime = 0;
  DateTime datetime, datetime0;
  int tsID;
  int varID, gridID;
  size_t readsize;
  int nrecords, nrecs, recID, rindex;
  long recsize = 0;
  int warn_numavg = TRUE;
  int taxisID = -1;
  TAXIS *taxis;
  int vlistID;
  long unzipsize;
  compvar2_t compVar, compVar0;
  stream_t *streamptr;
  grib_handle *gh = NULL;
  int leveltype;
  long editionNumber;
  long lpar;
  double dlevel = 0;

  streamptr = stream_to_pointer(streamID);

  stream_check_ptr(func, streamptr);

  streamptr->curTsID = 1;

  fileID  = streamInqFileID(streamID);
  vlistID = streamInqVlist(streamID);
  taxisID = vlistInqTaxis(vlistID);

  gribbuffer = (unsigned char *) streamptr->record->buffer;
  buffersize = streamptr->record->buffersize;
                                          
  tsID = streamptr->rtsteps;
  if ( tsID != 1 )
    Error(func, "Internal problem! unexpeceted timestep %d", tsID+1);

  taxis = &streamptr->tsteps[tsID].taxis;

  fileSetPos(fileID, streamptr->tsteps[tsID].position, SEEK_SET);

  cdiCreateRecords(streamID, tsID);

  nrecords = streamptr->tsteps[tsID].nallrecs;
  streamptr->tsteps[1].recIDs = (int *) malloc(nrecords*sizeof(int));
  streamptr->tsteps[1].nrecs = 0;
  for ( recID = 0; recID < nrecords; recID++ )
    streamptr->tsteps[1].recIDs[recID] = -1;
      
  for ( recID = 0; recID < nrecords; recID++ )
    {
      varID = streamptr->tsteps[0].records[recID].varID;
      streamptr->tsteps[tsID].records[recID].position = 
	streamptr->tsteps[0].records[recID].position;
      streamptr->tsteps[tsID].records[recID].size     = 
	streamptr->tsteps[0].records[recID].size;
    }

  rindex = 0;
  while ( TRUE )
    {
      if ( rindex > nrecords ) break;

      recsize = gribGetSize(fileID);
      recpos  = fileGetPos(fileID);
      if ( recsize == 0 )
	{
	  streamptr->ntsteps = 2;
	  break;
	}
      if ( recsize > buffersize )
	{
	  buffersize = recsize;
	  gribbuffer = (unsigned char *) realloc(gribbuffer, (size_t)buffersize);
	}

      readsize = recsize;
      status = gribRead(fileID, gribbuffer, &readsize);
      if ( status ) break;

      if ( gribGetZip(recsize, gribbuffer, &unzipsize) > 0 )
	{
	  unzipsize += 100; /* need 0 to 1 bytes for rounding of bds */
	  if ( (long) buffersize < unzipsize )
	    {
	      buffersize = unzipsize;
	      gribbuffer = (unsigned char *) realloc(gribbuffer, buffersize);
	    }
	}

      gh = grib_handle_new_from_message(NULL, (void *) gribbuffer, recsize);
      GRIB_CHECK(grib_set_double(gh, "missingValue", GRIB_MISSVAL), 0);

      GRIB_CHECK(grib_get_long(gh, "editionNumber", &editionNumber), 0);

      if ( editionNumber <= 1 )
	{
	  GRIB_CHECK(grib_get_long(gh, "indicatorOfParameter", &lpar), 0);
	  rcode = (int) lpar;
	  status = grib_get_long(gh, "indicatorOfTypeOfLevel", &lpar);
	  if ( status == 0 )
	    {
	      leveltype = (int) lpar;
	      GRIB_CHECK(grib_get_double(gh, "level", &dlevel), 0);
	      if ( leveltype == 100 ) dlevel *= 100;
	      if ( dlevel < -2.e9 || dlevel > 2.e9 ) dlevel = 0;
	    }
	  else 
	    {
	      leveltype = 0;
	      dlevel = 0;
	    }
	}
      else
	{
Uwe Schulzweida's avatar
Uwe Schulzweida committed
989
990
991
	  GRIB_CHECK(grib_get_long(gh, "parameterCategory", &lpar), 0);
	  table_num = (int) lpar;

Uwe Schulzweida's avatar
Uwe Schulzweida committed
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
	  GRIB_CHECK(grib_get_long(gh, "parameterNumber", &lpar), 0);
	  rcode = (int) lpar;
	  status = grib_get_long(gh, "typeOfFirstFixedSurface", &lpar);
	  if ( status == 0 )
	    {
	      leveltype = (int) lpar;
	      GRIB_CHECK(grib_get_double(gh, "level", &dlevel), 0);
	      if ( leveltype == 100 ) dlevel *= 100;
	      if ( dlevel < -2.e9 || dlevel > 2.e9 ) dlevel = 0;
	    }
	  else 
	    {
	      leveltype = 0;
	      dlevel = 0;
	    }
	}

      level1 = (int) dlevel;
      level2 = 0;

      GRIB_CHECK(grib_get_long(gh, "dataDate", &lpar), 0);
      vdate = (int) lpar;
      GRIB_CHECK(grib_get_long(gh, "dataTime", &lpar), 0);
      vtime = (int) lpar*100;

      if ( rindex == 0 )
	{
	  if ( taxisInqType(taxisID) == TAXIS_RELATIVE )
	    {
	      taxis->type  = TAXIS_RELATIVE;
	      taxis->rdate = 0;
	      taxis->rtime = 0;
	      taxis->unit  = 0;
	      /*
	      taxis->rdate = gribRefDate(isec1);
	      taxis->rtime = gribRefTime(isec1);
	      taxis->unit  = cgribexGetTimeUnit(isec1);
	      */
	    }
	  else
	    {
	      taxis->type  = TAXIS_ABSOLUTE;
	    }
	  taxis->vdate = vdate;
	  taxis->vtime = vtime;

	  datetime0.date = vdate;
	  datetime0.time = vtime;
	}
      /*
      if ( ISEC1_AvgNum )
	{
	  if (  taxis->numavg && warn_numavg &&
		(taxis->numavg != ISEC1_AvgNum) )
	    {
	      warn_numavg = FALSE;
	    }
	  else
	    {
	      taxis->numavg = ISEC1_AvgNum;
	    }
	}
      */
      datetime.date  = vdate;
      datetime.time  = vtime;
      compVar.code   = rcode;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1058
1059
      compVar.table  = table_num;
      compVar.discipline = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1060
1061
1062
1063
1064
1065
1066
      compVar.level1 = level1;
      compVar.level2 = level2;
      compVar.ltype  = leveltype;
      for ( recID = 0; recID < nrecords; recID++ )
	{
	  compVar0.code   = streamptr->tsteps[tsID].records[recID].code;
	  compVar0.table  = streamptr->tsteps[tsID].records[recID].table;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1067
	  compVar0.discipline = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
	  compVar0.level1 = streamptr->tsteps[tsID].records[recID].ilevel;
	  compVar0.level2 = streamptr->tsteps[tsID].records[recID].ilevel2;
	  compVar0.ltype  = streamptr->tsteps[tsID].records[recID].ltype;

	  if ( memcmp(&compVar0, &compVar, sizeof(compvar2_t)) == 0 ) break;
	}

      if ( recID == nrecords )
	{
	  Warning(func, "Code %d level %d not found at timestep %d!", rcode, level1, tsID+1);
	  return (CDI_EUFSTRUCT);
	}

      if ( cdiInventoryMode == 1 )
	{
	  if ( streamptr->tsteps[tsID].records[recID].used )
	    {
	      break;
	    }
	  else
	    {
	      streamptr->tsteps[tsID].records[recID].used = TRUE;
	      streamptr->tsteps[tsID].recIDs[rindex] = recID;
	    }    
	}
      else
	{
	  if ( streamptr->tsteps[tsID].records[recID].used )
	    {
	      if ( memcmp(&datetime, &datetime0, sizeof(DateTime)) != 0 ) break;

	      Warning(func, "Code %d level %d already exist, skipped!", rcode, level1);
	      continue;
	    }
	  else
	    {
	      streamptr->tsteps[tsID].records[recID].used = TRUE;
	      streamptr->tsteps[tsID].recIDs[rindex] = recID;
	    }    
	}

      if ( CDI_Debug )
	Message(func, "%4d %8d %4d %8d %8d %6d", rindex+1, (int)recpos, rcode, level1, vdate, vtime);

      streamptr->tsteps[tsID].records[recID].size = recsize;

      compVar0.code   = streamptr->tsteps[tsID].records[recID].code;
      compVar0.table  = streamptr->tsteps[tsID].records[recID].table;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1116
      compVar0.discipline = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
      compVar0.level1 = streamptr->tsteps[tsID].records[recID].ilevel;
      compVar0.level2 = streamptr->tsteps[tsID].records[recID].ilevel2;
      compVar0.ltype  = streamptr->tsteps[tsID].records[recID].ltype;

      if ( memcmp(&compVar0, &compVar, sizeof(compvar2_t)) != 0 )
	{
	  Message(func, "tsID = %d recID = %d code = %3d new %3d  level = %3d new %3d",
		  tsID, recID,
		  streamptr->tsteps[tsID].records[recID].code, rcode,
		  streamptr->tsteps[tsID].records[recID].ilevel, level1);
	  return (CDI_EUFSTRUCT);
	}

      streamptr->tsteps[1].records[recID].position = recpos;
      varID = streamptr->tsteps[tsID].records[recID].varID;
      gridID = vlistInqVarGrid(vlistID, varID);
      /*
      if ( gridInqSize(gridID) == 1 && gridInqType(gridID) == GRID_LONLAT )
	{
	  if ( IS_NOT_EQUAL(gridInqXval(gridID, 0),ISEC2_FirstLon*0.001) ||
	       IS_NOT_EQUAL(gridInqYval(gridID, 0),ISEC2_FirstLat*0.001) )
	    gridChangeType(gridID, GRID_TRAJECTORY);
	}
      */
      rindex++;
    }

  nrecs = 0;
  for ( recID = 0; recID < nrecords; recID++ )
    {
      if ( ! streamptr->tsteps[tsID].records[recID].used )
	{
	  varID = streamptr->tsteps[tsID].records[recID].varID;
	  vlistDefVarTime(vlistID, varID, TIME_CONSTANT);
	}
      else
	{
	  nrecs++;
	}
    }
  streamptr->tsteps[tsID].nrecs = nrecs;

  streamptr->rtsteps = 2;

  if ( streamptr->ntsteps == -1 )
    {
      tsID = tstepsNewEntry(streamID);
      if ( tsID != streamptr->rtsteps )
	Error(func, "Internal error. tsID = %d", tsID);

      streamptr->tsteps[tsID-1].next   = TRUE;
      streamptr->tsteps[tsID].position = recpos;
    }

  streamptr->record->buffer     = gribbuffer;
  streamptr->record->buffersize = buffersize;
#else
  Error(func, "GRIB_API support not compiled in!");
#endif
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1176
1177
1178
1179
1180
1181
1182
1183
1184

  return (status);
}


int gribapiScanTimestep(int streamID)
{
  static char func [] = "gribapiScanTimestep";
  int status = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1185
1186
1187
1188
1189
1190
1191
#if  defined  (HAVE_LIBGRIB_API)
  long recsize = 0;
  off_t recpos = 0;
  unsigned char *gribbuffer;
  long buffersize = 0;
  int iret = 0, ipunp = 0, iword = 0;
  int fileID;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1192
  int table_num = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
  int rcode = 0, level1 = 0, level2 = 0, vdate = 0, vtime = 0;
  DateTime datetime, datetime0;
  int tsID;
  int vrecID, recID;
  int warn_numavg = TRUE;
  size_t readsize;
  int taxisID = -1;
  TAXIS *taxis;
  int vlistID;
  int rindex, nrecs = 0;
  long unzipsize;
  compvar2_t compVar, compVar0;
  stream_t *streamptr;
  grib_handle *gh = NULL;
  int leveltype;
  long editionNumber;
  long lpar;
  double dlevel = 0;

  streamptr = stream_to_pointer(streamID);

  stream_check_ptr(func, streamptr);

  vlistID = streamInqVlist(streamID);

  if ( CDI_Debug )
    {
      Message(func, "streamID = %d", streamID);
      Message(func, "cts = %d", streamptr->curTsID);
      Message(func, "rts = %d", streamptr->rtsteps);
      Message(func, "nts = %d", streamptr->ntsteps);
    }

  tsID  = streamptr->rtsteps;
  taxis = &streamptr->tsteps[tsID].taxis;

  if ( streamptr->tsteps[tsID].recordSize == 0 )
    {
      gribbuffer = (unsigned char *) streamptr->record->buffer;
      buffersize = streamptr->record->buffersize;

      cdiCreateRecords(streamID, tsID);

      nrecs = streamptr->tsteps[1].nrecs;

      streamptr->tsteps[tsID].nrecs = nrecs;
      streamptr->tsteps[tsID].recIDs = (int *) malloc(nrecs*sizeof(int));
      for ( recID = 0; recID < nrecs; recID++ )
	streamptr->tsteps[tsID].recIDs[recID] = streamptr->tsteps[1].recIDs[recID];

      fileID = streamInqFileID(streamID);

      fileSetPos(fileID, streamptr->tsteps[tsID].position, SEEK_SET);

      rindex = 0;
      while ( TRUE )
	{
	  if ( rindex > nrecs ) break;

	  recsize = gribGetSize(fileID);
	  recpos  = fileGetPos(fileID);
	  if ( recsize == 0 )
	    {
	      streamptr->ntsteps = streamptr->rtsteps + 1;
	      break;
	    }
	  if ( recsize > buffersize )
	    {
	      buffersize = recsize;
	      gribbuffer = (unsigned char *) realloc(gribbuffer, buffersize);
	    }

	  readsize = recsize;
	  status = gribRead(fileID, gribbuffer, &readsize);
	  if ( status )
	    {
	      Error(func, "Inconsistent timestep %d (GRIB record %d/%d)!\n", tsID+1, rindex+1,
		    streamptr->tsteps[tsID].recordSize);
	      break;
	    }

	  if ( gribGetZip(recsize, gribbuffer, &unzipsize) > 0 )
	    {
	      unzipsize += 100; /* need 0 to 1 bytes for rounding of bds */
	      if ( (long) buffersize < unzipsize )
		{
		  buffersize = unzipsize;
		  gribbuffer = (unsigned char *) realloc(gribbuffer, buffersize);
		}
	    }

	  gh = grib_handle_new_from_message(NULL, (void *) gribbuffer, recsize);
	  GRIB_CHECK(grib_set_double(gh, "missingValue", GRIB_MISSVAL), 0);

	  GRIB_CHECK(grib_get_long(gh, "editionNumber", &editionNumber), 0);

	  if ( editionNumber <= 1 )
	    {
	      GRIB_CHECK(grib_get_long(gh, "indicatorOfParameter", &lpar), 0);
	      rcode = (int) lpar;
	      status = grib_get_long(gh, "indicatorOfTypeOfLevel", &lpar);
	      if ( status == 0 )
		{
		  leveltype = (int) lpar;
		  GRIB_CHECK(grib_get_double(gh, "level", &dlevel), 0);
		  if ( leveltype == 100 ) dlevel *= 100;
		  if ( dlevel < -2.e9 || dlevel > 2.e9 ) dlevel = 0;
		}
	      else 
		{
		  leveltype = 0;
		  dlevel = 0;
		}
	    }
	  else
	    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1309
1310
1311
	      GRIB_CHECK(grib_get_long(gh, "parameterCategory", &lpar), 0);
	      table_num = (int) lpar;

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
	      GRIB_CHECK(grib_get_long(gh, "parameterNumber", &lpar), 0);
	      rcode = (int) lpar;
	      status = grib_get_long(gh, "typeOfFirstFixedSurface", &lpar);
	      if ( status == 0 )
		{
		  leveltype = (int) lpar;
		  GRIB_CHECK(grib_get_double(gh, "level", &dlevel), 0);
		  if ( leveltype == 100 ) dlevel *= 100;
		  if ( dlevel < -2.e9 || dlevel > 2.e9 ) dlevel = 0;
		}
	      else 
		{
		  leveltype = 0;
		  dlevel = 0;
		}
	    }

	  level1 = (int) dlevel;
	  level2 = 0;

	  GRIB_CHECK(grib_get_long(gh, "dataDate", &lpar), 0);
	  vdate = (int) lpar;
	  GRIB_CHECK(grib_get_long(gh, "dataTime", &lpar), 0);
	  vtime = (int) lpar*100;

	  if ( rindex == nrecs ) break;

	  if ( rindex == 0 )
	    {
	      taxisID = vlistInqTaxis(vlistID);
	      if ( taxisInqType(taxisID) == TAXIS_RELATIVE )
		{
		  taxis->type  = TAXIS_RELATIVE;
		  taxis->rdate = 0;
		  taxis->rtime = 0;
		  taxis->unit  = 0;
		  /*
		    taxis->rdate = gribRefDate(isec1);
		    taxis->rtime = gribRefTime(isec1);
		    taxis->unit  = cgribexGetTimeUnit(isec1);
		  */
		}
	      else
		{
		  taxis->type  = TAXIS_ABSOLUTE;
		}
	      taxis->vdate = vdate;
	      taxis->vtime = vtime;

	      datetime0.date = vdate;
	      datetime0.time = vtime;
	    }
	  /*
	  if ( ISEC1_AvgNum )
	    {
	      if (  taxis->numavg && warn_numavg &&
		   (taxis->numavg != ISEC1_AvgNum) )
		{
		  warn_numavg = FALSE;
		}
	      else
		{
		  taxis->numavg = ISEC1_AvgNum;
		}
	    }
	  */
	  datetime.date  = vdate;
	  datetime.time  = vtime;
	  compVar.code   = rcode;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1381
1382
	  compVar.table  = table_num;
	  compVar.discipline = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1383
1384
1385
1386
1387
1388
1389
1390
          compVar.level1 = level1;
          compVar.level2 = level2;
          compVar.ltype  = leveltype;
	  for ( vrecID = 0; vrecID < nrecs; vrecID++ )
	    {
	      recID   = streamptr->tsteps[1].recIDs[vrecID];
	      compVar0.code   = streamptr->tsteps[tsID].records[recID].code;
	      compVar0.table  = streamptr->tsteps[tsID].records[recID].table;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1391
	      compVar0.discipline = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
	      compVar0.level1 = streamptr->tsteps[tsID].records[recID].ilevel;
	      compVar0.level2 = streamptr->tsteps[tsID].records[recID].ilevel2;
	      compVar0.ltype  = streamptr->tsteps[tsID].records[recID].ltype;

	      if ( memcmp(&compVar0, &compVar, sizeof(compvar2_t)) == 0 ) break;
	    }

	  if ( vrecID == nrecs )
	    {
	      Warning(func, "Code %d level %d not available at timestep %d!",
		      rcode, level1, tsID+1);

	      if ( cdiInventoryMode == 1 )
		return (CDI_EUFSTRUCT);
	      else
		continue;
	    }

	  if ( cdiInventoryMode == 1 )
	    {
	      streamptr->tsteps[tsID].records[recID].used = TRUE;
	      streamptr->tsteps[tsID].recIDs[rindex] = recID;
	    }
	  else
	    {
	      if ( streamptr->tsteps[tsID].records[recID].used )
		{
		  if ( memcmp(&datetime, &datetime0, sizeof(DateTime)) != 0 ) break;
		  
		  if ( CDI_Debug )
		    Warning(func, "Code %d level %d already exist, skipped!", rcode, level1);

		  continue;
		}
	      else
		{
		  streamptr->tsteps[tsID].records[recID].used = TRUE;
		  streamptr->tsteps[tsID].recIDs[rindex] = recID;
		}    
	    }

	  if ( CDI_Debug )
	    Message(func, "%4d %8d %4d %8d %8d %6d", rindex+1, (int)recpos, rcode, level1, vdate, vtime);

	  compVar0.code   = streamptr->tsteps[tsID].records[recID].code;
	  compVar0.table  = streamptr->tsteps[tsID].records[recID].table;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1438
	  compVar0.discipline = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
	  compVar0.level1 = streamptr->tsteps[tsID].records[recID].ilevel;
	  compVar0.level2 = streamptr->tsteps[tsID].records[recID].ilevel2;
	  compVar0.ltype  = streamptr->tsteps[tsID].records[recID].ltype;

	  if ( memcmp(&compVar0, &compVar, sizeof(compvar2_t)) != 0 )
	    {
	      Message(func, "tsID = %d recID = %d code = %3d new %3d  level = %3d new %3d",
		      tsID, recID,
		      streamptr->tsteps[tsID].records[recID].code, rcode,
		      streamptr->tsteps[tsID].records[recID].ilevel, level1);
	      Error(func, "Invalid, unsupported or inconsistent record structure");
	    }
	  
	  streamptr->tsteps[tsID].records[recID].position = recpos;
	  streamptr->tsteps[tsID].records[recID].size = recsize;

	  if ( CDI_Debug )
	    Message(func, "%4d %8d %4d %8d %8d %6d", rindex, (int)recpos, rcode, level1, vdate, vtime);

	  rindex++;
	}

      for ( vrecID = 0; vrecID < nrecs; vrecID++ )
	{
	  recID   = streamptr->tsteps[tsID].recIDs[vrecID];
	  if ( ! streamptr->tsteps[tsID].records[recID].used ) break;
	}

      if ( vrecID < nrecs )
	{
	  Warning(func, "Code %d level %d not found at timestep %d!",
		  streamptr->tsteps[tsID].records[recID].code,
		  streamptr->tsteps[tsID].records[recID].ilevel,
		  tsID+1);
	  return (CDI_EUFSTRUCT);
	}

      streamptr->rtsteps++;

      if ( streamptr->ntsteps != streamptr->rtsteps )
	{
	  tsID = tstepsNewEntry(streamID);
	  if ( tsID != streamptr->rtsteps )
	    Error(func, "Internal error. tsID = %d", tsID);

	  streamptr->tsteps[tsID-1].next   = 1;
	  streamptr->tsteps[tsID].position = recpos;
	}

      fileSetPos(fileID, streamptr->tsteps[tsID].position, SEEK_SET);
      streamptr->tsteps[tsID].position = recpos;

      streamptr->record->buffer     = gribbuffer;
      streamptr->record->buffersize = buffersize;
    }

  if ( nrecs > 0 && nrecs < streamptr->tsteps[tsID].nrecs )
    {
      Warning(func, "Incomplete timestep. Stop scanning at timestep %d.\n", tsID);
      streamptr->ntsteps = tsID;
    }

  status = streamptr->ntsteps;
#else
  Error(func, "GRIB_API support not compiled in!");
#endif
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515

  return (status);
}


int gribapiDecode(unsigned char *gribbuffer, int gribsize, double *data, int gridsize,
		  int unreduced, int *nmiss, int *zip)
{
  static char func[] = "gribapiDecode";
  int status = 0;
#if  defined  (HAVE_LIBGRIB_API)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
  long lpar;
  long editionNumber, numberOfPoints;
  size_t datasize, dummy, recsize;
  grib_handle *gh = NULL;

  if ( unreduced )
    {
      static int lwarn = 1;

      if ( lwarn )
	{
	  lwarn = 0;
	  Warning(func, "Conversion of gaussian reduced grids unsupported!\n");
	}
    }

  recsize = gribsize;
  gh = grib_handle_new_from_message(NULL, (void *) gribbuffer, recsize);
  GRIB_CHECK(grib_set_double(gh, "missingValue", GRIB_MISSVAL), 0);

  GRIB_CHECK(grib_get_long(gh, "editionNumber", &editionNumber), 0);

  /* get the size of the values array*/
  GRIB_CHECK(grib_get_size(gh, "values", &datasize), 0);
  GRIB_CHECK(grib_get_long(gh, "numberOfPoints", &numberOfPoints), 0);

  // printf("values_size = %d  numberOfPoints = %ld\n", datasize, numberOfPoints);

  if ( gridsize != (int) datasize )
    Error(func, "Internal problem: gridsize(%d) != datasize(%d)!\n", gridsize, datasize);
  dummy = datasize;
  GRIB_CHECK(grib_get_double_array(gh, "values", data, &dummy), 0);

  int gridtype;
  GRIB_CHECK(grib_get_long(gh, "gridDefinitionTemplateNumber", &lpar), 0);
  gridtype = (int) lpar;

  *nmiss = 0;
  if ( gridtype < 50 || gridtype > 53 )
    {
      GRIB_CHECK(grib_get_long(gh, "numberOfMissing", &lpar), 0);
      *nmiss = (int) lpar;
      // printf("gridtype %d, nmiss %d\n", gridtype, nmiss);
    }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
#else
  Error(func, "GRIB_API support not compiled in!");
#endif

  return (status);
}


#if  defined  (HAVE_LIBGRIB_API)
static
void gribapiDefInstitut(grib_handle *gh, int vlistID, int varID)
{
  int instID;

  if ( vlistInqInstitut(vlistID) != CDI_UNDEFID )
    instID = vlistInqInstitut(vlistID);
  else
    instID = vlistInqVarInstitut(vlistID, varID);

  if ( instID != CDI_UNDEFID )
    {
      int center, subcenter;
      center    = institutInqCenter(instID);
      subcenter = institutInqSubcenter(instID);
      GRIB_CHECK(grib_set_long(gh, "centre", center), 0);
      GRIB_CHECK(grib_set_long(gh, "subCentre", subcenter), 0);
    }
}

static
void gribapiDefModel(grib_handle *gh, int vlistID, int varID)
{
  int modelID;

  if ( vlistInqModel(vlistID) != CDI_UNDEFID )
    modelID = vlistInqModel(vlistID);
  else
    modelID = vlistInqVarModel(vlistID, varID);

  if ( modelID != CDI_UNDEFID )
    GRIB_CHECK(grib_set_long(gh, "generatingProcessIdentifier", modelInqGribID(modelID)), 0);
}

static
void gribapiDefCode(grib_handle *gh, int code, int codetable)
{
  //ISEC1_CodeTable = codetable;
  if ( code < 0 ) code = -code;
  // GRIB_CHECK(grib_set_long(gh, "indicatorOfParameter", code), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1609
1610
  GRIB_CHECK(grib_set_long(gh, "discipline", 255), 0);
  GRIB_CHECK(grib_set_long(gh, "parameterCategory", codetable), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1611
  GRIB_CHECK(grib_set_long(gh, "parameterNumber", code), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
}

static
void gribapiDefTime(grib_handle *gh , int date, int time, int numavg, int timeID)
{
  GRIB_CHECK(grib_set_long(gh, "dataDate", date), 0);
  GRIB_CHECK(grib_set_long(gh, "dataTime", time/100), 0);
}

static
void gribapiDefGrid(grib_handle *gh, int gridID)
{
  static char func[] = "gribapiDefGrid";
  int gridtype;
  static short lwarn = TRUE;

  // ISEC1_Sec2Or3Flag = 128;
  
  gridtype = gridInqType(gridID);

  // ISEC1_GridDefinition = 255;

  if ( gridtype == GRID_GENERIC )
    {
      int xsize, ysize;

      xsize = gridInqXsize(gridID);
      ysize = gridInqYsize(gridID);

      if ( (ysize == 32  || ysize == 48 || ysize == 64 ||
	    ysize == 96  || ysize == 160) && 
	   (xsize == 2*ysize || xsize == 1) )
	{
	  gridtype = GRID_GAUSSIAN;
	  gridChangeType(gridID, gridtype);
	}
      else if ( xsize == 1 && ysize == 1 )
	{
	  gridtype = GRID_LONLAT;
	  gridChangeType(gridID, gridtype);
	}
      else if ( gridInqXvals(gridID, NULL) && gridInqYvals(gridID, NULL) )
	{
	  gridtype = GRID_LONLAT;
	  gridChangeType(gridID, gridtype);
	}
    }
  else if ( gridtype == GRID_CURVILINEAR )
    {
      if ( lwarn )
	{
	  lwarn = FALSE;
	  Warning(func, "Curvilinear grids are unsupported in GRIB format! Created wrong GDS!");
	}
      gridtype = GRID_LONLAT;
    }

  // ISEC2_Reduced = FALSE;

  // ISEC2_ScanFlag = 0;

  switch (gridtype)
    {
    case GRID_LONLAT:
    case GRID_GAUSSIAN:
    case GRID_GAUSSIAN_REDUCED:
    case GRID_TRAJECTORY:
      {
	int nlon = 0, nlat;
	double latIncr;
	size_t len;

	if ( gridtype == GRID_GAUSSIAN_REDUCED )
	  {
	    //  ISEC2_Reduced = TRUE;
	    nlon = 0;
	    // gridInqRowlon(gridID, ISEC2_RowLonPtr);
	  }
	else
	  {
	    nlon = gridInqXsize(gridID);
	  }

	nlat = gridInqYsize(gridID);
	if ( gridtype == GRID_GAUSSIAN || gridtype == GRID_GAUSSIAN_REDUCED )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1697
	  GRIB_CHECK(grib_set_long(gh, "gridDefinitionTemplateNumber", GRIBAPI_GTYPE_GAUSSIAN), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1698
	else if ( gridtype == GRID_LONLAT && gridIsRotated(gridID) )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1699
	  GRIB_CHECK(grib_set_long(gh, "gridDefinitionTemplateNumber", GRIBAPI_GTYPE_LATLON_ROT), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1700
	else
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1701
1702
	  GRIB_CHECK(grib_set_long(gh, "gridDefinitionTemplateNumber", GRIBAPI_GTYPE_LATLON), 0);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
	GRIB_CHECK(grib_set_long(gh, "Ni", nlon), 0);
	GRIB_CHECK(grib_set_long(gh, "Nj", nlat), 0);
	GRIB_CHECK(grib_set_double(gh, "latitudeOfFirstGridPointInDegrees",  gridInqYval(gridID,      0)), 0);
	GRIB_CHECK(grib_set_double(gh, "latitudeOfLastGridPointInDegrees",   gridInqYval(gridID, nlat-1)), 0);
	GRIB_CHECK(grib_set_double(gh, "longitudeOfFirstGridPointInDegrees", gridInqXval(gridID,      0)), 0);
	GRIB_CHECK(grib_set_double(gh, "longitudeOfLastGridPointInDegrees",  gridInqXval(gridID, nlon-1)), 0);
	GRIB_CHECK(grib_set_double(gh, "iDirectionIncrementInDegrees", gridInqXinc(gridID)), 0);
	/*
	if ( fabs(gridInqXinc(gridID)*1000 - ISEC2_LonIncr) > FLT_EPSILON )
	  ISEC2_LonIncr = 0;
	*/
	if ( gridtype == GRID_GAUSSIAN )
	  GRIB_CHECK(grib_set_long(gh, "numberOfParallelsBetweenAPoleAndTheEquator", nlat/2), 0);
	else
	  {
	    latIncr = gridInqYinc(gridID);
	    if ( latIncr < 0 ) latIncr = -latIncr;
	    GRIB_CHECK(grib_set_double(gh, "jDirectionIncrementInDegrees", latIncr), 0);
	    /*
	    if ( fabs(gridInqYinc(gridID)*1000 - ISEC2_LatIncr) > FLT_EPSILON )
	      ISEC2_LatIncr = 0;
	    */
	  }
	/*
	if ( ISEC2_NumLon > 1 && ISEC2_NumLat == 1 ) 
	  if ( ISEC2_LonIncr != 0 && ISEC2_LatIncr == 0 ) ISEC2_LatIncr = ISEC2_LonIncr;

	if ( ISEC2_NumLon == 1 && ISEC2_NumLat > 1 ) 
	  if ( ISEC2_LonIncr == 0 && ISEC2_LatIncr != 0 ) ISEC2_LonIncr = ISEC2_LatIncr;

	if ( ISEC2_LatIncr == 0 || ISEC2_LonIncr == 0 )
	  ISEC2_ResFlag = 0;
	else
	  ISEC2_ResFlag = 128;

	if ( gridIsRotated(gridID) )
	  {
	    ISEC2_LatSP = - NINT(gridInqYpole(gridID) * 1000);
	    ISEC2_LonSP =   NINT((gridInqXpole(gridID) + 180) * 1000);
	  }
	*/

	/* East -> West */
	//if ( ISEC2_LastLon < ISEC2_FirstLon ) ISEC2_ScanFlag += 128;

	/* South -> North */
	//if ( ISEC2_LastLat > ISEC2_FirstLat ) ISEC2_ScanFlag += 64;

	GRIB_CHECK(grib_set_string(gh, "typeOfPacking", "grid_simple", &len), 0);

	break;
      }
      /*
    case GRID_LCC:
      {
	double originLon, originLat, lonParY, lat1, lat2, xincm, yincm;
	int xsize, ysize;
	int projflag, scanflag;

	xsize = gridInqXsize(gridID);
	ysize = gridInqYsize(gridID);

	gridInqLCC(gridID, &originLon, &originLat, &lonParY, &lat1, &lat2, &xincm, &yincm,
		   &projflag, &scanflag);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1768
	ISEC2_GridType = GRIBAPI_GTYPE_LCC;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
	ISEC2_NumLon   = xsize;
	ISEC2_NumLat   = ysize;
	ISEC2_FirstLon = NINT(originLon * 1000);
	ISEC2_FirstLat = NINT(originLat * 1000);
	ISEC2_Lambert_Lov    = NINT(lonParY * 1000);
	ISEC2_Lambert_LatS1  = NINT(lat1 * 1000);
	ISEC2_Lambert_LatS2  = NINT(lat2 * 1000);
	ISEC2_Lambert_dx     = NINT(xincm);
	ISEC2_Lambert_dy     = NINT(yincm);
	ISEC2_Lambert_LatSP  = 0;
	ISEC2_Lambert_LatSP  = 0;
	ISEC2_Lambert_ProjFlag = projflag;
	ISEC2_ScanFlag = scanflag;

	break;
      }
      */
    case GRID_SPECTRAL:
      {
	int trunc = gridInqTrunc(gridID);
	size_t len = 15;

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1791
	GRIB_CHECK(grib_set_long(gh, "gridDefinitionTemplateNumber", GRIBAPI_GTYPE_SPECTRAL), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1792
1793
1794
1795
	GRIB_CHECK(grib_set_long(gh, "J", trunc), 0);
	GRIB_CHECK(grib_set_long(gh, "K", trunc), 0);
	GRIB_CHECK(grib_set_long(gh, "M", trunc), 0);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1796
1797
1798
	GRIB_CHECK(grib_set_long(gh, "numberOfDataPoints", gridInqSize(gridID)), 0);
	GRIB_CHECK(grib_set_long(gh, "numberOfValues", gridInqSize(gridID)), 0);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
	GRIB_CHECK(grib_set_string(gh, "typeOfPacking", "spectral_simple", &len), 0);
	/*
	ISEC2_RepType  = 1;
	ISEC2_RepMode  = 1;
	*/
	break;
      }
      /*
    case GRID_GME:
      {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1809
	ISEC2_GridType   = GRIBAPI_GTYPE_GME;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
	ISEC2_GME_ND     = gridInqGMEnd(gridID);
	ISEC2_GME_NI     = gridInqGMEni(gridID);
	ISEC2_GME_NI2    = gridInqGMEni2(gridID);
	ISEC2_GME_NI3    = gridInqGMEni3(gridID);
	ISEC2_GME_AFlag  = 0;
	ISEC2_GME_LatPP  = 90000;
	ISEC2_GME_LonPP  = 0;
	ISEC2_GME_LonMPL = 0;
	ISEC2_GME_BFlag  = 0;
	break;
      }
      */
    default:
      Error(func, "%s grid unsupported!", gridNamePtr(gridtype));
    }
}

static
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1828
void gribapiDefLevel(grib_handle *gh, int code, int zaxisID, int levelID)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1829
1830
1831
{
  static char func[] = "gribapiDefLevel";
  double level;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1832
  int zaxistype, ltype;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
  static int warning = 1;

  zaxistype = zaxisInqType(zaxisID);
  ltype = zaxisInqLtype(zaxisID);

  if ( zaxistype == ZAXIS_GENERIC && ltype == 0 )
    {
      zaxistype = ZAXIS_PRESSURE;
      zaxisChangeType(zaxisID, zaxistype);
    }

  // ISEC2_NumVCP = 0;

  switch (zaxistype)
    {
    case ZAXIS_SURFACE:
      {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1850
1851
1852
	GRIB_CHECK(grib_set_long(gh, "typeOfFirstFixedSurface", GRIBAPI_LTYPE_SURFACE), 0);
	//GRIB_CHECK(grib_set_long(gh, "scaleFactorOfFirstFixedSurface", 0), 0);
	//GRIB_CHECK(grib_set_long(gh, "scaledValueOfFirstFixedSurface", 0), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1853
1854
1855
1856
1857
1858
1859
1860
1861
	GRIB_CHECK(grib_set_long(gh, "level", (long) zaxisInqLevel(zaxisID, levelID)), 0);
	/*
	ISEC1_Level1    = (int) zaxisInqLevel(zaxisID, levelID);
	ISEC1_Level2    = 0;
	*/
	break;
      }
    case ZAXIS_MEANSEA:
      {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1862
1863
1864
1865
1866
	level = zaxisInqLevel(zaxisID, levelID);

	GRIB_CHECK(grib_set_long(gh, "typeOfFirstFixedSurface", GRIBAPI_LTYPE_MEANSEA), 0);
	GRIB_CHECK(grib_set_double(gh, "level", level), 0);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1867
1868
1869
1870
1871
1872
1873
	break;
      }
    case ZAXIS_HYBRID:
    case ZAXIS_HYBRID_HALF:
      {
	int vctsize;

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1874
	GRIB_CHECK(grib_set_long(gh, "typeOfFirstFixedSurface", GRIBAPI_LTYPE_HYBRID), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
	if ( zaxisInqLbounds(zaxisID, NULL) && zaxisInqUbounds(zaxisID, NULL) )
	  {
	    GRIB_CHECK(grib_set_long(gh, "level", (long) zaxisInqLevel(zaxisID, levelID)), 0);
	    Error(func, "hybrid_half model level code missing!");
	    /*
	    ISEC1_Level1    = (int) zaxisInqLbound(zaxisID, levelID);
	    ISEC1_Level2    = (int) zaxisInqUbound(zaxisID, levelID);
	    */
	  }
	else
	  {
	    GRIB_CHECK(grib_set_long(gh, "level", (long) zaxisInqLevel(zaxisID, levelID)), 0);
	  }

	vctsize = zaxisInqVctSize(zaxisID);
	if ( vctsize == 0 && warning )
	  {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1892
	    Warning(func, "VCT missing. ( code = %d, zaxisID = %d )", code, zaxisID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1893
1894
	    warning = 0;
	  }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1895
1896
	GRIB_CHECK(grib_set_long(gh, "PVPresent", 1), 0);
	GRIB_CHECK(grib_set_double_array(gh, "pv", zaxisInqVctPtr(zaxisID), vctsize), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913

	break;
      }
    case ZAXIS_PRESSURE:
      {
	char units[128];

	level = zaxisInqLevel(zaxisID, levelID);
	if ( level < 0 )
	  Warning(func, "pressure level of %f Pa is below 0.", level);

	zaxisInqUnits(zaxisID, units);
	if ( memcmp(units, "hPa", 3) == 0 || memcmp(units, "mb",2 ) == 0 )
	  level = level;
	else
	  level /= 100;

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1914
	GRIB_CHECK(grib_set_long(gh, "typeOfFirstFixedSurface", GRIBAPI_LTYPE_ISOBARIC), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1915
	GRIB_CHECK(grib_set_double(gh, "level", level), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1916

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1917
1918
1919
1920
1921
1922
	break;
      }
    case ZAXIS_HEIGHT:
      {
	level = zaxisInqLevel(zaxisID, levelID);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1923
1924
	GRIB_CHECK(grib_set_long(gh, "typeOfFirstFixedSurface", GRIBAPI_LTYPE_HEIGHT), 0);
	GRIB_CHECK(grib_set_double(gh, "level", level), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1925
1926
1927
1928
1929
1930
1931

	break;
      }
    case ZAXIS_ALTITUDE:
      {
	level = zaxisInqLevel(zaxisID, levelID);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1932
1933
	GRIB_CHECK(grib_set_long(gh, "typeOfFirstFixedSurface", GRIBAPI_LTYPE_ALTITUDE), 0);
	GRIB_CHECK(grib_set_double(gh, "level", level), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1934
1935
1936
1937
1938
1939
1940

	break;
      }
    case ZAXIS_SIGMA:
      {
	level = zaxisInqLevel(zaxisID, levelID);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1941
1942
	GRIB_CHECK(grib_set_long(gh, "typeOfFirstFixedSurface", GRIBAPI_LTYPE_SIGMA), 0);
	GRIB_CHECK(grib_set_double(gh, "level", level), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1943
1944
1945
1946
1947
1948
1949

	break;
      }
    case ZAXIS_DEPTH_BELOW_LAND:
      {
	if ( zaxisInqLbounds(zaxisID, NULL) && zaxisInqUbounds(zaxisID, NULL) )
	  {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1950
1951
1952
1953
1954
1955
	    GRIB_CHECK(grib_set_long(gh, "typeOfFirstFixedSurface", GRIBAPI_LTYPE_LANDDEPTH), 0);
	    GRIB_CHECK(grib_set_double(gh, "level", zaxisInqLbound(zaxisID, levelID)), 0);
	    GRIB_CHECK(grib_set_long(gh, "typeOfSecondFixedSurface", GRIBAPI_LTYPE_LANDDEPTH), 0);
	    GRIB_CHECK(grib_set_double(gh, "level", zaxisInqUbound(zaxisID, levelID)), 0);
	    /*
	    ISEC1_LevelType = GRIBAPI_LTYPE_LANDDEPTH_LAYER;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1956
1957
	    ISEC1_Level1    = (int) zaxisInqLbound(zaxisID, levelID);
	    ISEC1_Level2    = (int) zaxisInqUbound(zaxisID, levelID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1958
	    */
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1959
1960
1961
1962
1963
	  }
	else
	  {
	    level = zaxisInqLevel(zaxisID, levelID);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1964
1965
	    GRIB_CHECK(grib_set_long(gh, "typeOfFirstFixedSurface", GRIBAPI_LTYPE_LANDDEPTH), 0);
	    GRIB_CHECK(grib_set_double(gh, "level", level), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1966
1967
1968
1969
1970
1971
1972
1973
	  }

	break;
      }
    case ZAXIS_DEPTH_BELOW_SEA:
      {
	level = zaxisInqLevel(zaxisID, levelID);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1974
1975
	GRIB_CHECK(grib_set_long(gh, "typeOfFirstFixedSurface", GRIBAPI_LTYPE_SEADEPTH), 0);
	GRIB_CHECK(grib_set_double(gh, "level", level), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1976
1977
1978
1979
1980
1981
1982

	break;
      }
    case ZAXIS_ISENTROPIC:
      {
	level = zaxisInqLevel(zaxisID, levelID);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1983
1984
	GRIB_CHECK(grib_set_long(gh, "typeOfFirstFixedSurface", GRIBAPI_LTYPE_ISENTROPIC), 0);
	GRIB_CHECK(grib_set_double(gh, "level", level), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1985
1986
1987
1988
1989
1990
1991

	break;
      }
    case ZAXIS_GENERIC:
      {
	level = zaxisInqLevel(zaxisID, levelID);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1992
1993
	GRIB_CHECK(grib_set_long(gh, "typeOfFirstFixedSurface", ltype), 0);
	GRIB_CHECK(grib_set_double(gh, "level", level), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015

	break;
      }
    default:
      {
	Error(func, "zaxistype >%s< unsupported", zaxisNamePtr(zaxistype));
	break;
      }
    }
}
#endif


size_t gribapiEncode(int varID, int levelID, int vlistID, int gridID, int zaxisID, int date, int time, int numavg, 
		     long datasize, const double *data, int nmiss, unsigned char *gribbuffer, size_t gribbuffersize)
{
  static char func[] = "gribapiEncode";
  size_t nbytes = 0;
#if  defined  (HAVE_LIBGRIB_API)
  size_t recsize = 0;
  void *dummy = NULL;
  long edition = 2;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
2016
  int datatype;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
2017
2018
2019
2020
2021
2022
  int code, tableID;
  long bitsPerValue;
  grib_handle *gh = NULL;

  code    = vlistInqVarCode(vlistID, varID);
  tableID = vlistInqVarTable(vlistID, varID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
2023
  datatype = vlistInqVarDatatype(vlistID, varID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
2024
2025

  gh = grib_handle_new_from_template(NULL, "GRIB2");
Uwe Schulzweida's avatar
Uwe Schulzweida committed
2026
2027
  if ( gh == NULL ) Error(func, "grib_handle_new_from_template failed!");
  
Uwe Schulzweida's avatar
Uwe Schulzweida committed
2028
2029
2030
2031
2032
2033
2034
2035
  GRIB_CHECK(grib_set_long(gh, "editionNumber", edition), 0);

  gribapiDefInstitut(gh, vlistID, varID);
  gribapiDefModel(gh, vlistID, varID);

  gribapiDefCode(gh, code, tableInqNum(tableID));
  gribapiDefTime(gh, date, time, numavg, vlistInqTaxis(vlistID));
  gribapiDefGrid(gh, gridID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
2036
  gribapiDefLevel(gh, code, zaxisID, levelID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
2037
2038
2039

  // GRIB_CHECK(grib_set_double(gh, "missingValue", GRIB_MISSVAL), 0);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
2040
  bitsPerValue = grbBitsPerValue(datatype);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
  GRIB_CHECK(grib_set_long(gh, "bitsPerValue", bitsPerValue), 0);

  GRIB_CHECK(grib_set_double_array(gh, "values", data, datasize), 0);

  /* get the size of coded message  */
  GRIB_CHECK(grib_get_message(gh, (const void **)&dummy, &recsize), 0);
  //recsize += 512; /* add some space for possible filling */

  if ( recsize > gribbuffersize )
    Error(func, "Internal problem: GRIB buffer to small (size = %ld, needed = %ld", gribbuffersize, recsize);

  /* get a copy of the coded message */
  GRIB_CHECK(grib_get_message_copy(gh, gribbuffer, &recsize), 0);

  grib_handle_delete(gh);

  nbytes = recsize;
#else
  Error(func, "GRIB_API support not compiled in!");
#endif

  return (nbytes);
}