NCEPLIBS-g2c  1.6.4
g2_gribend.c
Go to the documentation of this file.
1 
6 #include <stdio.h>
7 #include "grib2.h"
8 
35 g2int g2_gribend(unsigned char *cgrib)
36 {
37 
38  g2int iofst, lencurr, len, ilen, isecnum;
39  g2int ierr = 0, lengrib;
40  static unsigned char G = 0x47; /* 'G' */
41  static unsigned char R = 0x52; /* 'R' */
42  static unsigned char I = 0x49; /* 'I' */
43  static unsigned char B = 0x42; /* 'B' */
44  static unsigned char seven = 0x37; /* '7' */
45 
46  /* Check to see if beginning of GRIB message exists. */
47  if (cgrib[0] != G || cgrib[1] != R || cgrib[2] != I || cgrib[3] != B) {
48  printf("g2_gribend: GRIB not found in given message.\n");
49  ierr = -1;
50  return (ierr);
51  }
52 
53  /* Get current length of GRIB message. */
54  gbit(cgrib, &lencurr, 96, 32);
55 
56  /* Loop through all current sections of the GRIB message to find
57  * the last section number. */
58  len = 16; /* Length of Section 0. */
59  for (;;) {
60  /* Get number and length of next section. */
61  iofst = len * 8;
62  gbit(cgrib, &ilen, iofst, 32);
63  iofst = iofst + 32;
64  gbit(cgrib, &isecnum, iofst, 8);
65  len = len + ilen;
66  /* Exit loop if last section reached. */
67  if (len == lencurr)
68  break;
69  /* If byte count for each section doesn't match current
70  * total length, then there is a problem. */
71  if (len > lencurr) {
72  printf("g2_gribend: Section byte counts don''t add to total.\n");
73  printf("g2_gribend: Sum of section byte counts = %d\n", (int)len);
74  printf("g2_gribend: Total byte count in Section 0 = %d\n", (int)lencurr);
75  ierr = -3;
76  return (ierr);
77  }
78  }
79 
80  /* Can only add End Section (Section 8) after Section 7. */
81  if (isecnum != 7 ) {
82  printf("g2_gribend: Section 8 can only be added after Section 7.\n");
83  printf("g2_gribend: Section %ld was the last found in given GRIB message.\n", isecnum);
84  ierr = -4;
85  return (ierr);
86  }
87 
88  /* Add Section 8 - End Section */
89  cgrib[lencurr] = seven;
90  cgrib[lencurr + 1] = seven;
91  cgrib[lencurr + 2] = seven;
92  cgrib[lencurr + 3] = seven;
93 
94  /* Update current byte total of message in Section 0. */
95  lengrib = lencurr + 4;
96  sbit(cgrib, &lengrib, 96, 32);
97 
98  return (lengrib);
99 
100 }
g2int g2_gribend(unsigned char *cgrib)
This routine finalizes a GRIB2 message after all grids and fields have been added.
Definition: g2_gribend.c:35
void gbit(unsigned char *in, g2int *iout, g2int iskip, g2int nbyte)
Get bits - unpack bits: Extract arbitrary size values from a packed bit string, right justifying each...
Definition: gbits.c:20
void sbit(unsigned char *out, g2int *in, g2int iskip, g2int nbyte)
Store bits - put arbitrary size values into a packed bit string, taking the low order bits from each ...
Definition: gbits.c:38
Header file for NCEPLIBS-g2c library.
int64_t g2int
Long integer type.
Definition: grib2.h:20