stream_cdf_o.c 67.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#if defined (HAVE_CONFIG_H)
#  include "config.h"
#endif

#ifdef HAVE_LIBNETCDF

#include "dmemory.h"
#include "cdi_int.h"
#include "cdi_uuid.h"
#include "stream_cdf.h"
#include "cdf_int.h"
#include "varscan.h"
#include "vlist.h"
#include "zaxis.h"


#define  POSITIVE_UP    1
#define  POSITIVE_DOWN  2


Uwe Schulzweida's avatar
Uwe Schulzweida committed
21
22
23
static const char bndsName[] = "bnds";


24
25
26
27
28
29
30
31
32
33
void cdfCopyRecord(stream_t *streamptr2, stream_t *streamptr1)
{
  int vlistID1 = streamptr1->vlistID;
  int tsID     = streamptr1->curTsID;
  int vrecID   = streamptr1->tsteps[tsID].curRecID;
  int recID    = streamptr1->tsteps[tsID].recIDs[vrecID];
  int ivarID   = streamptr1->tsteps[tsID].records[recID].varID;
  int gridID   = vlistInqVarGrid(vlistID1, ivarID);
  int datasize = gridInqSize(gridID);
  int datatype = vlistInqVarDatatype(vlistID1, ivarID);
34
  int memtype  = datatype != CDI_DATATYPE_FLT32 ? MEMTYPE_DOUBLE : MEMTYPE_FLOAT;
35

Uwe Schulzweida's avatar
Uwe Schulzweida committed
36
  void *data = Malloc((size_t)datasize
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
             * (memtype == MEMTYPE_DOUBLE ? sizeof(double) : sizeof(float)));

  int nmiss;
  cdf_read_record(streamptr1, memtype, data, &nmiss);
  cdf_write_record(streamptr2, memtype, data, nmiss);

  Free(data);
}


void cdfDefRecord(stream_t *streamptr)
{
  (void)streamptr;
}

static
void cdfDefTimeValue(stream_t *streamptr, int tsID)
{
  int fileID = streamptr->fileID;

  if ( CDI_Debug )
    Message("streamID = %d, fileID = %d", streamptr->self, fileID);

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

  if ( streamptr->ncmode == 1 )
    {
      cdf_enddef(fileID);
      streamptr->ncmode = 2;
    }

  size_t index = (size_t)tsID;

  double timevalue = cdiEncodeTimeval(taxis->vdate, taxis->vtime, &streamptr->tsteps[0].taxis);
  if ( CDI_Debug ) Message("tsID = %d  timevalue = %f", tsID, timevalue);

  int ncvarid = streamptr->basetime.ncvarid;
  cdf_put_var1_double(fileID, ncvarid, &index, &timevalue);

  if ( taxis->has_bounds )
    {
      size_t start[2], count[2];

      ncvarid = streamptr->basetime.ncvarboundsid;

      timevalue = cdiEncodeTimeval(taxis->vdate_lb, taxis->vtime_lb, &streamptr->tsteps[0].taxis);
      start[0] = (size_t)tsID; count[0] = 1; start[1] = 0; count[1] = 1;
      cdf_put_vara_double(fileID, ncvarid, start, count, &timevalue);

      timevalue = cdiEncodeTimeval(taxis->vdate_ub, taxis->vtime_ub, &streamptr->tsteps[0].taxis);
      start[0] = (size_t)tsID; count[0] = 1; start[1] = 1; count[1] = 1;
      cdf_put_vara_double(fileID, ncvarid, start, count, &timevalue);
    }

  ncvarid = streamptr->basetime.leadtimeid;
92
  if ( taxis->type == TAXIS_FORECAST && ncvarid != CDI_UNDEFID )
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
    {
      timevalue = taxis->fc_period;
      cdf_put_var1_double(fileID, ncvarid, &index, &timevalue);
    }

  /*
printf("fileID = %d %d %d %f\n", fileID, time_varid, index, timevalue);
  */
}

static
int cdfDefTimeBounds(int fileID, int nctimevarid, int nctimedimid, const char *taxis_name, taxis_t* taxis)
{
  int time_bndsid = -1;
  int dims[2];

  dims[0] = nctimedimid;

  /* fprintf(stderr, "time has bounds\n"); */

  if ( nc_inq_dimid(fileID, bndsName, &dims[1]) != NC_NOERR )
    cdf_def_dim(fileID, bndsName, 2, &dims[1]);

  const char *bndsAttName, *bndsAttVal;
  size_t bndsAttValLen;
  char tmpstr[CDI_MAX_NAME];
  if ( taxis->climatology )
    {
      static const char climatology_bndsName[] = "climatology_bnds",
        climatology_bndsAttName[] = "climatology";
      bndsAttName = climatology_bndsAttName;
      bndsAttValLen = sizeof (climatology_bndsName) - 1;
      bndsAttVal = climatology_bndsName;
    }
  else
    {
      size_t taxisnameLen = strlen(taxis_name);
      memcpy(tmpstr, taxis_name, taxisnameLen);
      tmpstr[taxisnameLen] = '_';
      memcpy(tmpstr + taxisnameLen + 1, bndsName, sizeof (bndsName));
      size_t tmpstrLen = taxisnameLen + sizeof (bndsName);
      static const char generic_bndsAttName[] = "bounds";
      bndsAttName = generic_bndsAttName;
      bndsAttValLen = tmpstrLen;
      bndsAttVal = tmpstr;
    }
  cdf_def_var(fileID, bndsAttVal, NC_DOUBLE, 2, dims, &time_bndsid);
  cdf_put_att_text(fileID, nctimevarid, bndsAttName, bndsAttValLen, bndsAttVal);

  return time_bndsid;
}

static
void cdfDefTimeUnits(char *unitstr, taxis_t* taxis0, taxis_t* taxis)
{
  unitstr[0] = 0;

  if ( taxis0->type == TAXIS_ABSOLUTE )
    {
      if ( taxis0->unit == TUNIT_YEAR )
        sprintf(unitstr, "year as %s", "%Y.%f");
      else if ( taxis0->unit == TUNIT_MONTH )
        sprintf(unitstr, "month as %s", "%Y%m.%f");
      else
        sprintf(unitstr, "day as %s", "%Y%m%d.%f");
    }
  else
    {
      int timeunit = taxis->unit != -1 ? taxis->unit : TUNIT_HOUR;
      int rdate    = taxis->rdate;
      int rtime    = taxis->rtime;
      if ( rdate == -1 )
        {
          rdate  = taxis->vdate;
          rtime  = taxis->vtime;
        }

      int year, month, day, hour, minute, second;
      cdiDecodeDate(rdate, &year, &month, &day);
      cdiDecodeTime(rtime, &hour, &minute, &second);

      if ( timeunit == TUNIT_QUARTER   ) timeunit = TUNIT_MINUTE;
      if ( timeunit == TUNIT_30MINUTES ) timeunit = TUNIT_MINUTE;
      if ( timeunit == TUNIT_3HOURS  ||
	   timeunit == TUNIT_6HOURS  ||
	   timeunit == TUNIT_12HOURS ) timeunit = TUNIT_HOUR;

      sprintf(unitstr, "%s since %d-%d-%d %02d:%02d:%02d",
              tunitNamePtr(timeunit), year, month, day, hour, minute, second);
    }
}

static
void cdfDefForecastTimeUnits(char *unitstr, int timeunit)
{
  unitstr[0] = 0;

  if ( timeunit == -1 ) timeunit = TUNIT_HOUR;

  if ( timeunit == TUNIT_QUARTER   ) timeunit = TUNIT_MINUTE;
  if ( timeunit == TUNIT_30MINUTES ) timeunit = TUNIT_MINUTE;
  if ( timeunit == TUNIT_3HOURS  ||
       timeunit == TUNIT_6HOURS  ||
       timeunit == TUNIT_12HOURS ) timeunit = TUNIT_HOUR;

  strcpy(unitstr, tunitNamePtr(timeunit));
}

static
void cdfDefCalendar(int fileID, int ncvarid, int calendar)
{
  static const struct { int calCode; const char *calStr; } calTab[] = {
    { CALENDAR_STANDARD, "standard" },
    { CALENDAR_PROLEPTIC, "proleptic_gregorian" },
    { CALENDAR_NONE, "none" },
    { CALENDAR_360DAYS, "360_day" },
    { CALENDAR_365DAYS, "365_day" },
    { CALENDAR_366DAYS, "366_day" },
  };
  enum { calTabSize = sizeof calTab / sizeof calTab[0] };

214
215
  for ( size_t i = 0; i < calTabSize; ++i )
    if ( calTab[i].calCode == calendar )
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
      {
        const char *calstr = calTab[i].calStr;
        size_t len = strlen(calstr);
        cdf_put_att_text(fileID, ncvarid, "calendar", len, calstr);
        break;
      }
}


void cdfDefTime(stream_t* streamptr)
{
  int time_varid;
  int time_dimid;
  int time_bndsid = -1;
  static const char default_name[] = "time";

232
  if ( streamptr->basetime.ncvarid != CDI_UNDEFID ) return;
233
234
235
236
237
238
239
240
241
242
243
244
245

  int fileID = streamptr->fileID;

  if ( streamptr->ncmode == 0 ) streamptr->ncmode = 1;
  if ( streamptr->ncmode == 2 ) cdf_redef(fileID);

  taxis_t *taxis = &streamptr->tsteps[0].taxis;

  const char *taxis_name = (taxis->name && taxis->name[0]) ? taxis->name : default_name ;

  cdf_def_dim(fileID, taxis_name, NC_UNLIMITED, &time_dimid);
  streamptr->basetime.ncdimid = time_dimid;

246
  nc_type xtype = (taxis->datatype == CDI_DATATYPE_FLT32) ? NC_FLOAT : NC_DOUBLE;
247
248

  cdf_def_var(fileID, taxis_name, xtype, 1, &time_dimid, &time_varid);
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

  streamptr->basetime.ncvarid = time_varid;

  {
    static const char timeStr[] = "time";
    cdf_put_att_text(fileID, time_varid, "standard_name", sizeof(timeStr) - 1, timeStr);
  }

  if ( taxis->longname && taxis->longname[0] )
    cdf_put_att_text(fileID, time_varid, "long_name", strlen(taxis->longname), taxis->longname);

  if ( taxis->has_bounds )
    {
      time_bndsid = cdfDefTimeBounds(fileID, time_varid, time_dimid, taxis_name, taxis);
      streamptr->basetime.ncvarboundsid = time_bndsid;
    }

  {
    char unitstr[CDI_MAX_NAME];
    cdfDefTimeUnits(unitstr, &streamptr->tsteps[0].taxis, taxis);
    size_t len = strlen(unitstr);
    if ( len )
      {
        cdf_put_att_text(fileID, time_varid, "units", len, unitstr);
        /*
          if ( taxis->has_bounds )
          cdf_put_att_text(fileID, time_bndsid, "units", len, unitstr);
        */
      }
  }

  if ( taxis->calendar != -1 )
    {
      cdfDefCalendar(fileID, time_varid, taxis->calendar);
      /*
      if ( taxis->has_bounds )
        cdfDefCalendar(fileID, time_bndsid, taxis->calendar);
      */
    }

  if ( taxis->type == TAXIS_FORECAST )
    {
      int leadtimeid;

293
      cdf_def_var(fileID, "leadtime", xtype, 1, &time_dimid, &leadtimeid);
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

      streamptr->basetime.leadtimeid = leadtimeid;

      {
        static const char stdname[] = "forecast_period";
        cdf_put_att_text(fileID, leadtimeid, "standard_name", sizeof(stdname) - 1, stdname);
      }

      {
        static const char lname[] = "Time elapsed since the start of the forecast";
        cdf_put_att_text(fileID, leadtimeid, "long_name", sizeof(lname) - 1, lname);
      }

      {
          char unitstr[CDI_MAX_NAME];
          cdfDefForecastTimeUnits(unitstr, taxis->fc_unit);
          size_t len = strlen(unitstr);
          if ( len )
            cdf_put_att_text(fileID, leadtimeid, "units", len, unitstr);
      }
    }

  cdf_put_att_text(fileID, time_varid, "axis", 1, "T");

  if ( streamptr->ncmode == 2 ) cdf_enddef(fileID);
}


void cdfDefTimestep(stream_t *streamptr, int tsID)
{
  int vlistID = streamptr->vlistID;

  if ( vlistHasTime(vlistID) ) cdfDefTime(streamptr);

  cdfDefTimeValue(streamptr, tsID);
}

static
Uwe Schulzweida's avatar
Uwe Schulzweida committed
332
void cdfDefComplex(stream_t *streamptr, int gridID, int gridindex)
333
{
334
  int dimID = CDI_UNDEFID;
335
  int fileID  = streamptr->fileID;
336
  ncgrid_t *ncgrid = streamptr->ncgrid;
337

Uwe Schulzweida's avatar
Uwe Schulzweida committed
338
  for ( int index = 0; index < gridindex; ++index )
339
    {
340
      if ( ncgrid[index].xdimID != CDI_UNDEFID )
341
        {
342
          int gridID0 = ncgrid[index].gridID;
343
344
345
          int gridtype0 = gridInqType(gridID0);
          if ( gridtype0 == GRID_SPECTRAL || gridtype0 == GRID_FOURIER )
            {
346
              dimID = ncgrid[index].xdimID;
347
348
349
350
351
              break;
            }
        }
    }

352
  if ( dimID == CDI_UNDEFID )
353
    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
354
      static const char axisname[] = "nc2";
355
356
357
358
359
      size_t dimlen = 2;

      if ( streamptr->ncmode == 2 ) cdf_redef(fileID);
      cdf_def_dim(fileID, axisname, dimlen, &dimID);
      cdf_enddef(fileID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
360

361
362
363
      streamptr->ncmode = 2;
    }

364
365
  ncgrid[gridindex].gridID = gridID;
  ncgrid[gridindex].xdimID = dimID;
366
367
368
}

static void
Uwe Schulzweida's avatar
Uwe Schulzweida committed
369
cdfDefSPorFC(stream_t *streamptr, int gridID, int gridindex,
370
371
             char *restrict axisname, int gridRefType)
{
372
  int iz = 0;
373
  int dimID = CDI_UNDEFID;
374
  ncgrid_t *ncgrid = streamptr->ncgrid;
375
376
377

  size_t dimlen = (size_t)gridInqSize(gridID)/2;

378
  for ( int index = 0; index < gridindex; index++ )
379
    {
380
      if ( ncgrid[index].ydimID != CDI_UNDEFID )
381
        {
382
          int gridID0 = ncgrid[index].gridID;
383
384
385
386
387
388
          int gridtype0 = gridInqType(gridID0);
          if ( gridtype0 == gridRefType )
            {
              size_t dimlen0 = (size_t)gridInqSize(gridID0)/2;
              if ( dimlen == dimlen0 )
                {
389
                  dimID = ncgrid[index].ydimID;
390
391
392
393
394
395
396
397
                  break;
                }
              else
                iz++;
            }
        }
    }

398
  if ( dimID == CDI_UNDEFID )
399
400
401
402
403
404
405
406
407
408
409
410
411
    {
      int fileID  = streamptr->fileID;
      if ( iz == 0 ) axisname[3] = '\0';
      else           sprintf(&axisname[3], "%1d", iz+1);

      if ( streamptr->ncmode == 2 ) cdf_redef(fileID);

      cdf_def_dim(fileID, axisname, dimlen, &dimID);

      cdf_enddef(fileID);
      streamptr->ncmode = 2;
    }

412
413
  ncgrid[gridindex].gridID = gridID;
  ncgrid[gridindex].ydimID = dimID;
414
415
416
}

static
Uwe Schulzweida's avatar
Uwe Schulzweida committed
417
void cdfDefSP(stream_t *streamptr, int gridID, int gridindex)
418
419
420
421
422
{
  /*
  char longname[] = "Spherical harmonic coefficient";
  */
  char axisname[5] = "nspX";
Uwe Schulzweida's avatar
Uwe Schulzweida committed
423
  cdfDefSPorFC(streamptr, gridID, gridindex, axisname, GRID_SPECTRAL);
424
425
426
427
}


static
Uwe Schulzweida's avatar
Uwe Schulzweida committed
428
void cdfDefFC(stream_t *streamptr, int gridID, int gridindex)
429
430
{
  char axisname[5] = "nfcX";
Uwe Schulzweida's avatar
Uwe Schulzweida committed
431
  cdfDefSPorFC(streamptr, gridID, gridindex, axisname, GRID_FOURIER);
432
433
434
435
}

static const struct cdfDefGridAxisInqs {
  int (*axisSize)(int gridID);
436
  int (*axisDimname)(int cdiID, int key, int size, char *mesg);
437
438
  int (*axisName)(int cdiID, int key, int size, char *mesg);
  int (*axisLongname)(int cdiID, int key, int size, char *mesg);
439
440
  int (*axisUnits)(int cdiID, int key, int size, char *mesg);
  void (*axisStdname)(int cdiID, char *dimstdname);
441
442
443
444
445
  double (*axisVal)(int gridID, int index);
  const double *(*axisValsPtr)(int gridID);
  const double *(*axisBoundsPtr)(int gridID);
} gridInqsX = {
  .axisSize = gridInqXsize,
446
  .axisDimname = cdiGridInqKeyStr,
447
  .axisName = cdiGridInqKeyStr,
448
  .axisLongname = cdiGridInqKeyStr,
449
450
  .axisUnits = cdiGridInqKeyStr,
  .axisStdname = gridInqXstdname,
451
452
453
454
455
  .axisVal = gridInqXval,
  .axisValsPtr = gridInqXvalsPtr,
  .axisBoundsPtr = gridInqXboundsPtr,
}, gridInqsY = {
  .axisSize = gridInqYsize,
456
  .axisDimname = cdiGridInqKeyStr,
457
  .axisName = cdiGridInqKeyStr,
458
  .axisLongname = cdiGridInqKeyStr,
459
460
  .axisUnits = cdiGridInqKeyStr,
  .axisStdname = gridInqYstdname,
461
462
463
464
  .axisVal = gridInqYval,
  .axisValsPtr = gridInqYvalsPtr,
  .axisBoundsPtr = gridInqYboundsPtr,
}, gridInqsZ = {
465
  .axisLongname = cdiZaxisInqKeyStr,
466
467
  .axisUnits = cdiZaxisInqKeyStr,
  .axisStdname = zaxisInqStdname,
468
469
};

470
471
static
void cdfPutGridStdAtts(int fileID, int ncvarid, int gridID, int dimtype, const struct cdfDefGridAxisInqs *inqs)
472
473
{
  size_t len;
474
475
476
477
478
479
480
481
482

  char stdname[CDI_MAX_NAME];
  inqs->axisStdname(gridID, stdname);
  if ( (len = strlen(stdname)) )
    cdf_put_att_text(fileID, ncvarid, "standard_name", len, stdname);

  char longname[CDI_MAX_NAME]; longname[0] = 0;
  int keyname = (dimtype == 'Z') ? CDI_KEY_LONGNAME : (dimtype == 'X') ? CDI_KEY_XLONGNAME : CDI_KEY_YLONGNAME;
  inqs->axisLongname(gridID, keyname, CDI_MAX_NAME, longname);
483
  if ( longname[0] && (len = strlen(longname)) )
484
485
    cdf_put_att_text(fileID, ncvarid, "long_name", len, longname);

486
487
488
489
  char units[CDI_MAX_NAME]; units[0] = 0;
  keyname = (dimtype == 'Z') ? CDI_KEY_UNITS : (dimtype == 'X') ? CDI_KEY_XUNITS : CDI_KEY_YUNITS;
  inqs->axisUnits(gridID, keyname, CDI_MAX_NAME, units);
  if ( units[0] && (len = strlen(units)) )
490
    cdf_put_att_text(fileID, ncvarid, "units", len, units);
491
492
493
}

static void
Uwe Schulzweida's avatar
Uwe Schulzweida committed
494
cdfDefTrajLatLon(stream_t *streamptr, int gridID, int gridindex,
495
                 const struct cdfDefGridAxisInqs *inqs, int dimtype)
496
{
497
  nc_type xtype = (gridInqPrec(gridID) == CDI_DATATYPE_FLT32) ? NC_FLOAT : NC_DOUBLE;
498
  ncgrid_t *ncgrid = streamptr->ncgrid;
499
500
501

  int dimlen = inqs->axisSize(gridID);
  if ( dimlen != 1 )
502
    Error("%c size isn't 1 for %s grid!", dimtype, gridNamePtr(gridInqType(gridID)));
503

504
  int ncvarid = CDI_UNDEFID;
505
506
507
508
  if ( dimtype == 'X' )
    ncvarid = ncgrid[gridindex].xdimID;
  else
    ncvarid = ncgrid[gridindex].ydimID;
509

510
  if ( ncvarid == CDI_UNDEFID )
511
512
513
514
515
    {
      int dimNcID = streamptr->basetime.ncvarid;
      int fileID  = streamptr->fileID;
      if ( streamptr->ncmode == 2 ) cdf_redef(fileID);

516
517
518
      char axisname[CDI_MAX_NAME]; axisname[0] = 0;
      int keyname = (dimtype == 'X') ? CDI_KEY_XNAME : CDI_KEY_YNAME;
      inqs->axisName(gridID, keyname, CDI_MAX_NAME, axisname);
519
      cdf_def_var(fileID, axisname, xtype, 1, &dimNcID, &ncvarid);
520
      cdfPutGridStdAtts(fileID, ncvarid, gridID, dimtype, inqs);
521
522
523
524
      cdf_enddef(fileID);
      streamptr->ncmode = 2;
    }

525
526
527
528
529
  ncgrid[gridindex].gridID = gridID;
  if ( dimtype == 'X' )
    ncgrid[gridindex].xdimID = ncvarid; /* var ID for trajectory !!! */
  else
    ncgrid[gridindex].ydimID = ncvarid; /* var ID for trajectory !!! */
530
531
532
}

static
Uwe Schulzweida's avatar
Uwe Schulzweida committed
533
void cdfDefTrajLon(stream_t *streamptr, int gridID, int gridindex)
534
{
535
  cdfDefTrajLatLon(streamptr, gridID, gridindex, &gridInqsX, 'X');
536
537
538
539
}


static
Uwe Schulzweida's avatar
Uwe Schulzweida committed
540
void cdfDefTrajLat(stream_t *streamptr, int gridID, int gridindex)
541
{
542
  cdfDefTrajLatLon(streamptr, gridID, gridindex, &gridInqsY, 'Y');
543
544
545
546
547
548
549
}

static
int checkDimName(int fileID, size_t dimlen, char *dimname)
{
  /* check whether the dimenion name is already defined with the same length */
  unsigned iz = 0;
550
  int dimid = CDI_UNDEFID;
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
  char name[CDI_MAX_NAME];

  size_t len = strlen(dimname);
  memcpy(name, dimname, len + 1);

  do
    {
      if ( iz ) sprintf(name + len, "_%u", iz+1);

      int dimid0, status = nc_inq_dimid(fileID, name, &dimid0);
      if ( status != NC_NOERR )
        break;
      size_t dimlen0;
      cdf_inq_dimlen(fileID, dimid0, &dimlen0);
      if ( dimlen0 == dimlen )
        {
          dimid = dimid0;
          break;
        }
      iz++;
    }
  while ( iz <= 99 );


  if ( iz ) sprintf(dimname + len, "_%u", iz+1);

  return dimid;
}

static
581
void checkGridName(char *axisname, int fileID)
582
583
584
585
586
587
588
589
590
591
592
593
594
595
{
  int ncdimid;
  char axisname2[CDI_MAX_NAME];

  /* check that the name is not already defined */
  unsigned iz = 0;

  size_t axisnameLen = strlen(axisname);
  memcpy(axisname2, axisname, axisnameLen + 1);
  do
    {
      if ( iz ) sprintf(axisname2 + axisnameLen, "_%u", iz+1);

      int status = nc_inq_varid(fileID, axisname2, &ncdimid);
596
      if ( status != NC_NOERR ) break;
597
598
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

      ++iz;
    }
  while ( iz <= 99 );

  if ( iz ) sprintf(axisname + axisnameLen, "_%u", iz+1);
}

static
int checkZaxisName(char *axisname, int fileID, int vlistID, int zaxisID, int nzaxis)
{
  char axisname2[CDI_MAX_NAME];

  /* check that the name is not already defined */
  unsigned iz = 0;

  size_t axisnameLen = strlen(axisname);
  memcpy(axisname2, axisname, axisnameLen + 1);
  do
    {
      if ( iz ) sprintf(axisname2 + axisnameLen, "_%u", iz+1);

      int ncdimid, status = nc_inq_varid(fileID, axisname2, &ncdimid);

      if ( status != NC_NOERR )
        {
          if ( iz )
            {
              /* check that the name does not exist for other zaxes */
              for ( int index = 0; index < nzaxis; index++ )
                {
                  int zaxisID0 = vlistZaxis(vlistID, index);
                  if ( zaxisID != zaxisID0 )
                    {
                      const char *axisname0 = zaxisInqNamePtr(zaxisID0);
                      if ( strcmp(axisname0, axisname2) == 0 ) goto nextSuffix;
                    }
                }
            }
          break;
        }
      nextSuffix:
      ++iz;
    }
  while (iz <= 99);


  if ( iz ) sprintf(axisname + axisnameLen, "_%u", iz+1);

  return (int)iz;
}

static void
650
cdfDefAxisCommon(stream_t *streamptr, int gridID, int gridindex, int ndims,
651
652
                 const struct cdfDefGridAxisInqs *gridAxisInq, int dimKey, char axisLetter,
                 void (*finishCyclicBounds)(double *pbounds, size_t dimlen, const double *pvals))
653
{
654
655
656
  int dimID = CDI_UNDEFID;
  int ncvarid = CDI_UNDEFID, ncbvarid = CDI_UNDEFID;
  int nvdimID = CDI_UNDEFID;
657
658
  int fileID  = streamptr->fileID;
  size_t dimlen = (size_t)gridAxisInq->axisSize(gridID);
659
660
  nc_type xtype = (nc_type)cdfDefDatatype(gridInqPrec(gridID), streamptr->filetype);

661
  ncgrid_t *ncgrid = streamptr->ncgrid;
662

663
664
665
666
  const double *pvals = gridAxisInq->axisValsPtr(gridID);
  char dimname[CDI_MAX_NAME+3]; dimname[0] = 0;
  if ( ndims && pvals == NULL ) cdiGridInqKeyStr(gridID, dimKey, CDI_MAX_NAME, dimname);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
667
  for ( int index = 0; index < gridindex; ++index )
668
    {
669
      int gridID0 = ncgrid[index].gridID;
670
      assert(gridID0 != CDI_UNDEFID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
671
672
673
674
675
676
      int gridtype0 = gridInqType(gridID0);
      if ( gridtype0 == GRID_GAUSSIAN    ||
           gridtype0 == GRID_LONLAT      ||
           gridtype0 == GRID_PROJECTION  ||
           gridtype0 == GRID_CURVILINEAR ||
           gridtype0 == GRID_GENERIC )
677
        {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
678
          size_t dimlen0 = (size_t)gridAxisInq->axisSize(gridID0);
679
680
681
682
          char dimname0[CDI_MAX_NAME]; dimname0[0] = 0;
          if ( dimname[0] ) cdiGridInqKeyStr(gridID0, dimKey, CDI_MAX_NAME, dimname0);
          bool lname = dimname0[0] ? strcmp(dimname, dimname0) == 0 : true;
          if ( dimlen == dimlen0 && lname )
683
            {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
684
685
686
              double (*inqVal)(int gridID, int index) = gridAxisInq->axisVal;
              if ( IS_EQUAL(inqVal(gridID0, 0), inqVal(gridID, 0)) &&
                   IS_EQUAL(inqVal(gridID0, (int)dimlen-1), inqVal(gridID, (int)dimlen-1)) )
687
                {
688
                  dimID = (dimKey == CDI_KEY_XDIMNAME) ? ncgrid[index].xdimID : ncgrid[index].ydimID;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
689
                  break;
690
691
692
693
694
                }
            }
        }
    }

695
  if ( dimID == CDI_UNDEFID )
696
    {
697
698
699
      char axisname[CDI_MAX_NAME]; axisname[0] = 0;
      int keyname = (axisLetter == 'X') ? CDI_KEY_XNAME : CDI_KEY_YNAME;
      gridAxisInq->axisName(gridID, keyname, CDI_MAX_NAME, axisname);
700
701
702
      if ( axisname[0] == 0 ) Error("axis name undefined!");
      size_t axisnameLen = strlen(axisname);

703
704
705
      /* enough to append _ plus up to 100 decimal and trailing \0 */
      char extendedAxisname[axisnameLen + 4 + 1];
      memcpy(extendedAxisname, axisname, axisnameLen + 1);
706
      checkGridName(extendedAxisname, fileID);
707
      size_t extendedAxisnameLen = axisnameLen + strlen(extendedAxisname + axisnameLen);
708
709
710
711
712
713
714
715

      if ( streamptr->ncmode == 2 ) cdf_redef(fileID);

      if ( ndims )
        {
          if ( dimname[0] == 0 ) strcpy(dimname, extendedAxisname);
          dimID = checkDimName(fileID, dimlen, dimname);

716
          if ( dimID == CDI_UNDEFID ) cdf_def_dim(fileID, dimname, dimlen, &dimID);
717
718
719
        }

      bool gen_bounds = false;
720
      bool grid_is_cyclic = gridIsCircular(gridID) > 0;
721
722
723
724
725
      double *pbounds = NULL;
      if ( pvals )
        {
          cdf_def_var(fileID, extendedAxisname, xtype, ndims, &dimID, &ncvarid);

726
          cdfPutGridStdAtts(fileID, ncvarid, gridID, axisLetter, gridAxisInq);
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
          {
            char axisStr[2] = { axisLetter, '\0' };
            cdf_put_att_text(fileID, ncvarid, "axis", 1, axisStr);
          }

          pbounds = (double *)gridAxisInq->axisBoundsPtr(gridID);

          if ( CDI_cmor_mode && grid_is_cyclic && !pbounds )
            {
              gen_bounds = true;
              pbounds = (double*) Malloc(2*dimlen*sizeof(double));
              for ( size_t i = 0; i < dimlen-1; ++i )
                {
                  pbounds[i*2+1]   = (pvals[i] + pvals[i+1])/2;
                  pbounds[(i+1)*2] = (pvals[i] + pvals[i+1])/2;
                }
              finishCyclicBounds(pbounds, dimlen, pvals);
            }
          if ( pbounds )
            {
              size_t nvertex = 2;
              if ( nc_inq_dimid(fileID, bndsName, &nvdimID) != NC_NOERR )
                cdf_def_dim(fileID, bndsName, nvertex, &nvdimID);
            }
751
          if ( pbounds && nvdimID != CDI_UNDEFID )
752
753
754
755
756
757
758
759
760
761
762
763
764
765
            {
              char boundsname[extendedAxisnameLen + 1 + sizeof (bndsName)];
              memcpy(boundsname, axisname, extendedAxisnameLen);
              boundsname[extendedAxisnameLen] = '_';
              memcpy(boundsname + extendedAxisnameLen + 1, bndsName, sizeof bndsName);
              int dimIDs[2] = { dimID, nvdimID };
              cdf_def_var(fileID, boundsname, xtype, 2, dimIDs, &ncbvarid);
              cdf_put_att_text(fileID, ncvarid, "bounds", extendedAxisnameLen + sizeof (bndsName), boundsname);
            }
        }

      cdf_enddef(fileID);
      streamptr->ncmode = 2;

766
767
      if ( ncvarid  != CDI_UNDEFID ) cdf_put_var_double(fileID, ncvarid, pvals);
      if ( ncbvarid != CDI_UNDEFID ) cdf_put_var_double(fileID, ncbvarid, pbounds);
768
769
      if ( gen_bounds ) Free(pbounds);

770
771
772
773
774
775
776
      if ( ndims == 0 )
        {
          if ( dimKey == CDI_KEY_XDIMNAME )
            ncgrid[gridindex].xvarID = ncvarid;
          else
            ncgrid[gridindex].yvarID = ncvarid;
        }
777
778
    }

779
780
781
782
783
  ncgrid[gridindex].gridID = gridID;
  if ( dimKey == CDI_KEY_XDIMNAME )
    ncgrid[gridindex].xdimID = dimID;
  else
    ncgrid[gridindex].ydimID = dimID;
784
785
}

786
787
static
void finishCyclicXBounds(double *pbounds, size_t dimlen, const double *pvals)
788
789
790
791
792
793
{
  pbounds[0] = (pvals[0] + pvals[dimlen-1]-360)*0.5;
  pbounds[2*dimlen-1] = (pvals[dimlen-1] + pvals[0]+360)*0.5;
}

static
Uwe Schulzweida's avatar
Uwe Schulzweida committed
794
void cdfDefXaxis(stream_t *streamptr, int gridID, int gridindex, int ndims)
795
{
796
797
  cdfDefAxisCommon(streamptr, gridID, gridindex, ndims, &gridInqsX,
                   CDI_KEY_XDIMNAME, 'X', finishCyclicXBounds);
798
799
}

800
801
static
void finishCyclicYBounds(double *pbounds, size_t dimlen, const double *pvals)
802
803
804
805
806
807
{
  pbounds[0] = copysign(90.0, pvals[0]);
  pbounds[2*dimlen-1] = copysign(90.0, pvals[dimlen-1]);
}

static
Uwe Schulzweida's avatar
Uwe Schulzweida committed
808
void cdfDefYaxis(stream_t *streamptr, int gridID, int gridindex, int ndims)
809
{
810
811
  cdfDefAxisCommon(streamptr, gridID, gridindex, ndims, &gridInqsY,
                   CDI_KEY_YDIMNAME, 'Y', finishCyclicYBounds);
812
813
814
815
816
817
}

static
void cdfGridCompress(int fileID, int ncvarid, int gridsize, int filetype, int comptype)
{
#if  defined  (HAVE_NETCDF4)
818
  if ( gridsize > 1 && comptype == CDI_COMPRESS_ZIP && (filetype == CDI_FILETYPE_NC4 || filetype == CDI_FILETYPE_NC4C) )
819
820
821
822
823
824
825
826
    {
      nc_def_var_chunking(fileID, ncvarid, NC_CHUNKED, NULL);
      cdfDefVarDeflate(fileID, ncvarid, 1);
    }
#endif
}

static
Uwe Schulzweida's avatar
Uwe Schulzweida committed
827
void cdfDefCurvilinear(stream_t *streamptr, int gridID, int gridindex)
828
{
829
830
831
832
  int xdimID = CDI_UNDEFID;
  int ydimID = CDI_UNDEFID;
  int ncxvarid = CDI_UNDEFID, ncyvarid = CDI_UNDEFID;
  int ncbxvarid = CDI_UNDEFID, ncbyvarid = CDI_UNDEFID, ncavarid = CDI_UNDEFID;
833
  nc_type xtype = (nc_type)cdfDefDatatype(gridInqPrec(gridID), streamptr->filetype);
834
  ncgrid_t *ncgrid = streamptr->ncgrid;
835
836
837
838
839
840
841

  int fileID  = streamptr->fileID;

  size_t dimlen = (size_t)gridInqSize(gridID);
  size_t xdimlen = (size_t)gridInqXsize(gridID);
  size_t ydimlen = (size_t)gridInqYsize(gridID);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
842
  for ( int index = 0; index < gridindex; index++ )
843
    {
844
      if ( ncgrid[index].xdimID != CDI_UNDEFID )
845
        {
846
          int gridID0 = ncgrid[index].gridID;
847
848
849
850
851
852
853
854
855
856
          int gridtype0 = gridInqType(gridID0);
          if ( gridtype0 == GRID_CURVILINEAR )
            {
              size_t dimlen0 = (size_t)gridInqSize(gridID0);
              if ( dimlen == dimlen0 )
                if ( IS_EQUAL(gridInqXval(gridID0, 0), gridInqXval(gridID, 0)) &&
                     IS_EQUAL(gridInqXval(gridID0, (int)dimlen-1), gridInqXval(gridID, (int)dimlen-1)) &&
                     IS_EQUAL(gridInqYval(gridID0, 0), gridInqYval(gridID, 0)) &&
                     IS_EQUAL(gridInqYval(gridID0, (int)dimlen-1), gridInqYval(gridID, (int)dimlen-1)) )
                  {
857
858
859
860
                    xdimID = ncgrid[index].xdimID;
                    ydimID = ncgrid[index].ydimID;
                    ncxvarid = ncgrid[index].xvarID;
                    ncyvarid = ncgrid[index].yvarID;
861
862
863
864
865
866
                    break;
                  }
            }
        }
    }

867
  if ( xdimID == CDI_UNDEFID || ydimID == CDI_UNDEFID )
868
869
870
871
872
    {
      if ( streamptr->ncmode == 2 ) cdf_redef(fileID);
      {
        char xdimname[CDI_MAX_NAME+3];
        xdimname[0] = 0;
873
        cdiGridInqKeyStr(gridID, CDI_KEY_XDIMNAME, CDI_MAX_NAME, xdimname);
874
875
        if ( xdimname[0] == 0 ) { xdimname[0] = 'x'; xdimname[1] = 0; }
        xdimID = checkDimName(fileID, xdimlen, xdimname);
876
        if ( xdimID == CDI_UNDEFID ) cdf_def_dim(fileID, xdimname, xdimlen, &xdimID);
877
878
879
880
      }
      {
        char ydimname[CDI_MAX_NAME+3];
        ydimname[0] = 0;
881
        cdiGridInqKeyStr(gridID, CDI_KEY_YDIMNAME, CDI_MAX_NAME, ydimname);
882
883
        if ( ydimname[0] == 0 ) { ydimname[0] = 'y'; ydimname[1] = 0; }
        ydimID = checkDimName(fileID, ydimlen, ydimname);
884
        if ( ydimID == CDI_UNDEFID ) cdf_def_dim(fileID, ydimname, ydimlen, &ydimID);
885
886
      }

887
      int nvdimID = CDI_UNDEFID;
888
889
890
      int dimIDs[3];
      if ( gridInqXboundsPtr(gridID) || gridInqYboundsPtr(gridID) )
        {
891
          char vdimname[CDI_MAX_NAME+3]; vdimname[0] = 0;
892
          cdiGridInqKeyStr(gridID, CDI_KEY_VDIMNAME, CDI_MAX_NAME, vdimname);
893
894
895
          if ( vdimname[0] == 0 ) strcpy(vdimname, "nv4");
          size_t nvertex = 4;
          nvdimID = checkDimName(fileID, nvertex, vdimname);
896
          if ( nvdimID == CDI_UNDEFID ) cdf_def_dim(fileID, vdimname, nvertex, &nvdimID);
897
898
899
900
901
902
903
904
        }

      dimIDs[0] = ydimID;
      dimIDs[1] = xdimID;
      dimIDs[2] = nvdimID;

      if ( gridInqXvalsPtr(gridID) )
        {
905
906
          char xaxisname[CDI_MAX_NAME]; xaxisname[0] = 0;
          cdiGridInqKeyStr(gridID, CDI_KEY_XNAME, CDI_MAX_NAME, xaxisname);
907
          checkGridName(xaxisname, fileID);
908
909
910
911

          cdf_def_var(fileID, xaxisname, xtype, 2, dimIDs, &ncxvarid);
          cdfGridCompress(fileID, ncxvarid, (int)(xdimlen*ydimlen), streamptr->filetype, streamptr->comptype);

912
          cdfPutGridStdAtts(fileID, ncxvarid, gridID, 'X', &gridInqsX);
913
914
915
916

          /* attribute for Panoply */
          cdf_put_att_text(fileID, ncxvarid, "_CoordinateAxisType", 3, "Lon");

917
          if ( gridInqXboundsPtr(gridID) && nvdimID != CDI_UNDEFID )
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
            {
              size_t xaxisnameLen = strlen(xaxisname);
              xaxisname[xaxisnameLen] = '_';
              memcpy(xaxisname + xaxisnameLen + 1, bndsName, sizeof (bndsName));
              cdf_def_var(fileID, xaxisname, xtype, 3, dimIDs, &ncbxvarid);
              cdfGridCompress(fileID, ncbxvarid, (int)(xdimlen*ydimlen), streamptr->filetype, streamptr->comptype);

              cdf_put_att_text(fileID, ncxvarid, "bounds", xaxisnameLen + sizeof (bndsName), xaxisname);
            }
        }

      if ( gridInqYvalsPtr(gridID) )
        {
          char yaxisname[CDI_MAX_NAME];
          gridInqYname(gridID, yaxisname);
933
          checkGridName(yaxisname, fileID);
934
935
936
937

          cdf_def_var(fileID, yaxisname, xtype, 2, dimIDs, &ncyvarid);
          cdfGridCompress(fileID, ncyvarid, (int)(xdimlen*ydimlen), streamptr->filetype, streamptr->comptype);

938
          cdfPutGridStdAtts(fileID, ncyvarid, gridID, 'Y', &gridInqsY);
939
940
941
942

          /* attribute for Panoply */
          cdf_put_att_text(fileID, ncyvarid, "_CoordinateAxisType", 3, "Lat");

943
          if ( gridInqYboundsPtr(gridID) && nvdimID != CDI_UNDEFID )
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
            {
              size_t yaxisnameLen = strlen(yaxisname);
              yaxisname[yaxisnameLen] = '_';
              memcpy(yaxisname + yaxisnameLen + 1, bndsName, sizeof (bndsName));
              cdf_def_var(fileID, yaxisname, xtype, 3, dimIDs, &ncbyvarid);
              cdfGridCompress(fileID, ncbyvarid, (int)(xdimlen*ydimlen), streamptr->filetype, streamptr->comptype);

              cdf_put_att_text(fileID, ncyvarid, "bounds", yaxisnameLen + sizeof (bndsName), yaxisname);
            }
        }

      if ( gridInqAreaPtr(gridID) )
        {
          static const char yaxisname_[] = "cell_area";
          static const char units[] = "m2";
          static const char longname[] = "area of grid cell";
          static const char stdname[] = "cell_area";

          cdf_def_var(fileID, yaxisname_, xtype, 2, dimIDs, &ncavarid);

          cdf_put_att_text(fileID, ncavarid, "standard_name", sizeof (stdname) - 1, stdname);
          cdf_put_att_text(fileID, ncavarid, "long_name", sizeof (longname) - 1, longname);
          cdf_put_att_text(fileID, ncavarid, "units", sizeof (units) - 1, units);
        }

      cdf_enddef(fileID);
      streamptr->ncmode = 2;

972
973
974
975
976
      if ( ncxvarid  != CDI_UNDEFID ) cdf_put_var_double(fileID, ncxvarid,  gridInqXvalsPtr(gridID));
      if ( ncbxvarid != CDI_UNDEFID ) cdf_put_var_double(fileID, ncbxvarid, gridInqXboundsPtr(gridID));
      if ( ncyvarid  != CDI_UNDEFID ) cdf_put_var_double(fileID, ncyvarid,  gridInqYvalsPtr(gridID));
      if ( ncbyvarid != CDI_UNDEFID ) cdf_put_var_double(fileID, ncbyvarid, gridInqYboundsPtr(gridID));
      if ( ncavarid  != CDI_UNDEFID ) cdf_put_var_double(fileID, ncavarid,  gridInqAreaPtr(gridID));
977
978
    }

979
980
981
982
983
984
  ncgrid[gridindex].gridID = gridID;
  ncgrid[gridindex].xdimID = xdimID;
  ncgrid[gridindex].ydimID = ydimID;
  ncgrid[gridindex].xvarID = ncxvarid;
  ncgrid[gridindex].yvarID = ncyvarid;
  ncgrid[gridindex].avarID = ncavarid;
985
986
987
}

static
Uwe Schulzweida's avatar
Uwe Schulzweida committed
988
void cdfDefRgrid(stream_t *streamptr, int gridID, int gridindex)
989
{
990
  ncgrid_t *ncgrid = streamptr->ncgrid;
991
  int dimID = CDI_UNDEFID;
992
993
994
995

  size_t dimlen = (size_t)gridInqSize(gridID);

  int iz = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
996
  for ( int index = 0; index < gridindex; index++ )
997
    {
998
      if ( ncgrid[index].xdimID != CDI_UNDEFID )
999
        {
1000
          int gridID0 = ncgrid[index].gridID;