grid.c 51 KB
Newer Older
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1
2
3
4
/*
  This file is part of CDO. CDO is a collection of Operators to
  manipulate and analyse Climate model Data.

5
  Copyright (C) 2003-2013 Uwe Schulzweida, Uwe.Schulzweida@zmaw.de
Uwe Schulzweida's avatar
Uwe Schulzweida committed
6
7
8
9
10
11
12
13
14
15
16
  See COPYING file for copying and redistribution conditions.

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; version 2 of the License.
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
*/

17
18
19
20
#if  defined  (HAVE_CONFIG_H)
#  include "config.h"
#endif

Uwe Schulzweida's avatar
Uwe Schulzweida committed
21
#include <stdio.h>
Uwe Schulzweida's avatar
Uwe Schulzweida committed
22
#include <stdarg.h> /* va_list */
Uwe Schulzweida's avatar
Uwe Schulzweida committed
23

24
#if defined (HAVE_LIBPROJ)
25
#  include "proj_api.h"
26
27
#endif

Ralf Müller's avatar
Ralf Müller committed
28
#include <cdi.h>
Uwe Schulzweida's avatar
Uwe Schulzweida committed
29
30
31
32
33
34
#include "cdo.h"
#include "cdo_int.h"
#include "error.h"
#include "grid.h"


35
static
36
void scale_vec(double scalefactor, long nvals, double *restrict values)
37
38
39
40
{
  long n;

#if defined (_OPENMP)
41
#pragma omp parallel for default(none) shared(nvals, scalefactor, values)
42
43
44
#endif
  for ( n = 0; n < nvals; ++n )
    {
45
      values[n] *= scalefactor;
46
47
48
49
    }
}


50
void grid_to_radian(const char *units, long nvals, double *restrict values, const char *description)
51
52
53
{
  if ( memcmp(units, "degree", 6) == 0 )
    {
54
      scale_vec(DEG2RAD, nvals, values);
55
56
57
58
59
60
61
62
63
64
65
    }
  else if ( memcmp(units, "radian", 6) == 0 )
    {
      /* No conversion necessary */
    }
  else
    {
      cdoWarning("Unknown units [%s] supplied for %s; proceeding assuming radians!", units, description);
    }
}

Uwe Schulzweida's avatar
Uwe Schulzweida committed
66

67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
void grid_to_degree(const char *units, long nvals, double *restrict values, const char *description)
{
  if ( memcmp(units, "radian", 6) == 0 )
    {
      for ( long n = 0; n < nvals; ++n ) values[n] *= RAD2DEG;
    }
  else if ( memcmp(units, "degree", 6) == 0 )
    {
      /* No conversion necessary */
    }
  else
    {
      cdoWarning("Unknown units [%s] supplied for %s; proceeding assuming degress!", units, description);
    }
}


Uwe Schulzweida's avatar
Uwe Schulzweida committed
84
85
86
87
88
89
90
91
92
93
94
int gridToZonal(int gridID1)
{
  int gridID2;
  int gridtype, gridsize;
  double  xval = 0;
  double *yvals;

  gridtype = gridInqType(gridID1);
  gridsize = gridInqYsize(gridID1);
  gridID2  = gridCreate(gridtype, gridsize);
	  
95
96
97
  if ( gridtype == GRID_LONLAT   ||
       gridtype == GRID_GAUSSIAN ||
       gridtype == GRID_GENERIC )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
    {
      gridDefXsize(gridID2, 1);
      gridDefYsize(gridID2, gridsize);

      gridDefXvals(gridID2, &xval);

      if ( gridInqYvals(gridID1, NULL) )
	{
	  yvals = (double *) malloc(gridsize*sizeof(double));

	  gridInqYvals(gridID1, yvals);
	  gridDefYvals(gridID2, yvals);

	  free(yvals);
	}
    }
114
115
  else
    {
116
      Error("Gridtype %s unsupported!", gridNamePtr(gridtype));
117
    }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133

  return (gridID2);
}


int gridToMeridional(int gridID1)
{
  int gridID2;
  int gridtype, gridsize;
  double *xvals;
  double  yval = 0;

  gridtype = gridInqType(gridID1);
  gridsize = gridInqXsize(gridID1);
  gridID2  = gridCreate(gridtype, gridsize);
	  
134
135
136
  if ( gridtype == GRID_LONLAT   ||
       gridtype == GRID_GAUSSIAN ||
       gridtype == GRID_GENERIC )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
137
    {
138
139
      gridDefXsize(gridID2, gridsize);
      gridDefYsize(gridID2, 1);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
140

141
142
143
      if ( gridInqXvals(gridID1, NULL) )
	{
	  xvals = (double *) malloc(gridsize*sizeof(double));
Uwe Schulzweida's avatar
Uwe Schulzweida committed
144

145
146
	  gridInqXvals(gridID1, xvals);
	  gridDefXvals(gridID2, xvals);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
147

148
149
	  free(xvals);
	}
Uwe Schulzweida's avatar
Uwe Schulzweida committed
150

151
152
153
154
      gridDefYvals(gridID2, &yval);
    }
  else
    {
155
      Error("Gridtype %s unsupported!", gridNamePtr(gridtype));
Uwe Schulzweida's avatar
Uwe Schulzweida committed
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
    }

  return (gridID2);
}


void gridGenXbounds(int nx, double *xvals, double *xbounds)
{
  int i;

  for ( i = 0; i < nx-1; i++ )
    {
      xbounds[2*i+1]   = 0.5*(xvals[i] + xvals[i+1]);
      xbounds[2*(i+1)] = 0.5*(xvals[i] + xvals[i+1]);
    }

  xbounds[0]      = 2*xvals[0] - xbounds[1];
  xbounds[2*nx-1] = 2*xvals[nx-1] - xbounds[2*(nx-1)];
}


void gridGenYbounds(int ny, double *yvals, double *ybounds)
{
  int i;

  for ( i = 0; i < ny-1; i++ )
    {
      ybounds[2*i+1]   = 0.5*(yvals[i] + yvals[i+1]);
      ybounds[2*(i+1)] = 0.5*(yvals[i] + yvals[i+1]);
    }

  ybounds[0]      = 2*yvals[0] - ybounds[1];
  ybounds[2*ny-1] = 2*yvals[ny-1] - ybounds[2*(ny-1)];

  if ( yvals[0] > yvals[ny-1] )
    {
      if ( ybounds[0]      >  88 ) ybounds[0]      =  90;
      if ( ybounds[2*ny-1] < -88 ) ybounds[2*ny-1] = -90;
    }
  else
    {
      if ( ybounds[0]      < -88 ) ybounds[0]      = -90;
      if ( ybounds[2*ny-1] >  88 ) ybounds[2*ny-1] =  90;
    }
}


203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
void gridGenYboundsM(int ny, double *yvals, double *ybounds)
{
  int i;

  for ( i = 0; i < ny-1; i++ )
    {
      ybounds[2*i+1]   = 0.5*(yvals[i] + yvals[i+1]);
      ybounds[2*(i+1)] = 0.5*(yvals[i] + yvals[i+1]);
    }

  ybounds[0]      = 2*yvals[0] - ybounds[1];
  ybounds[2*ny-1] = 2*yvals[ny-1] - ybounds[2*(ny-1)];
}


Uwe Schulzweida's avatar
Uwe Schulzweida committed
218
219
220
void gridGenRotBounds(int gridID, int nx, int ny,
		      double *xbounds, double *ybounds, double *xbounds2D, double *ybounds2D)
{
Uwe Schulzweida's avatar
Uwe Schulzweida committed
221
  long i, j, index;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
222
223
  double minlon, maxlon;
  double minlat, maxlat;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
224
  double xpole, ypole, angle;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
225
226
227

  xpole = gridInqXpole(gridID);
  ypole = gridInqYpole(gridID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
228
  angle = gridInqAngle(gridID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248

  for ( j = 0; j < ny; j++ )
    {
      if ( ybounds[0] > ybounds[1] )
	{
	  maxlat = ybounds[2*j];
	  minlat = ybounds[2*j+1];
	}
      else
	{
	  maxlat = ybounds[2*j+1];
	  minlat = ybounds[2*j];
	}

      for ( i = 0; i < nx; i++ )
	{
	  minlon = xbounds[2*i];
	  maxlon = xbounds[2*i+1];

	  index = j*4*nx + 4*i;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
249
250
251
252
253
254
255
256
257
	  xbounds2D[index+0] = lamrot_to_lam(minlat, minlon, ypole, xpole, angle);
	  xbounds2D[index+1] = lamrot_to_lam(minlat, maxlon, ypole, xpole, angle);
	  xbounds2D[index+2] = lamrot_to_lam(maxlat, maxlon, ypole, xpole, angle);
	  xbounds2D[index+3] = lamrot_to_lam(maxlat, minlon, ypole, xpole, angle);

	  ybounds2D[index+0] = phirot_to_phi(minlat, minlon, ypole, angle);
	  ybounds2D[index+1] = phirot_to_phi(minlat, maxlon, ypole, angle);
	  ybounds2D[index+2] = phirot_to_phi(maxlat, maxlon, ypole, angle);
	  ybounds2D[index+3] = phirot_to_phi(maxlat, minlon, ypole, angle);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
258
259
260
261
	}
    }
}

262
263
static
void gridGenXbounds2D(int nx, int ny, const double * restrict xbounds, double * restrict xbounds2D)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
264
{
Uwe Schulzweida's avatar
Uwe Schulzweida committed
265
  long i, j, index;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
266
267
  double minlon, maxlon;

268
269
270
271
272
273
#if defined (_OPENMP)
#pragma omp parallel for default(none)        \
  shared(nx, ny, xbounds, xbounds2D)	      \
  private(i, j, minlon, maxlon, index)
#endif
  for ( i = 0; i < nx; ++i )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
274
    {
275
      minlon = xbounds[2*i  ];
Uwe Schulzweida's avatar
Uwe Schulzweida committed
276
277
      maxlon = xbounds[2*i+1];

278
      for ( j = 0; j < ny; ++j )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
279
280
	{
	  index = j*4*nx + 4*i;
281
	  xbounds2D[index  ] = minlon;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
282
283
284
285
286
287
288
	  xbounds2D[index+1] = maxlon;
	  xbounds2D[index+2] = maxlon;
	  xbounds2D[index+3] = minlon;
	}
    }
}

289
290
static
void gridGenYbounds2D(int nx, int ny, const double * restrict ybounds, double * restrict ybounds2D)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
291
{
Uwe Schulzweida's avatar
Uwe Schulzweida committed
292
  long i, j, index;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
293
294
  double minlat, maxlat;

295
296
297
298
299
300
#if defined (_OPENMP)
#pragma omp parallel for default(none)        \
  shared(nx, ny, ybounds, ybounds2D)	      \
  private(i, j, minlat, maxlat, index)
#endif
  for ( j = 0; j < ny; ++j )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
301
302
303
    {
      if ( ybounds[0] > ybounds[1] )
	{
304
	  maxlat = ybounds[2*j  ];
Uwe Schulzweida's avatar
Uwe Schulzweida committed
305
306
307
308
309
	  minlat = ybounds[2*j+1];
	}
      else
	{
	  maxlat = ybounds[2*j+1];
310
	  minlat = ybounds[2*j  ];
Uwe Schulzweida's avatar
Uwe Schulzweida committed
311
312
	}

313
      for ( i = 0; i < nx; ++i )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
314
315
	{
	  index = j*4*nx + 4*i;
316
	  ybounds2D[index  ] = minlat;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
317
318
319
320
321
322
323
	  ybounds2D[index+1] = minlat;
	  ybounds2D[index+2] = maxlat;
	  ybounds2D[index+3] = maxlat;
	}
    }
}

Uwe Schulzweida's avatar
Uwe Schulzweida committed
324
static
Uwe Schulzweida's avatar
Uwe Schulzweida committed
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
char *gen_param(const char *fmt, ...)
{
  va_list args;
  char str[256];
  char *rstr;
  int len;

  va_start(args, fmt);

  len = vsprintf(str, fmt, args);

  va_end(args);

  len++;
  rstr = (char *) malloc(len*sizeof(char));
  memcpy(rstr, str, len*sizeof(char));

  return (rstr);
}

Uwe Schulzweida's avatar
Uwe Schulzweida committed
345
346
347
348
349
350
351
352
353
static
void lcc_to_geo(int gridID, int gridsize, double *xvals, double *yvals)
{
  double originLon, originLat, lonParY, lat1, lat2, xincm, yincm;
  double zlat, zlon;
  double xi, xj;
  int projflag, scanflag;
  int status;
  long i;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
354
  proj_info_t proj;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
355
356
357
358
359
360
361
362

  gridInqLCC(gridID, &originLon, &originLat, &lonParY, &lat1, &lat2, &xincm, &yincm,
	     &projflag, &scanflag);
  /*
    while ( originLon < 0 ) originLon += 360;
    while ( lonParY   < 0 ) lonParY   += 360;
  */
  if ( IS_NOT_EQUAL(xincm, yincm) )
363
    Warning("X and Y increment must be equal on Lambert Conformal grid (Xinc = %g, Yinc = %g)\n", 
Uwe Schulzweida's avatar
Uwe Schulzweida committed
364
	    xincm, yincm);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
365
  /*
Uwe Schulzweida's avatar
Uwe Schulzweida committed
366
  if ( IS_NOT_EQUAL(lat1, lat2) )
367
    Warning("Lat1 and Lat2 must be equal on Lambert Conformal grid (Lat1 = %g, Lat2 = %g)\n", 
Uwe Schulzweida's avatar
Uwe Schulzweida committed
368
	    lat1, lat2);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
369
370
371
  */
  map_set(PROJ_LC, originLat, originLon, xincm, lonParY, lat1, lat2, &proj);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
372
373
374
375
  for ( i = 0; i < gridsize; i++ )
    {
      xi = xvals[i];
      xj = yvals[i];
Uwe Schulzweida's avatar
Uwe Schulzweida committed
376
377
      // status = W3FB12(xi, xj, originLat, originLon, xincm, lonParY, lat1, &zlat, &zlon);
      ijll_lc(xi, xj, proj, &zlat, &zlon);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
378
379
380
381
382
383
384
385
386
      xvals[i] = zlon;
      yvals[i] = zlat;
    }
}

static
void sinusoidal_to_geo(int gridsize, double *xvals, double *yvals)
{
#if defined (HAVE_LIBPROJ)
387
  projPJ   *libProj;
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
  char *params[20];
  int nbpar=0;
  projUV data, res;
  long i;

  nbpar = 0;
  params[nbpar++] = (char*) "proj=sinu";
  params[nbpar++] = (char*) "ellps=WGS84";

  if ( cdoVerbose )
    for ( i = 0; i < nbpar; ++i )
      cdoPrint("Proj.param[%ld] = %s", i+1, params[i]);

  libProj = pj_init(nbpar, params);
  if ( !libProj )
    cdoAbort("proj error: %s", pj_strerrno(pj_errno));

  /* libProj->over = 1; */		/* allow longitude > 180 */

  for ( i = 0; i < gridsize; i++ )
    {
      data.u = xvals[i];
      data.v = yvals[i];
      res = pj_inv(data, libProj);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
412
413
      xvals[i] = res.u*RAD2DEG;
      yvals[i] = res.v*RAD2DEG;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
414
415
416
417
418
419
420
421
422
423
    }
#else
  cdoAbort("proj4 support not compiled in!");
#endif
}

static
void laea_to_geo(int gridID, int gridsize, double *xvals, double *yvals)
{
#if defined (HAVE_LIBPROJ)
424
  projPJ   *libProj;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
425
426
427
428
429
430
431
432
433
434
  char *params[20];
  int nbpar=0;
  projUV data, res;
  double a, lon_0, lat_0;
  long i;

  gridInqLaea(gridID, &a , &lon_0, &lat_0);

  nbpar = 0;
  params[nbpar++] = gen_param("proj=laea");
Uwe Schulzweida's avatar
Uwe Schulzweida committed
435
  if ( a > 0 ) params[nbpar++] = gen_param("a=%g", a);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
  params[nbpar++] = gen_param("lon_0=%g", lon_0);
  params[nbpar++] = gen_param("lat_0=%g", lat_0);

  if ( cdoVerbose )
    for ( i = 0; i < nbpar; ++i )
      cdoPrint("Proj.param[%d] = %s", i+1, params[i]);

  libProj = pj_init(nbpar, &params[0]);
  if ( !libProj )
    cdoAbort("proj error: %s", pj_strerrno(pj_errno));

  for ( i = 0; i < nbpar; ++i ) free(params[i]);

  /* libProj->over = 1; */		/* allow longitude > 180 */

  for ( i = 0; i < gridsize; i++ )
    {
      data.u = xvals[i];
      data.v = yvals[i];
      res = pj_inv(data, libProj);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
456
457
      xvals[i] = res.u*RAD2DEG;
      yvals[i] = res.v*RAD2DEG;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
458
459
460
461
462
463
464
465
466
467
    }
#else
  cdoAbort("proj4 support not compiled in!");
#endif
}

static
void lcc2_to_geo(int gridID, int gridsize, double *xvals, double *yvals)
{
#if defined (HAVE_LIBPROJ)
468
  projPJ   *libProj;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
  char *params[20];
  int nbpar=0;
  projUV data, res;
  double a, lon_0, lat_0, lat_1, lat_2;
  long i;

  gridInqLcc2(gridID, &a , &lon_0, &lat_0, &lat_1, &lat_2);

  nbpar = 0;
  params[nbpar++] = gen_param("proj=lcc");
  if ( a > 0 ) params[nbpar++] = gen_param("a=%g", a);
  params[nbpar++] = gen_param("lon_0=%g", lon_0);
  params[nbpar++] = gen_param("lat_0=%g", lat_0);
  params[nbpar++] = gen_param("lat_1=%g", lat_1);
  params[nbpar++] = gen_param("lat_2=%g", lat_2);

  if ( cdoVerbose )
    for ( i = 0; i < nbpar; ++i )
      cdoPrint("Proj.param[%d] = %s", i+1, params[i]);
  
  libProj = pj_init(nbpar, &params[0]);
  if ( !libProj )
    cdoAbort("proj error: %s", pj_strerrno(pj_errno));

  for ( i = 0; i < nbpar; ++i ) free(params[i]);

  /* libProj->over = 1; */		/* allow longitude > 180 */
  
  for ( i = 0; i < gridsize; i++ )
    {
      data.u = xvals[i];
      data.v = yvals[i];
      res = pj_inv(data, libProj);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
502
503
      xvals[i] = res.u*RAD2DEG;
      yvals[i] = res.v*RAD2DEG;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
504
505
506
507
508
509
    }
#else
  cdoAbort("proj4 support not compiled in!");
#endif
}

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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
/*
 * grib_get_reduced_row: code from GRIB_API 1.10.4
 *
 * Description:
 *   computes the number of points within the range lon_first->lon_last and the zero based indexes
 *   ilon_first,ilon_last of the first and last point given the number of points along a parallel (pl)
 *
 */
static
void grib_get_reduced_row(long pl,double lon_first,double lon_last,long* npoints,long* ilon_first, long* ilon_last )
{
  double range=0,dlon_first=0,dlon_last=0;
  long irange;

  range=lon_last-lon_first;
  if (range<0) {range+=360;lon_first-=360;}

  /* computing integer number of points and coordinates without using floating point resolution*/
  *npoints=(range*pl)/360.0+1;
  *ilon_first=(lon_first*pl)/360.0;
  *ilon_last=(lon_last*pl)/360.0;

  irange=*ilon_last-*ilon_first+1;

  if (irange != *npoints) {
    if (irange > *npoints) {
      /* checking if the first point is out of range*/
      dlon_first=((*ilon_first)*360.0)/pl;
      if (dlon_first < lon_first) {(*ilon_first)++;irange--;
      }

      /* checking if the last point is out of range*/
      dlon_last=((*ilon_last)*360.0)/pl;
      if (dlon_last > lon_last) {(*ilon_last)--;irange--;
      }
    } else {
      int ok=0;
      /* checking if the point before the first is in the range*/
      dlon_first=((*ilon_first-1)*360.0)/pl;
      if (dlon_first > lon_first) {(*ilon_first)--;irange++;ok=1;
      }

      /* checking if the point after the last is in the range*/
      dlon_last=((*ilon_last+1)*360.0)/pl;
      if (dlon_last < lon_last) {(*ilon_last)++;irange++;ok=1;
      }

      /* if neither of the two are triggered then npoints is too large */
      if (!ok) {(*npoints)--;
      }
    }

    //   assert(*npoints==irange);
  } else {
	  /* checking if the first point is out of range*/
	  dlon_first=((*ilon_first)*360.0)/pl;
	  if (dlon_first < lon_first) {
		  (*ilon_first)++;(*ilon_last)++;
	  }
  }

  if (*ilon_first<0) *ilon_first+=pl;

  return;
}
575
576


577
578
579
int    qu2reg3(double *pfield, int *kpoint, int klat, int klon,
	       double msval, int *kret, int omisng, int operio, int oveggy);

580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
static
int qu2reg_subarea(int gridsize, int np, double xfirst, double xlast, 
		   double *array, int *rowlon, int ny, double missval, int *iret, int lmiss, int lperio, int lveggy)
{
  int nx = 0;
  /* sub area (longitudes) */
  long ilon_firstx;
  long ilon_first, ilon_last;
  int i, j;
  long row_count;
  int rlon, nwork = 0;
  int np4 = np*4;
  int size = 0;
  int wlen;
  double *work, **pwork;
  int ii;
  double *parray;

  if ( np <= 0 ) cdoAbort("Number of values between pole and equator missing!");

  grib_get_reduced_row(np4, xfirst, xlast, &row_count, &ilon_firstx, &ilon_last);
  nx = row_count;
  // printf("nx %d  %ld %ld lon1 %g lon2 %g\n", nx, ilon_firstx, ilon_last, (ilon_firstx*360.)/np4, (ilon_last*360.)/np4);

  for ( j = 0; j < ny; ++j ) nwork += rowlon[j];

  pwork = (double **) malloc(ny*sizeof(double *));
  work  = (double *) malloc(ny*np4*sizeof(double));
  wlen = 0;
  pwork[0] = work;
  for ( j = 1; j < ny; ++j )
    {
      wlen += rowlon[j-1];
      pwork[j] = work + wlen;
    } 
  // printf(" ny, np4, nwork %d %d %d wlen %d\n", ny, np4, nwork, wlen);

  for ( j = 0; j < ny; ++j )
    {
      rlon = rowlon[j];
      for ( i = 0; i < rlon; ++i ) pwork[j][i] = missval;
    } 

  parray = array;
  for ( j = 0; j < ny; ++j )
    {
      rlon = rowlon[j];
      row_count = 0;
      grib_get_reduced_row(rlon, xfirst, xlast, &row_count, &ilon_first, &ilon_last);
      // printf("j %d xfirst %g xlast %g rowlon %d %ld %ld %ld %g %g\n", j, xfirst, xlast, rlon, row_count, ilon_first, ilon_last, (ilon_first*360.)/rlon, (ilon_last*360.)/rlon);

      for ( i = ilon_first; i < (ilon_first+row_count); ++i )
	{
	  ii = i;
	  if ( ii >= rlon ) ii -= rlon; 
	  pwork[j][ii] = *parray;
	  parray++;
	}
      size += row_count;
    }

  if ( gridsize != size ) cdoAbort("gridsize1 inconsistent!");

  (void) qu2reg3(work, rowlon, ny, np4, missval, iret, lmiss, lperio, lveggy);

  wlen = 0;
  pwork[0] = work;
  for ( j = 1; j < ny; ++j )
    {
      wlen += np4;
      pwork[j] = work + wlen;
    } 

  // printf("nx, ilon_firstx %d %ld\n", nx, ilon_firstx);
  parray = array;
  for ( j = 0; j < ny; ++j )
    {
      for ( i = ilon_firstx; i < (ilon_firstx+nx); ++i )
	{
	  ii = i;
	  if ( ii >= np4 ) ii -= np4; 
	  *parray = pwork[j][ii];
	  parray++;
	}
    }

  free(work);
  free(pwork);

  return (nx);
}


673
674
void field2regular(int gridID1, int gridID2, double missval, double *array, int nmiss)
{
675
  int nx = 0, ny, np;
676
677
678
  int gridtype;
  int lmiss, lperio, lveggy;
  int iret;
679
680
681
  int *rowlon;
  double xfirstandlast[2];
  double xfirst, xlast;
682
683
684

  gridtype = gridInqType(gridID1);

685
  if ( gridtype != GRID_GAUSSIAN_REDUCED ) Error("Not a reduced gaussian grid!");
686

687
688
689
  lmiss = nmiss > 0;
  lperio = 1;
  lveggy = 0;
690

691
  ny = gridInqYsize(gridID1);
692
  np = gridInqNP(gridID1);
693

694
695
  rowlon = (int *) malloc(ny*sizeof(int));
  gridInqRowlon(gridID1, rowlon);
696

697
698
699
700
701
  xfirstandlast[0] = 0.;
  xfirstandlast[1] = 0.;
  gridInqXvals(gridID1, xfirstandlast);
  xfirst = xfirstandlast[0];
  xlast  = xfirstandlast[1];
702

703
  if ( fabs(xfirst) > 0 || (np > 0 && fabs(xlast - (360.0-90.0/np)) > 90.0/np) )
704
    {
705
      nx = qu2reg_subarea(gridInqSize(gridID1), np, xfirst, xlast, array, rowlon, ny, missval, &iret, lmiss, lperio, lveggy);
706
707
708
    }
  else
    {
709
      nx = 2*ny;
710
711
      (void) qu2reg3(array, rowlon, ny, nx, missval, &iret, lmiss, lperio, lveggy);
    }
712

713
  if ( gridInqSize(gridID2) != nx*ny ) Error("Gridsize differ!");
714

715
  free(rowlon);
716
717
718
719
720
721
722
}


int gridToRegular(int gridID1)
{
  int gridID2;
  int gridtype, gridsize;
723
  int nx = 0, ny, np;
724
725
  long i;
  double *xvals = NULL, *yvals = NULL;
726
727
  double xfirstandlast[2];
  double xfirst, xlast;
728
729
730

  gridtype = gridInqType(gridID1);

731
  if ( gridtype != GRID_GAUSSIAN_REDUCED ) Error("Not a reduced gaussian grid!");
732
733

  ny = gridInqYsize(gridID1);
734
735
736
737
738
739
740
741
742
743
744
  np = gridInqNP(gridID1);

  yvals = (double *) malloc(ny*sizeof(double));
  gridInqYvals(gridID1, yvals);

  xfirstandlast[0] = 0.;
  xfirstandlast[1] = 0.;
  gridInqXvals(gridID1, xfirstandlast);
  xfirst = xfirstandlast[0];
  xlast  = xfirstandlast[1];

745
  if ( fabs(xfirst) > 0 || (np > 0 && fabs(xlast - (360.0-90.0/np)) > 90.0/np) )
746
747
    {
      /* sub area (longitudes) */
748
      long ilon_first, ilon_last;
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
      long row_count;
      int np4 = np*4;
      int *rowlon = NULL;

      if ( np <= 0 ) cdoAbort("Number of values between pole and equator missing!");

      grib_get_reduced_row(np4, xfirst, xlast, &row_count, &ilon_first, &ilon_last);

      nx = row_count;
      xvals = (double *) malloc(nx*sizeof(double));
      for ( i = 0; i < nx; ++i )
	{
	  xvals[i] = ((ilon_first+i)*360.)/np4;
	  if ( xfirst > xlast ) xvals[i] -= 360.;
	}

      free(rowlon);
    }
  else
    {
      nx = 2*ny;
      xvals = (double *) malloc(nx*sizeof(double));
      for ( i = 0; i < nx; ++i ) xvals[i] = i * 360./nx;
    }

774
775
776
777
778
779
780
781
782
  gridsize = nx*ny;

  gridID2  = gridCreate(GRID_GAUSSIAN, gridsize);
	  
  gridDefXsize(gridID2, nx);
  gridDefYsize(gridID2, ny);
  
  gridDefXvals(gridID2, xvals);
  gridDefYvals(gridID2, yvals);
783
  gridDefNP(gridID2, np);
784
785
786
787
788
789
790

  free(xvals);
  free(yvals);

  return (gridID2);
}

Uwe Schulzweida's avatar
Uwe Schulzweida committed
791
792
793
794
795
796
797
798
799
800
801
802
803
static
void gridCopyMask(int gridID1, int gridID2, long gridsize)
{
  if ( gridInqMask(gridID1, NULL) )
    {
      int *mask;
      mask = (int *) malloc(gridsize*sizeof(int));
      gridInqMask(gridID1, mask);
      gridDefMask(gridID2, mask);
      free(mask);
    }
}

804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
static
int check_range(long n, double *vals, double valid_min, double valid_max)
{
  int status = 0;
  long i;

  for ( i = 0; i < n; ++i )
    {
      if ( vals[i] < valid_min || vals[i] > valid_max )
	{
	  status = 1;
	  break;
	}
    }

  return (status);
}
Uwe Schulzweida's avatar
Uwe Schulzweida committed
821

822

823
int gridToCurvilinear(int gridID1, int lbounds)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
824
825
826
{
  int gridID2;
  int gridtype, gridsize;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
827
  long index;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
828
829
830
831

  gridtype = gridInqType(gridID1);
  gridsize = gridInqSize(gridID1);
  gridID2  = gridCreate(GRID_CURVILINEAR, gridsize);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
832
  gridDefPrec(gridID2, DATATYPE_FLT32);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
833
834
835
836
837
838
	  
  switch (gridtype)
    {
    case GRID_LONLAT:
    case GRID_GAUSSIAN:
    case GRID_LCC:
839
    case GRID_LCC2:
Uwe Schulzweida's avatar
Uwe Schulzweida committed
840
    case GRID_LAEA:
841
    case GRID_SINUSOIDAL:
Uwe Schulzweida's avatar
Uwe Schulzweida committed
842
      {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
843
844
	long i, j;
	int nx, ny;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
845
846
847
848
	double *xvals = NULL, *yvals = NULL;
	double *xvals2D, *yvals2D;
	double *xbounds = NULL, *ybounds = NULL;
	double *xbounds2D, *ybounds2D;
849
	char xunits[CDI_MAX_NAME], yunits[CDI_MAX_NAME];
850
	double xscale = 1, yscale = 1;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
851
852
853
854

	nx = gridInqXsize(gridID1);
	ny = gridInqYsize(gridID1);

855
856
857
	gridInqXunits(gridID1, xunits);
	gridInqYunits(gridID1, yunits);

858
859
860
861
862
863
864
	if ( gridtype == GRID_LAEA )
	  {
	    int lvalid_xunits = FALSE;
	    int lvalid_yunits = FALSE;
	    int len;
	    len = (int) strlen(xunits);
	    if ( len == 1 && memcmp(xunits, "m",  1) == 0 ) lvalid_xunits = TRUE;
865
	    if ( len == 2 && memcmp(xunits, "km", 2) == 0 ) lvalid_xunits = TRUE;
866
867
	    len = (int) strlen(yunits);
	    if ( len == 1 && memcmp(yunits, "m",  1) == 0 ) lvalid_yunits = TRUE;
868
	    if ( len == 2 && memcmp(yunits, "km", 2) == 0 ) lvalid_yunits = TRUE;
869
870

	    if ( lvalid_xunits == FALSE )
871
	      cdoWarning("Possibly wrong result! Invalid x-coordinate units: \"%s\" (expected \"m\" or \"km\")", xunits);
872
	    if ( lvalid_yunits == FALSE )
873
	      cdoWarning("Possibly wrong result! Invalid y-coordinate units: \"%s\" (expected \"m\" or \"km\")", yunits);
874
875
	  }

876
877
	if ( memcmp(xunits, "km", 2) == 0 ) xscale = 1000;
	if ( memcmp(yunits, "km", 2) == 0 ) yscale = 1000;
878

Uwe Schulzweida's avatar
Uwe Schulzweida committed
879
880
881
882
883
884
885
886
887
888
889
890
	gridDefXsize(gridID2, nx);
	gridDefYsize(gridID2, ny);

	xvals2D = (double *) malloc(gridsize*sizeof(double));
	yvals2D = (double *) malloc(gridsize*sizeof(double));


	if ( gridtype == GRID_LCC )
	  {
	    for ( j = 0; j < ny; j++ )
	      for ( i = 0; i < nx; i++ )
		{
Uwe Schulzweida's avatar
Uwe Schulzweida committed
891
892
		  xvals2D[j*nx+i] = i+1;
		  yvals2D[j*nx+i] = j+1;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
893
		}
Uwe Schulzweida's avatar
Uwe Schulzweida committed
894
895

	    lcc_to_geo(gridID1, gridsize, xvals2D, yvals2D);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
896
897
898
899
	  }
	else
	  {
	    if ( ! (gridInqXvals(gridID1, NULL) && gridInqYvals(gridID1, NULL)) )
900
	      Error("Grid has no values");
Uwe Schulzweida's avatar
Uwe Schulzweida committed
901
902
903
904
905
906
907
908
909

	    xvals = (double *) malloc(nx*sizeof(double));
	    yvals = (double *) malloc(ny*sizeof(double));

	    gridInqXvals(gridID1, xvals);
	    gridInqYvals(gridID1, yvals);

	    if ( gridIsRotated(gridID1) )
	      {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
910
		double xpole, ypole, angle;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
911
912
913
		
		xpole = gridInqXpole(gridID1);
		ypole = gridInqYpole(gridID1);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
914
		angle = gridInqAngle(gridID1);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
915
916
917
918
		
		for ( j = 0; j < ny; j++ )
		  for ( i = 0; i < nx; i++ )
		    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
919
920
		      xvals2D[j*nx+i] = lamrot_to_lam(yvals[j], xvals[i], ypole, xpole, angle);
		      yvals2D[j*nx+i] = phirot_to_phi(yvals[j], xvals[i], ypole, angle);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
921
922
923
924
		    }	    
	      }
	    else
	      {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
925
926
927
928
929
930
931
		for ( j = 0; j < ny; j++ )
		  for ( i = 0; i < nx; i++ )
		    {
		      xvals2D[j*nx+i] = xscale*xvals[i];
		      yvals2D[j*nx+i] = yscale*yvals[j];
		    }

932
		if ( gridtype == GRID_SINUSOIDAL )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
933
934
935
936
		  {
		    sinusoidal_to_geo(gridsize, xvals2D, yvals2D);
		    /* correct_sinxvals(nx, ny, xvals2D); */
		  }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
937
		else if ( gridtype == GRID_LAEA )
938
939
940
		  {
		    laea_to_geo(gridID1, gridsize, xvals2D, yvals2D);
		  }
941
		else if ( gridtype == GRID_LCC2 )
942
943
944
		  {
		    lcc2_to_geo(gridID1, gridsize, xvals2D, yvals2D);
		  }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
945
946
947
948
949
950
	      }
	  }

	gridDefXvals(gridID2, xvals2D);
	gridDefYvals(gridID2, yvals2D);

951
952
	if ( xvals2D ) free(xvals2D);
	if ( yvals2D ) free(yvals2D);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
953

954
955
	if ( !lbounds ) goto NO_BOUNDS;

Uwe Schulzweida's avatar
Uwe Schulzweida committed
956
957
958
959
960
961
962
963
964
965
	if ( gridtype == GRID_LCC )
	  {		
	    xbounds2D = (double *) malloc(4*gridsize*sizeof(double));
	    ybounds2D = (double *) malloc(4*gridsize*sizeof(double));

	    for ( j = 0; j < ny; j++ )
	      for ( i = 0; i < nx; i++ )
		{
		  index = j*4*nx + 4*i;

Uwe Schulzweida's avatar
Uwe Schulzweida committed
966
967
968
969
970
971
972
973
974
975
976
		  xbounds2D[index+0] = i+1.5;
		  ybounds2D[index+0] = j+1.5;

		  xbounds2D[index+1] = i+0.5;
		  ybounds2D[index+1] = j+1.5;

		  xbounds2D[index+2] = i+0.5;
		  ybounds2D[index+2] = j+0.5;

		  xbounds2D[index+3] = i+1.5;
		  ybounds2D[index+3] = j+0.5;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
977
978
		}

Uwe Schulzweida's avatar
Uwe Schulzweida committed
979
980
	    lcc_to_geo(gridID1, 4*gridsize, xbounds2D, ybounds2D);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
981
982
983
984
985
986
987
988
	    gridDefXbounds(gridID2, xbounds2D);
	    gridDefYbounds(gridID2, ybounds2D);

	    free(xbounds2D);
	    free(ybounds2D);
	  }
	else
	  {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
989
	    if ( gridInqXbounds(gridID1, NULL) )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
990
991
992
	      {
		xbounds = (double *) malloc(2*nx*sizeof(double));
		gridInqXbounds(gridID1, xbounds);
993
994
995
		if ( gridtype == GRID_LONLAT || gridtype == GRID_GAUSSIAN )
		  if ( check_range(2*nx, xbounds, -720, 720) )
		    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
996
		      cdoWarning("longitude bounds out of range, skipped!");
997
998
999
		      free(xbounds);
		      xbounds = NULL;
		    }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1000
1001
1002
1003
1004
1005
1006
	      }
	    else if ( nx > 1 )
	      {
		xbounds = (double *) malloc(2*nx*sizeof(double));
		gridGenXbounds(nx, xvals, xbounds);
	      }

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1007
	    if ( gridInqYbounds(gridID1, NULL) )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1008
1009
1010
	      {
		ybounds = (double *) malloc(2*ny*sizeof(double));
		gridInqYbounds(gridID1, ybounds);
1011
1012
1013
		if ( gridtype == GRID_LONLAT || gridtype == GRID_GAUSSIAN )
		  if ( check_range(2*ny, ybounds, -180, 180) )
		    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1014
		      cdoWarning("latitude bounds out of range, skipped!");
1015
1016
1017
		      free(ybounds);
		      ybounds = NULL;
		    }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1018
1019
1020
1021
	      }
	    else if ( ny > 1 )
	      {
		ybounds = (double *) malloc(2*ny*sizeof(double));
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1022
1023
1024
		if ( gridtype == GRID_SINUSOIDAL || 
		     gridtype == GRID_LAEA       || 
		     gridtype == GRID_LCC2 )
1025
1026
1027
		  gridGenYboundsM(ny, yvals, ybounds);
		else
		  gridGenYbounds(ny, yvals, ybounds);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
	      }

	    if ( xbounds && ybounds )
	      {
		xbounds2D = (double *) malloc(4*gridsize*sizeof(double));
		ybounds2D = (double *) malloc(4*gridsize*sizeof(double));

		if ( gridIsRotated(gridID1) )
		  {
		    gridGenRotBounds(gridID1, nx, ny, xbounds, ybounds, xbounds2D, ybounds2D);
		  }
		else
		  {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1041
1042
1043
		    if ( gridtype == GRID_SINUSOIDAL ||
			 gridtype == GRID_LAEA       || 
			 gridtype == GRID_LCC2 )
1044
1045
1046
1047
1048
1049
		      {
			for ( j = 0; j < ny; j++ )
			  for ( i = 0; i < nx; i++ )
			    {
			      index = j*4*nx + 4*i;

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1050
1051
			      xbounds2D[index+0] = xscale*xbounds[2*i];
			      ybounds2D[index+0] = yscale*ybounds[2*j];
1052

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1053
1054
1055
1056
1057
			      xbounds2D[index+1] = xscale*xbounds[2*i];
			      ybounds2D[index+1] = yscale*ybounds[2*j+1];

			      xbounds2D[index+2] = xscale*xbounds[2*i+1];
			      ybounds2D[index+2] = yscale*ybounds[2*j+1];
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1058

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1059
1060
			      xbounds2D[index+3] = xscale*xbounds[2*i+1];
			      ybounds2D[index+3] = yscale*ybounds[2*j];
1061
			    }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1062
1063
			
			if ( gridtype == GRID_SINUSOIDAL )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
			  {
			    sinusoidal_to_geo(4*gridsize, xbounds2D, ybounds2D);
			    /*
			    xvals2D = (double *) malloc(gridsize*sizeof(double));
			    for ( j = 0; j < 4; ++j )
			      {
				for ( i = 0; i < gridsize; ++i ) xvals2D[i] = xbounds2D[i*4+j];
				correct_sinxvals(nx, ny, xvals2D);
				for ( i = 0; i < gridsize; ++i ) xbounds2D[i*4+j] = xvals2D[i];
			      }
			    free(xvals2D);
			    */
			  }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1077
1078
1079
1080
			else if ( gridtype == GRID_LAEA )
			  laea_to_geo(gridID1, 4*gridsize, xbounds2D, ybounds2D);
			else if ( gridtype == GRID_LCC2 )
			  lcc2_to_geo(gridID1, 4*gridsize, xbounds2D, ybounds2D);
1081
1082
1083
1084
1085
1086
		      }
		    else
		      {
			gridGenXbounds2D(nx, ny, xbounds, xbounds2D);
			gridGenYbounds2D(nx, ny, ybounds, ybounds2D);
		      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1087
1088
1089
1090
1091
		  }
		
		gridDefXbounds(gridID2, xbounds2D);
		gridDefYbounds(gridID2, ybounds2D);
		
1092
1093
1094
1095
		if ( xbounds )  free(xbounds);
		if ( ybounds )  free(ybounds);
		if ( xbounds2D) free(xbounds2D);
		if ( ybounds2D) free(ybounds2D);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1096
1097
1098
	      }
	  }

1099
1100
1101
1102
1103
      NO_BOUNDS:

	if ( xvals ) free(xvals);
	if ( yvals ) free(yvals);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1104
1105
	gridCopyMask(gridID1, gridID2, gridsize);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1106
1107
1108
1109
	break;
      }
    default:
      {
1110
	Error("Grid type >%s< unsupported!", gridNamePtr(gridtype));
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1111
1112
1113
1114
1115
1116
1117
1118
	break;
      }
    }

  return (gridID2);
}


1119
int gridToUnstructured(int gridID1, int lbounds)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1120
1121
1122
1123
1124
1125
{
  int gridID2;
  int gridtype, gridsize;

  gridtype = gridInqType(gridID1);
  gridsize = gridInqSize(gridID1);
1126
  gridID2  = gridCreate(GRID_UNSTRUCTURED, gridsize);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1127
  gridDefPrec(gridID2, DATATYPE_FLT32);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1128
1129
1130
1131
1132
1133
	  
  switch (gridtype)
    {
    case GRID_LONLAT:
    case GRID_GAUSSIAN:
      {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1134
1135
	long i, j;
	int nx, ny;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
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
	double *xvals, *yvals;
	double *xvals2D, *yvals2D;

	gridDefXname(gridID2, "lon");
	gridDefYname(gridID2, "lat");
	gridDefXlongname(gridID2, "longitude");
	gridDefYlongname(gridID2, "latitude");
	gridDefXunits(gridID2, "degrees_east");
	gridDefYunits(gridID2, "degrees_north");

	gridDefNvertex(gridID2, 4);

	nx = gridInqXsize(gridID1);
	ny = gridInqYsize(gridID1);
	 
	gridDefXsize(gridID2, gridsize);
	gridDefYsize(gridID2, gridsize);

	xvals = (double *) malloc(nx*sizeof(double));
	yvals = (double *) malloc(ny*sizeof(double));

	xvals2D = (double *) malloc(gridsize*sizeof(double));
	yvals2D = (double *) malloc(gridsize*sizeof(double));

	gridInqXvals(gridID1, xvals);
	gridInqYvals(gridID1, yvals);

1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
	if ( gridIsRotated(gridID1) )
	  {
	    double xpole, ypole, angle;
	    
	    xpole = gridInqXpole(gridID1);
	    ypole = gridInqYpole(gridID1);
	    angle = gridInqAngle(gridID1);
		
	    for ( j = 0; j < ny; j++ )
	      for ( i = 0; i < nx; i++ )
		{
		  xvals2D[j*nx+i] = lamrot_to_lam(yvals[j], xvals[i], ypole, xpole, angle);
		  yvals2D[j*nx+i] = phirot_to_phi(yvals[j], xvals[i], ypole, angle);
		}
	  }
	else
	  {
	    for ( j = 0; j < ny; j++ )
	      for ( i = 0; i < nx; i++ )
		{
		  xvals2D[j*nx+i] = xvals[i];
		  yvals2D[j*nx+i] = yvals[j];
		}
	  }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1187
1188
1189
1190
1191
1192
1193

	gridDefXvals(gridID2, xvals2D);
	gridDefYvals(gridID2, yvals2D);

	free(xvals2D);
	free(yvals2D);

1194
	if ( lbounds )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1195
	  {
1196
1197
	    double *xbounds = NULL, *ybounds = NULL;
	    double *xbounds2D, *ybounds2D;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1198

1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
	    if ( gridInqXbounds(gridID1, NULL) )
	      {
		xbounds = (double *) malloc(2*nx*sizeof(double));
		gridInqXbounds(gridID1, xbounds);
	      }
	    else if ( nx > 1 )
	      {
		xbounds = (double *) malloc(2*nx*sizeof(double));
		gridGenXbounds(nx, xvals, xbounds);
	      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1209

1210
	    if ( gridInqYbounds(gridID1, NULL) )
1211
	      {
1212
1213
		ybounds = (double *) malloc(2*ny*sizeof(double));
		gridInqYbounds(gridID1, ybounds);
1214
	      }
1215
	    else if ( ny > 1 )
1216
	      {
1217
1218
		ybounds = (double *) malloc(2*ny*sizeof(double));
		gridGenYbounds(ny, yvals, ybounds);
1219
	      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1220

1221
1222
1223
1224
	    if ( xbounds && ybounds )
	      {
		xbounds2D = (double *) malloc(4*gridsize*sizeof(double));
		ybounds2D = (double *) malloc(4*gridsize*sizeof(double));
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1225

1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
		if ( gridIsRotated(gridID1) )
		  {
		    gridGenRotBounds(gridID1, nx, ny, xbounds, ybounds, xbounds2D, ybounds2D);
		  }
		else
		  {
		    gridGenXbounds2D(nx, ny, xbounds, xbounds2D);
		    gridGenYbounds2D(nx, ny, ybounds, ybounds2D);
		  }

		gridDefXbounds(gridID2, xbounds2D);
		gridDefYbounds(gridID2, ybounds2D);

		free(xbounds);
		free(ybounds);
		free(xbounds2D);
		free(ybounds2D);
	      }
	    }

	free(xvals);
	free(yvals);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1248

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1249
1250
	gridCopyMask(gridID1, gridID2, gridsize);

1251
1252
1253
1254
1255
1256
1257
1258
1259
	break;
      }
    case GRID_CURVILINEAR:
      {
	gridID2 = gridDuplicate(gridID1);
	gridChangeType(gridID2, GRID_UNSTRUCTURED);
	gridDefXsize(gridID2, gridsize);
	gridDefYsize(gridID2, gridsize);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1260
1261
1262
1263
	break;
      }
    case GRID_GME:
      {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1264
1265
	int nd, ni, ni2, ni3;
	long i, j;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1266
1267
1268
	int nv = 6;
	int *imask;
	double *xvals, *yvals;
1269
	double *xbounds = NULL, *ybounds = NULL;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1270
1271
1272
1273
1274
1275
1276
1277
1278

	nd  = gridInqGMEnd(gridID1);
	ni  = gridInqGMEni(gridID1);
	ni2 = gridInqGMEni2(gridID1);
	ni3 = gridInqGMEni3(gridID1);

	imask   = (int *) malloc(gridsize*sizeof(int));
	xvals   = (double *) malloc(gridsize*sizeof(double));
	yvals   = (double *) malloc(gridsize*sizeof(double));
1279
1280
1281
1282
1283
	if ( lbounds )
	  {
	    xbounds = (double *) malloc(nv*gridsize*sizeof(double));
	    ybounds = (double *) malloc(nv*gridsize*sizeof(double));
	  }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1284

1285
	gme_grid(lbounds, gridsize, xvals, yvals, xbounds, ybounds, imask, ni, nd, ni2, ni3);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1286
1287
1288
1289
1290
1291
	
	for ( i = 0; i < gridsize; i++ )
	  {
	    xvals[i] *= RAD2DEG;
	    yvals[i] *= RAD2DEG;

1292
1293
1294
1295
1296
1297
	    if ( lbounds )
	      for ( j = 0; j < nv; j++ )
		{
		  xbounds[i*nv + j] *= RAD2DEG;
		  ybounds[i*nv + j] *= RAD2DEG;
		}
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1298
1299
1300
1301
1302
1303
1304
1305
1306
	    /* printf("%d %g %g\n", i, xvals[i], yvals[i]); */
	  }
	
	gridDefXsize(gridID2, gridsize);
	gridDefYsize(gridID2, gridsize);

	gridDefXvals(gridID2, xvals);
	gridDefYvals(gridID2, yvals);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1307
	gridDefMaskGME(gridID2, imask);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1308
1309
1310

	gridDefNvertex(gridID2, nv);

1311
1312
1313
1314
1315
	if ( lbounds )
	  {
	    gridDefXbounds(gridID2, xbounds);
	    gridDefYbounds(gridID2, ybounds);
	  }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1316

1317
1318
	gridDefXunits(gridID2, "degrees_east");
	gridDefYunits(gridID2, "degrees_north");
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1319
1320
1321
1322

	free (imask);
	free (xvals);
	free (yvals);
1323
1324
	if ( xbounds ) free (xbounds);
	if ( ybounds ) free (ybounds);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1325
	
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1326
1327
	gridCopyMask(gridID1, gridID2, gridsize);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1328
1329
1330
1331
	break;
      }
    default:
      {
1332
	Error("Grid type >%s< unsupported!", gridNamePtr(gridtype));
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1333
1334
1335
1336
1337
1338
1339
	break;
      }
    }

  return (gridID2);
}

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
int gridCurvilinearToRegular(int gridID1)
{
  int gridID2 = -1;
  int gridtype, gridsize;
  long index;
  long i, j;
  int nx, ny;
  int lx = TRUE, ly = TRUE;
  double *xvals = NULL, *yvals = NULL;
  double *xvals2D = NULL, *yvals2D = NULL;
	
  gridtype = gridInqType(gridID1);
  gridsize = gridInqSize(gridID1);

  if ( gridtype != GRID_CURVILINEAR ) return (gridID2);

  nx = gridInqXsize(gridID1);
  ny = gridInqYsize(gridID1);
	
  xvals2D = (double *) malloc(gridsize*sizeof(double));
  yvals2D = (double *) malloc(gridsize*sizeof(double));

  gridInqXvals(gridID1, xvals2D);
  gridInqYvals(gridID1, yvals2D);

  xvals = (double *) malloc(nx*sizeof(double));
  yvals = (double *) malloc(ny*sizeof(double));

  for ( i = 0; i < nx; i++ ) xvals[i] = xvals2D[i];
  for ( j = 0; j < ny; j++ ) yvals[j] = yvals2D[j*nx];

  for ( j = 1; j < ny; j++ )
    for ( i = 0; i < nx; i++ )
      {
1375
	if ( fabs(xvals[i] - xvals2D[j*nx+i]) > 1.e-6 )
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
	  {
	    lx = FALSE;
	    j = ny;
	    break;
	  }
      }
	
  for ( i = 1; i < nx; i++ )
    for ( j = 0; j < ny; j++ )
      {
1386
	if ( fabs(yvals[j] - yvals2D[j*nx+i]) > 1.e-6 )
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
	  {
	    ly = FALSE;
	    i = nx;
	    break;
	  }
      }

  free(xvals2D);
  free(yvals2D);

  if ( lx && ly )
    {
      char xunits[CDI_MAX_NAME], yunits[CDI_MAX_NAME];
      
      gridID2  = gridCreate(GRID_LONLAT, gridsize);
      gridDefXsize(gridID2, nx);
      gridDefYsize(gridID2, ny);
      
      //  gridDefPrec(gridID2, DATATYPE_FLT32);

      gridInqXunits(gridID1, xunits);
      gridInqYunits(gridID1, yunits);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
1410
1411
      grid_to_degree(xunits, nx, xvals, "grid1 center lon");
      grid_to_degree(yunits, ny, yvals, "grid1 center lat");
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422

      gridDefXvals(gridID2, xvals);
      gridDefYvals(gridID2, yvals);
    }

  free(xvals);
  free(yvals);

  return (gridID2);
}

1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
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
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
#include <sys/stat.h>
/*
 * Search for filename.
 */
int search_file(const char *restrict directory, const char *restrict filename)
{
  struct stat buf;
  int status;

  status = stat(directory, &buf);

  if ( status == 0 )
    {
      status = stat(filename, &buf);
      if ( status == 0 ) return 0;
    }
  else
    {
      perror(directory);
    }

  return 1;
}

#if defined (HAVE_LIBCURL)
#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.h>
#include <errno.h>
#endif

/*
 * callback function for curl for writing the network retrieved grid file
 */
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
  size_t written;
  written = fwrite(ptr, size, nmemb, stream);
  return written;
}

/* code from grid_tools.2 */
int download_gridfile(const char *restrict uri, const char *restrict basename)
{
#if  defined  (HAVE_LIBCURL)
  // As curl_easy_init calls non-thread safe curl_global_init the libcurl developer advice
  // to call curl_global_init first and before potential thread spawning.

  CURLcode ret;  
  CURL *hd;
  double length;
  int status;
  int curlflags = CURL_GLOBAL_DEFAULT;

#if defined (CURL_GLOBAL_ACK_EINTR)
  curlflags |= CURL_GLOBAL_ACK_EINTR;
#endif

  ret = curl_global_init(curlflags);
  if(ret != 0)
    {
      fprintf(stderr, "ERROR: %s!\n", curl_easy_strerror(ret));
      return -1;
    }

  hd = curl_easy_init();
  if (hd == NULL) 
    {
      fprintf(stderr, "ERROR: could not get curl handler.\n");
      return -1;
    }
  else
    {
      FILE *fp;
      fp = fopen(basename, "w");
      if (fp == NULL)
	{
	  fprintf(stderr, "ERROR: could not open local output file %s. %s.\n", basename, strerror(errno));
	  return -1;
	}

      curl_easy_setopt(hd, CURLOPT_URL, uri);
      curl_easy_setopt(hd, CURLOPT_WRITEFUNCTION, write_data);
      curl_easy_setopt(hd, CURLOPT_WRITEDATA, fp);
      ret = curl_easy_perform(hd);
      if (ret == 0) 
	{
	  fclose(fp);
	  curl_easy_getinfo(hd, CURLINFO_SIZE_DOWNLOAD, &length);
	  if ( cdoVerbose ) cdoPrint("File %s downloaded - size: %.0lf byte", basename, length); 
	  curl_easy_cleanup(hd);
	  return 0;
	}
      else
	{
	  fclose(fp);
	  status = remove(basename);
	  if (status == -1) perror(basename);
	  fprintf(stderr, "ERROR: %s. Download %s failed.\n\n", curl_easy_strerror(ret), basename);
	  curl_easy_cleanup(hd);
	}
    }
#else
  cdoWarning("CURL support not compiled in!");
#endif  

  return 1;
}

1531

1532
1533
1534
1535
int referenceToGrid(int gridID1)
{
  int gridID2 = -1;
  int gridtype, gridsize;
1536
  int offset = 7;
1537
1538
  char griduri[8912];
  char gridpath[8912];
1539

Uwe Schulzweida's avatar