Merge remote-tracking branch 'origin/release-v4.6.1'
[WRF.git] / external / io_grib1 / WGRIB / seekgrib.c
blobdc64385f2884f3b901e12025e067f7be0916ca41
1 /*
2 * find next grib header
4 * file = what do you think?
5 * pos = initial position to start looking at ( = 0 for 1st call)
6 * returns with position of next grib header (units=bytes)
7 * len_grib = length of the grib record (bytes)
8 * buffer[buf_len] = buffer for reading/writing
10 * returns (char *) to start of GRIB header+PDS
11 * NULL if not found
13 * adapted from SKGB (Mark Iredell)
15 * v1.1 9/94 Wesley Ebisuzaki
16 * v1.2 3/96 Wesley Ebisuzaki handles short records at end of file
17 * v1.3 8/96 Wesley Ebisuzaki increase NTRY from 3 to 100 for the folks
18 * at Automation decided a 21 byte WMO bulletin header wasn't long
19 * enough and decided to go to an 8K header.
20 * v1.4 11/10/2001 D. Haalman, looks at entire file, does not try
21 * to read past EOF
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stddef.h>
26 #include "grib.h"
28 #ifndef min
29 #define min(a,b) ((a) < (b) ? (a) : (b))
30 #endif
32 #define NTRY 100
33 /* #define LEN_HEADER_PDS (28+42+100) */
34 #define LEN_HEADER_PDS (28+8)
36 unsigned char *seek_grib(FILE *file, long *pos, long *len_grib,
37 unsigned char *buffer, unsigned int buf_len) {
39 int i, j, len;
41 j = 1;
42 clearerr(file);
43 while ( !feof(file) ) {
45 if (fseek(file, *pos, SEEK_SET) == -1) break;
46 i = fread(buffer, sizeof (unsigned char), buf_len, file);
47 if (ferror(file)) break;
48 len = i - LEN_HEADER_PDS;
50 for (i = 0; i < len; i++) {
51 if (buffer[i] == 'G' && buffer[i+1] == 'R' && buffer[i+2] == 'I'
52 && buffer[i+3] == 'B' && buffer[i+7] == 1) {
53 *pos = i + *pos;
54 *len_grib = (buffer[i+4] << 16) + (buffer[i+5] << 8) +
55 buffer[i+6];
56 return (buffer+i);
60 if (j++ == NTRY) {
61 fprintf(stderr,"found unidentified data \n");
62 /* break; // stop seeking after NTRY records */
65 *pos = *pos + (buf_len - LEN_HEADER_PDS);
68 *len_grib = 0;
69 return (unsigned char *) NULL;