OpenCPN Partial API docs
Loading...
Searching...
No Matches
tcmgr.cpp
Go to the documentation of this file.
1/***************************************************************************
2 * Copyright (C) 2010 by David S. Register *
3 * *
4 * This program is free software; you can redistribute it and/or modify *
5 * it under the terms of the GNU General Public License as published by *
6 * the Free Software Foundation; either version 2 of the License, or *
7 * (at your option) any later version. *
8 * *
9 * This program is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU General Public License for more details. *
13 * *
14 * You should have received a copy of the GNU General Public License *
15 * along with this program; if not, see <https://www.gnu.org/licenses/>. *
16 **************************************************************************/
17
24#include <wx/wxprec.h>
25#ifndef WX_PRECOMP
26#include <wx/wx.h>
27#endif // precompiled headers
28#include <wx/hashmap.h>
29
30#include <stdlib.h>
31#include <math.h>
32#include <time.h>
33
34#include "model/georef.h"
35#include "model/logger.h"
36
37#include "gui_lib.h"
38#include "dychart.h"
39#include "navutil.h"
40#include "tcmgr.h"
41
43
44//-----------------------------------------------------------------------------------
45// TIDELIB
46//-----------------------------------------------------------------------------------
47
48// Static variables for the TIDELIB
49
50static time_t s_next_epoch = TIDE_BAD_TIME; /* next years newyears */
51static time_t s_this_epoch = TIDE_BAD_TIME; /* this years newyears */
52static int s_this_year = -1;
53
54static double time2dt_tide(time_t t, int deriv, IDX_entry *pIDX);
55static int yearoftimet(time_t t);
56static void happy_new_year(IDX_entry *pIDX, int new_year);
57static void set_epoch(IDX_entry *pIDX, int year);
58
59static double time2tide(time_t t, IDX_entry *pIDX) {
60 return time2dt_tide(t, 0, pIDX);
61}
62
67double BOGUS_amplitude(double mpy, IDX_entry *pIDX) {
68 Station_Data *pmsd = pIDX->pref_sta_data;
69
70 if (!pmsd->have_BOGUS) // || !convert_BOGUS) // Added mgh
71 return (mpy * pIDX->max_amplitude);
72 else {
73 if (mpy >= 0.0)
74 return (sqrt(mpy * pIDX->max_amplitude));
75 else
76 return (-sqrt(-mpy * pIDX->max_amplitude));
77 }
78}
79
80/* Calculate the denormalized tide. */
81double time2atide(time_t t, IDX_entry *pIDX) {
82 return BOGUS_amplitude(time2tide(t, pIDX), pIDX) + pIDX->pref_sta_data->DATUM;
83}
84
85/* Next high tide, low tide, transition of the mark level, or some
86 * combination.
87 * Bit Meaning
88 * 0 low tide
89 * 1 high tide
90 * 2 falling transition
91 * 3 rising transition
92 */
93int next_big_event(time_t *tm, IDX_entry *pIDX) {
94 double p, q;
95 int flags = 0, slope = 0;
96 p = time2atide(*tm, pIDX);
97 *tm += 60;
98 q = time2atide(*tm, pIDX);
99 *tm += 60;
100 if (p < q) slope = 1;
101 while (1) {
102 if ((slope == 1 && q < p) || (slope == 0 && p < q)) {
103 /* Tide event */
104 flags |= (1 << slope);
105 }
106 /* Modes in which to return mark transitions: */
107 /* -text (no -graph) */
108 /* -graph (no -text) */
109 /* -ppm */
110 /* -gif */
111 /* -ps */
112
113 // if (mark && ((text && !graphmode) || (!text && graphmode)
114 // || ppm || gif || ps))
115 // int marklev = 0;
116#if (0)
117 if (0)
118 if ((p > marklev && q <= marklev) || (p < marklev && q >= marklev)) {
119 /* Transition event */
120 if (p < q)
121 flags |= 8;
122 else
123 flags |= 4;
124 if (!(flags & 3)) {
125 /* If we're incredibly unlucky, we could miss a tide event if we
126 * don't check for it here:
127 *
128 * . <---- Value that would be
129 * returned
130 * ----------- Mark level
131 * . .
132 */
133 p = q;
134 q = time2atide(*tm, pIDX);
135 if ((slope == 1 && q < p) || (slope == 0 && p < q)) {
136 /* Tide event */
137 flags |= (1 << slope);
138 }
139 }
140 }
141#endif
142
143 if (flags) {
144 *tm -= 60;
145 /* Don't back up over a transition event, but do back up to where the
146 * tide changed if possible. If they happen at the same
147 * time, then we're off by a minute on the tide, but if we back it up it
148 * will get snagged on the transition event over and over. */
149 if (flags < 4) *tm -= 60;
150 return flags;
151 }
152 p = q;
153 q = time2atide(*tm, pIDX);
154 *tm += 60;
155 }
156}
157
158/* Estimate the normalized mean tide level around a particular time by
159 * summing only the long-term constituents. */
160/* Does not do any blending around year's end. */
161/* This is used only by time2asecondary for finding the mean tide level */
162double time2mean(time_t t, IDX_entry *pIDX) {
163 double tide = 0.0;
164 int a;
165 int new_year = yearoftimet(t);
166 if (pIDX->epoch_year != new_year) happy_new_year(pIDX, new_year);
167
168 for (a = 0; a < pIDX->num_csts; a++) {
169 if (pIDX->m_cst_speeds[a] < 6e-6) {
170 tide += pIDX->m_work_buffer[a] *
171 cos(pIDX->m_cst_speeds[a] * ((long)(t - pIDX->epoch) +
172 pIDX->pref_sta_data->meridian) +
173 pIDX->m_cst_epochs[a][pIDX->epoch_year - pIDX->first_year] -
174 pIDX->pref_sta_data->epoch[a]);
175 }
176 }
177
178 return tide;
179}
180
181/* If offsets are in effect, interpolate the 'corrected' denormalized
182 * tide. The normalized is derived from this, instead of the other way
183 * around, because the application of height offsets requires the
184 * denormalized tide. */
185double time2asecondary(time_t t, IDX_entry *pIDX) {
186 time_t tadj = t + pIDX->station_tz_offset;
187
188 /* Get rid of the normals. */
189 if (!(pIDX->have_offsets)) return time2atide(tadj, pIDX);
190
191 {
192 /* Intervalwidth of 14 (was originally 13) failed on this input:
193 * -location Dublon -hloff +0.0001 -gstart 1997:09:10:00:00 -raw
194 * 1997:09:15:00:00
195 */
196#define intervalwidth 15
197#define stretchfactor 3
198
199 static time_t lowtime = 0, hightime = 0;
200 static double lowlvl, highlvl; /* Normalized tide levels for MIN, MAX */
201 time_t T; /* Adjusted t */
202 double S, Z, HI, HS, magicnum;
203 time_t interval = 3600 * intervalwidth;
204 long difflow, diffhigh;
205 int badlowflag = 0, badhighflag = 0;
206
207 /* Algorithm by Jean-Pierre Lapointe (scipur@collegenotre-dame.qc.ca) */
208 /* as interpreted, munged, and implemented by DWF */
209
210 /* This is the initial guess (average of time offsets) */
211 // T = t - (httimeoff + lttimeoff) / 2;
212 T = tadj - (pIDX->IDX_ht_time_off * 60 + pIDX->IDX_lt_time_off * 60) / 2;
213 /* The usage of an estimate of mean tide level here is to correct
214 * for seasonal changes in tide level. Previously I had simply
215 * used the zero of the tide function as the mean, but this gave bad results
216 * around summer and winter for locations with large seasonal variations. */
217 // printf("-----time2asecondary %ld %ld %d %d\n", t, T,
218 // pIDX->IDX_ht_time_off ,pIDX->IDX_lt_time_off);
219
220 Z = time2mean(T, pIDX);
221 S = time2tide(T, pIDX) - Z;
222
223 /* Find MAX and MIN. I use the highest high tide and the lowest
224 * low tide over a 26 hour period, but I allow the interval to
225 * stretch a lot if necessary to avoid creating discontinuities. The
226 * heuristic used is not perfect but will hopefully be good
227 * enough.
228 *
229 * It is an assumption in the algorithm that the tide level will
230 * be above the mean tide level for MAX and below it for MIN. A
231 * changeover occurs at mean tide level. It would be nice to
232 * always use the two tides that immediately bracket T and to put
233 * the changeover at mid tide instead of always at mean tide
234 * level, since this would eliminate much of the inaccuracy.
235 * Unfortunately if you change the location of the changeover it
236 * causes the tide function to become discontinuous.
237 *
238 * Now that I'm using time2mean, the changeover does move, but so
239 * slowly that it makes no difference.
240 */
241
242 if (lowtime < T)
243 difflow = T - lowtime;
244 else
245 difflow = lowtime - T;
246 if (hightime < T)
247 diffhigh = T - hightime;
248 else
249 diffhigh = hightime - T;
250
251 /* Update MIN? */
252 if (difflow > interval * stretchfactor) badlowflag = 1;
253 if (badlowflag || (difflow > interval && S > 0)) {
254 time_t tt;
255 double tl;
256 tt = T - interval;
257 next_big_event(&tt, pIDX);
258 lowlvl = time2tide(tt, pIDX);
259 lowtime = tt;
260 while (tt < T + interval) {
261 next_big_event(&tt, pIDX);
262 tl = time2tide(tt, pIDX);
263 if (tl < lowlvl && tt < T + interval) {
264 lowlvl = tl;
265 lowtime = tt;
266 }
267 }
268 }
269 /* Update MAX? */
270 if (diffhigh > interval * stretchfactor) badhighflag = 1;
271 if (badhighflag || (diffhigh > interval && S < 0)) {
272 time_t tt;
273 double tl;
274 tt = T - interval;
275 next_big_event(&tt, pIDX);
276 highlvl = time2tide(tt, pIDX);
277 hightime = tt;
278 while (tt < T + interval) {
279 next_big_event(&tt, pIDX);
280 tl = time2tide(tt, pIDX);
281 if (tl > highlvl && tt < T + interval) {
282 highlvl = tl;
283 hightime = tt;
284 }
285 }
286 }
287
288#if 0
289 /* UNFORTUNATELY there are times when the tide level NEVER CROSSES
290 * THE MEAN for extended periods of time. ARRRGH! */
291 if (lowlvl >= 0.0)
292 lowlvl = -1.0;
293 if (highlvl <= 0.0)
294 highlvl = 1.0;
295#endif
296 /* Now that I'm using time2mean, I should be guaranteed to get
297 * an appropriate low and high. */
298
299 /* Improve the initial guess. */
300 if (S > 0)
301 magicnum = 0.5 * S / fabs(highlvl - Z);
302 else
303 magicnum = 0.5 * S / fabs(lowlvl - Z);
304 // T = T - magicnum * (httimeoff - lttimeoff);
305 T = T - (time_t)(magicnum * ((pIDX->IDX_ht_time_off * 60) -
306 (pIDX->IDX_lt_time_off * 60)));
307 HI = time2tide(T, pIDX);
308
309 // Correct the amplitude offsets for BOGUS knot^2 units
310 double ht_off, lt_off;
311 if (pIDX->pref_sta_data->have_BOGUS) {
312 ht_off = pIDX->IDX_ht_off *
313 pIDX->IDX_ht_off; // Square offset in kts to adjust for kts^2
314 lt_off = pIDX->IDX_lt_off * pIDX->IDX_lt_off;
315 } else {
316 ht_off = pIDX->IDX_ht_off;
317 lt_off = pIDX->IDX_lt_off;
318 }
319
320 /* Denormalize and apply the height offsets. */
321 HI = BOGUS_amplitude(HI, pIDX) + pIDX->pref_sta_data->DATUM;
322 {
323 double RH = 1.0, RL = 1.0, HH = 0.0, HL = 0.0;
324 RH = pIDX->IDX_ht_mpy;
325 HH = ht_off;
326 RL = pIDX->IDX_lt_mpy;
327 HL = lt_off;
328
329 /* I patched the usage of RH and RL to avoid big ugly
330 * discontinuities when they are not equal. -- DWF */
331
332 HS = HI * ((RH + RL) / 2 + (RH - RL) * magicnum) + (HH + HL) / 2 +
333 (HH - HL) * magicnum;
334 }
335
336 return HS;
337 }
338}
339
340/*
341 * We will need a function for tidal height as a function of time
342 * which is continuous (and has continuous first and second derivatives)
343 * for all times.
344 *
345 * Since the epochs & multipliers for the tidal constituents change
346 * with the year, the regular time2tide(t) function has small
347 * discontinuities at new years. These discontinuities really
348 * fry the fast root-finders.
349 *
350 * We will eliminate the new-years discontinuities by smoothly
351 * interpolating (or "blending") between the tides calculated with one
352 * year's coefficients, and the tides calculated with the next year's
353 * coefficients.
354 *
355 * i.e. for times near a new years, we will "blend" a tide
356 * as follows:
357 *
358 * tide(t) = tide(year-1, t)
359 * + w((t - t0) / Tblend) * (tide(year,t) - tide(year-1,t))
360 *
361 * Here: t0 is the time of the nearest new-year.
362 * tide(year-1, t) is the tide calculated using the coefficients
363 * for the year just preceding t0.
364 * tide(year, t) is the tide calculated using the coefficients
365 * for the year which starts at t0.
366 * Tblend is the "blending" time scale. This is set by
367 * the macro TIDE_BLEND_TIME, currently one hour.
368 * w(x) is the "blending function", whice varies smoothly
369 * from 0, for x < -1 to 1 for x > 1.
370 *
371 * Derivatives of the blended tide can be evaluated in terms of derivatives
372 * of w(x), tide(year-1, t), and tide(year, t). The blended tide is
373 * guaranteed to have as many continuous derivatives as w(x). */
374
375/* time2dt_tide(time_t t, int n)
376 *
377 * Calculate nth time derivative the normalized tide.
378 *
379 * Notes: This function does not check for changes in year.
380 * This is important to our algorithm, since for times near
381 * new years, we interpolate between the tides calculated
382 * using one years coefficients, and the next years coefficients.
383 *
384 * Except for this detail, time2dt_tide(t,0) should return a value
385 * identical to time2tide(t).
386 */
387double _time2dt_tide(time_t t, int deriv, IDX_entry *pIDX) {
388 double dt_tide = 0.0;
389 int a, b;
390 double term, tempd;
391
392 tempd = M_PI / 2.0 * deriv;
393 for (a = 0; a < pIDX->num_csts; a++) {
394 term = pIDX->m_work_buffer[a] *
395 cos(tempd +
396 pIDX->m_cst_speeds[a] *
397 ((long)(t - pIDX->epoch) + pIDX->pref_sta_data->meridian) +
398 pIDX->m_cst_epochs[a][pIDX->epoch_year - pIDX->first_year] -
399 pIDX->pref_sta_data->epoch[a]);
400 for (b = deriv; b > 0; b--) term *= pIDX->m_cst_speeds[a];
401 dt_tide += term;
402 }
403 return dt_tide;
404}
405
406/* blend_weight (double x, int deriv)
407 *
408 * Returns the value nth derivative of the "blending function" w(x):
409 *
410 * w(x) = 0, for x <= -1
411 *
412 * w(x) = 1/2 + (15/16) x - (5/8) x^3 + (3/16) x^5,
413 * for -1 < x < 1
414 *
415 * w(x) = 1, for x >= 1
416 *
417 * This function has the following desirable properties:
418 *
419 * w(x) is exactly either 0 or 1 for |x| > 1
420 *
421 * w(x), as well as its first two derivatives are continuous for all x.
422 */
423static double blend_weight(double x, int deriv) {
424 double x2 = x * x;
425
426 if (x2 >= 1.0) return deriv == 0 && x > 0.0 ? 1.0 : 0.0;
427
428 switch (deriv) {
429 case 0:
430 return ((3.0 * x2 - 10.0) * x2 + 15.0) * x / 16.0 + 0.5;
431 case 1:
432 return ((x2 - 2.0) * x2 + 1.0) * (15.0 / 16.0);
433 case 2:
434 return (x2 - 1.0) * x * (15.0 / 4.0);
435 }
436 return (0); // mgh+ to get rid of compiler warning
437}
438
439/*
440 * This function does the actual "blending" of the tide
441 * and its derivatives.
442 */
443double blend_tide(time_t t, unsigned int deriv, int first_year, double blend,
444 IDX_entry *pIDX) {
445 double fl[TIDE_MAX_DERIV + 1];
446 double fr[TIDE_MAX_DERIV + 1];
447 double *fp = fl;
448 double w[TIDE_MAX_DERIV + 1];
449 double fact = 1.0;
450 double f;
451 unsigned int n;
452
453 /*
454 * If we are already happy_new_year()ed into one of the two years
455 * of interest, compute that years tide values first.
456 */
457 int year = yearoftimet(t);
458 if (year == first_year + 1)
459 fp = fr;
460 else if (year != first_year)
461 happy_new_year(pIDX, first_year);
462 for (n = 0; n <= deriv; n++) fp[n] = _time2dt_tide(t, n, pIDX);
463
464 /*
465 * Compute tide values for the other year of interest,
466 * and the needed values of w(x) and its derivatives.
467 */
468 if (fp == fl) {
469 happy_new_year(pIDX, first_year + 1);
470 fp = fr;
471 } else {
472 happy_new_year(pIDX, first_year);
473 fp = fl;
474 }
475 for (n = 0; n <= deriv; n++) {
476 fp[n] = _time2dt_tide(t, n, pIDX);
477 w[n] = blend_weight(blend, n);
478 }
479
480 /*
481 * Do the blending.
482 */
483
484 f = fl[deriv];
485 for (n = 0; n <= deriv; n++) {
486 f += fact * w[n] * (fr[deriv - n] - fl[deriv - n]);
487 fact *= (double)(deriv - n) / (n + 1) * (1.0 / TIDE_BLEND_TIME);
488 }
489 printf(" %ld %g %g %g %g\n", (long)t, blend, fr[0], fl[0], f);
490 return f;
491}
492
493static double time2dt_tide(time_t t, int deriv, IDX_entry *pIDX) {
494 int new_year;
495 int yott = yearoftimet(t);
496 new_year = yott;
497
498 /* Make sure our values of next_epoch and epoch are up to date. */
499 if (new_year != s_this_year) {
500 if (new_year + 1 < pIDX->first_year + pIDX->num_epochs) {
501 set_epoch(pIDX, new_year + 1);
502 s_next_epoch = pIDX->epoch;
503 } else
504 s_next_epoch = TIDE_BAD_TIME;
505
506 happy_new_year(pIDX, s_this_year = new_year);
507 s_this_epoch = pIDX->epoch;
508 }
509
510 /*
511 * If we're close to either the previous or the next
512 * new years we must blend the two years tides.
513 */
514 if (t - s_this_epoch <= TIDE_BLEND_TIME && s_this_year > pIDX->first_year)
515 return blend_tide(t, deriv, s_this_year - 1,
516 (double)(t - s_this_epoch) / TIDE_BLEND_TIME, pIDX);
517 else if (s_next_epoch - t <= TIDE_BLEND_TIME &&
518 s_this_year + 1 < pIDX->first_year + pIDX->num_epochs)
519 return blend_tide(t, deriv, s_this_year,
520 -(double)(s_next_epoch - t) / TIDE_BLEND_TIME, pIDX);
521
522 /*
523 * Else, we're far enough from newyears to ignore the blending.
524 */
525 if (pIDX->epoch_year != new_year) happy_new_year(pIDX, new_year);
526
527 return _time2dt_tide(t, deriv, pIDX);
528}
529
530/* Figure out max amplitude over all the years in the node factors table. */
531/* This function by Geoffrey T. Dairiki */
532void figure_max_amplitude(IDX_entry *pIDX) {
533 int i, a;
534
535 if (pIDX->max_amplitude == 0.0) {
536 for (i = 0; i < pIDX->num_nodes; i++) {
537 double year_amp = 0.0;
538
539 for (a = 0; a < pIDX->num_csts; a++)
540 year_amp += pIDX->pref_sta_data->amplitude[a] * pIDX->m_cst_nodes[a][i];
541 if (year_amp > pIDX->max_amplitude) pIDX->max_amplitude = year_amp;
542 }
543 }
544}
545
546/* Figure out normalized multipliers for constituents for a particular year. */
547void figure_multipliers(IDX_entry *pIDX, int year) {
548 int a;
549
550 figure_max_amplitude(pIDX);
551 for (a = 0; a < pIDX->num_csts; a++) {
552 pIDX->m_work_buffer[a] = pIDX->pref_sta_data->amplitude[a] *
553 pIDX->m_cst_nodes[a][year - pIDX->first_year] /
554 pIDX->max_amplitude; // BOGUS_amplitude?
555 }
556}
557
558/* This idiotic function is needed by the new tm2gmt. */
559#define compare_int(a, b) (((int)(a)) - ((int)(b)))
560int compare_tm(struct tm *a, struct tm *b) {
561 int temp;
562 /* printf ("A is %d:%d:%d:%d:%d:%d B is %d:%d:%d:%d:%d:%d\n",
563 * a->tm_year+1900, a->tm_mon+1, a->tm_mday, a->tm_hour,
564 * a->tm_min, a->tm_sec,
565 * b->tm_year+1900, b->tm_mon+1, b->tm_mday, b->tm_hour,
566 * b->tm_min, b->tm_sec); */
567
568 temp = compare_int(a->tm_year, b->tm_year);
569 if (temp) return temp;
570 temp = compare_int(a->tm_mon, b->tm_mon);
571 if (temp) return temp;
572 temp = compare_int(a->tm_mday, b->tm_mday);
573 if (temp) return temp;
574 temp = compare_int(a->tm_hour, b->tm_hour);
575 if (temp) return temp;
576 temp = compare_int(a->tm_min, b->tm_min);
577 if (temp) return temp;
578 return compare_int(a->tm_sec, b->tm_sec);
579}
580
581/* Convert a struct tm in GMT back to a time_t. isdst is ignored, since
582 * it never should have been needed by mktime in the first place.
583 */
584time_t tm2gmt(struct tm *ht) {
585 time_t guess, newguess, thebit;
586 int loopcounter, compare;
587 struct tm *gt;
588
589 guess = 0;
590 loopcounter = (sizeof(time_t) * 8) - 1;
591 thebit = ((time_t)1) << (loopcounter - 1);
592
593 /* For simplicity, I'm going to insist that the time_t we want is
594 * positive. If time_t is signed, skip the sign bit.
595 */
596 if ((signed long)thebit < (time_t)(0)) {
597 /* You can't just shift thebit right because it propagates the sign bit. */
598 loopcounter--;
599 thebit = ((time_t)1) << (loopcounter - 1);
600 }
601
602 for (; loopcounter; loopcounter--) {
603 newguess = guess | thebit;
604 gt = gmtime(&newguess);
605 if (NULL != gt) {
606 compare = compare_tm(gt, ht);
607 if (compare <= 0) guess = newguess;
608 }
609 thebit >>= 1;
610 }
611
612 return guess;
613}
614
615static int yearoftimet(time_t t) { return ((gmtime(&t))->tm_year) + 1900; }
616
617/* Calculate time_t of the epoch. */
618static void set_epoch(IDX_entry *pIDX, int year) {
619 struct tm ht;
620
621 ht.tm_year = year - 1900;
622 ht.tm_sec = ht.tm_min = ht.tm_hour = ht.tm_mon = 0;
623 ht.tm_mday = 1;
624 pIDX->epoch = tm2gmt(&ht);
625}
626
627/* Re-initialize for a different year */
628static void happy_new_year(IDX_entry *pIDX, int new_year) {
629 pIDX->epoch_year = new_year;
630 figure_multipliers(pIDX, new_year);
631 set_epoch(pIDX, new_year);
632}
633
634// TCMgr Implementation
635TCMgr::TCMgr() {}
636
637TCMgr::~TCMgr() { PurgeData(); }
638
639void TCMgr::PurgeData() {
640 m_Combined_IDX_array.clear();
641
642 // Delete all the data sources
643 m_source_array.Clear();
644}
645
646TC_Error_Code TCMgr::LoadDataSources(std::vector<std::string> &sources) {
647 PurgeData();
648
649 // Take a copy of dataset file name array
650 m_sourcefile_array.clear();
651 m_sourcefile_array = sources;
652
653 int num_IDX = 0;
654
655 for (auto src : sources) {
656 TCDataSource *s = new TCDataSource;
657 TC_Error_Code r = s->LoadData(src);
658 if (r != TC_NO_ERROR) {
659 wxString msg;
660 msg.Printf(" Error loading Tide/Currect data source %s ", src.c_str());
661 if (r == TC_FILE_NOT_FOUND)
662 msg += "Error Code: TC_FILE_NOT_FOUND";
663 else {
664 wxString msg1;
665 msg1.Printf("Error code: %d", r);
666 msg += msg1;
667 }
668 wxLogMessage(msg);
669 delete s;
670 } else {
671 m_source_array.Add(s);
672
673 for (int k = 0; k < s->GetMaxIndex(); k++) {
674 IDX_entry *pIDX = s->GetIndexEntry(k);
675 pIDX->IDX_rec_num = num_IDX;
676 num_IDX++;
677 m_Combined_IDX_array.push_back(pIDX);
678 }
679 }
680 }
681
682 bTCMReady = true;
683
684 if (m_Combined_IDX_array.empty())
685 OCPNMessageBox(
686 NULL, _("It seems you have no tide/current harmonic data installed."),
687 _("OpenCPN Info"), wxOK | wxCENTER);
688
689 ScrubCurrentDepths();
690 return TC_NO_ERROR;
691}
692
693void TCMgr::ScrubCurrentDepths() {
694 // Process Current stations reporting values at multiple depths
695 // Identify and mark the shallowest record, as being most usable to OCPN
696 // users
697
698 WX_DECLARE_STRING_HASH_MAP(int, currentDepth_index_hash);
699
700 currentDepth_index_hash hash1;
701
702 for (int i = 1; i < Get_max_IDX() + 1; i++) {
703 IDX_entry *a = (IDX_entry *)GetIDX_entry(i);
704 if (a->IDX_type == 'C') {
705 if (a->current_depth > 0) {
706 int depth_a = a->current_depth;
707
708 // We formulate the hash map with geo-location as the keys
709 // Using "doubles" as hashmap key values is dangerous, especially
710 // cross-platform So, we a printf-ed string of lat/lon for hash key,
711 // This is relatively inefficient. but tolerable in this little used
712 // method.
713
714 wxString key1;
715 key1.Printf("%10.6f %10.6f", a->IDX_lat, a->IDX_lon);
716
717 currentDepth_index_hash::iterator it = hash1.find(key1);
718 if (it == hash1.end()) {
719 // Key not found, needs to be added
720 hash1[key1] = i;
721 } else {
722 // Check the depth value at the referenced index
723 // if less than the current depth, replace the hashmap value
724 IDX_entry *b = (IDX_entry *)GetIDX_entry(it->second);
725 std::string bName(b->IDX_station_name);
726 int depth_b = b->current_depth;
727 if (depth_a < depth_b) {
728 hash1[key1] = i;
729 b->b_skipTooDeep = 1; // mark deeper index to skip display
730 } else {
731 a->b_skipTooDeep = 1; // mark deeper index to skip display
732 }
733 }
734 }
735 }
736 }
737}
738
739const IDX_entry *TCMgr::GetIDX_entry(int index) const {
740 if ((unsigned int)index < m_Combined_IDX_array.size())
741 return m_Combined_IDX_array[index];
742 else
743 return NULL;
744}
745
746bool TCMgr::GetTideOrCurrent(time_t t, int idx, float &tcvalue, float &dir) {
747 // Return a sensible value of 0,0 by default
748 dir = 0;
749 tcvalue = 0;
750
751 // Load up this location data
752 IDX_entry *pIDX = m_Combined_IDX_array[idx]; // point to the index entry
753
754 if (!pIDX) {
755 dir = 0;
756 tcvalue = 0;
757 return false;
758 }
759
760 if (!pIDX->IDX_Useable) {
761 dir = 0;
762 tcvalue = 0;
763 return (false); // no error, but unuseable
764 }
765
766 if (pIDX->pDataSource) {
767 if (pIDX->pDataSource->LoadHarmonicData(pIDX) != TC_NO_ERROR) return false;
768 }
769
770 pIDX->max_amplitude = 0.0; // Force multiplier re-compute
771 int yott = yearoftimet(t);
772
773 happy_new_year(pIDX, yott); // Calculate new multipliers
774
775 // Finally, calculate the tide/current
776
777 double level = time2asecondary(t + (00 * 60), pIDX); // 300. 240
778 if (level >= 0)
779 dir = pIDX->IDX_flood_dir;
780 else
781 dir = pIDX->IDX_ebb_dir;
782
783 tcvalue = level;
784
785 return (true); // Got it!
786}
787
788extern wxDateTime gTimeSource;
789
790bool TCMgr::GetTideOrCurrent15(time_t t_d, int idx, float &tcvalue, float &dir,
791 bool &bnew_val) {
792 int ret;
793 IDX_entry *pIDX = m_Combined_IDX_array[idx]; // point to the index entry
794
795 if (!pIDX) {
796 dir = 0;
797 tcvalue = 0;
798 return false;
799 }
800
801 // Figure out this computer timezone minute offset
802 wxDateTime this_now = gTimeSource; // wxDateTime::Now();
803 if (this_now.IsValid() == false) this_now = wxDateTime::Now();
804 wxDateTime this_gmt = this_now.ToGMT();
805 wxTimeSpan diff = this_gmt.Subtract(this_now);
806 int diff_mins = diff.GetMinutes();
807
808 int station_offset = pIDX->IDX_time_zone;
809 if (this_now.IsDST()) station_offset += 60;
810 int corr_mins = station_offset - diff_mins;
811
812 wxDateTime today_00 = this_now;
813 today_00.ResetTime();
814 int t_today_00 = today_00.GetTicks();
815 int t_today_00_at_station = t_today_00 - (corr_mins * 60);
816
817 int t_at_station =
818 this_gmt.GetTicks() - (station_offset * 60) + (corr_mins * 60);
819
820 int t_mins = (t_at_station - t_today_00_at_station) / 60;
821 int t_15s = t_mins / 15;
822
823 if (pIDX->Valid15) // valid data available
824 {
825 int tref1 = t_today_00_at_station + t_15s * 15 * 60;
826 if (tref1 == pIDX->Valid15) {
827 tcvalue = pIDX->Value15;
828 dir = pIDX->Dir15;
829 bnew_val = false;
830 return pIDX->Ret15;
831 } else {
832 int tref = t_today_00_at_station + t_15s * 15 * 60;
833 ret = GetTideOrCurrent(tref, idx, tcvalue, dir);
834
835 pIDX->Valid15 = tref;
836 pIDX->Value15 = tcvalue;
837 pIDX->Dir15 = dir;
838 pIDX->Ret15 = !(ret == 0);
839 bnew_val = true;
840
841 return !(ret == 0);
842 }
843 }
844
845 else {
846 int tref = t_today_00_at_station + t_15s * 15 * 60;
847 ret = GetTideOrCurrent(tref, idx, tcvalue, dir);
848
849 pIDX->Valid15 = tref;
850 pIDX->Value15 = tcvalue;
851 pIDX->Dir15 = dir;
852 pIDX->Ret15 = !(ret == 0);
853 bnew_val = true;
854 }
855
856 return !(ret == 0);
857}
858
859bool TCMgr::GetTideFlowSens(time_t t, int sch_step, int idx, float &tcvalue_now,
860 float &tcvalue_prev, bool &w_t) {
861 // Return a sensible value of 0 by default
862 tcvalue_now = 0;
863 tcvalue_prev = 0;
864 w_t = false;
865
866 // Load up this location data
867 IDX_entry *pIDX = m_Combined_IDX_array[idx]; // point to the index entry
868
869 if (!pIDX) return false;
870
871 if (!pIDX->IDX_Useable) return false; // no error, but unuseable
872
873 if (pIDX->pDataSource) {
874 if (pIDX->pDataSource->LoadHarmonicData(pIDX) != TC_NO_ERROR) return false;
875 }
876
877 pIDX->max_amplitude = 0.0; // Force multiplier re-compute
878 int yott = yearoftimet(t);
879 happy_new_year(pIDX, yott); // Force new multipliers
880
881 // Finally, process the tide flow sens
882
883 tcvalue_now = time2asecondary(t, pIDX);
884 tcvalue_prev = time2asecondary(t + sch_step, pIDX);
885
886 w_t =
887 tcvalue_now > tcvalue_prev; // w_t = true --> flood , w_t = false --> ebb
888
889 return true;
890}
891
892void TCMgr::GetHightOrLowTide(time_t t, int sch_step_1, int sch_step_2,
893 float tide_val, bool w_t, int idx, float &tcvalue,
894 time_t &tctime) {
895 // Return a sensible value of 0,0 by default
896 tcvalue = 0;
897 tctime = t;
898
899 // Load up this location data
900 IDX_entry *pIDX = m_Combined_IDX_array[idx]; // point to the index entry
901
902 if (!pIDX) return;
903
904 if (!pIDX->IDX_Useable) return; // no error, but unuseable
905
906 if (pIDX->pDataSource) {
907 if (pIDX->pDataSource->LoadHarmonicData(pIDX) != TC_NO_ERROR) return;
908 }
909
910 // Is the cache data reasonably fresh?
911 if (abs(t - pIDX->recent_highlow_calc_time) < 60) {
912 if (w_t) {
913 tcvalue = pIDX->recent_high_level;
914 tctime = pIDX->recent_high_time;
915 } else {
916 tcvalue = pIDX->recent_low_level;
917 tctime = pIDX->recent_low_time;
918 }
919 return;
920 }
921
922 pIDX->max_amplitude = 0.0; // Force multiplier re-compute
923 int yott = yearoftimet(t);
924 happy_new_year(pIDX, yott);
925
926 // Finally, calculate the Hight and low tides
927 double newval = tide_val;
928 double oldval = (w_t) ? newval - 1 : newval + 1;
929 int j = 0;
930 int k = 0;
931 int ttt = 0;
932 while ((newval > oldval) == w_t) // searching each ten minute
933 {
934 j++;
935 oldval = newval;
936 ttt = t + (sch_step_1 * j);
937 newval = time2asecondary(ttt, pIDX);
938 }
939 oldval = (w_t) ? newval - 1 : newval + 1;
940 while ((newval > oldval) == w_t) // searching back each minute
941 {
942 oldval = newval;
943 k++;
944 ttt = t + (sch_step_1 * j) - (sch_step_2 * k);
945 newval = time2asecondary(ttt, pIDX);
946 }
947 tcvalue = newval;
948 tctime = ttt + sch_step_2;
949
950 // Cache the data
951 pIDX->recent_highlow_calc_time = t;
952 if (w_t) {
953 pIDX->recent_high_level = newval;
954 pIDX->recent_high_time = tctime;
955 } else {
956 pIDX->recent_low_level = newval;
957 pIDX->recent_low_time = tctime;
958 }
959}
960
961int TCMgr::GetStationTimeOffset(IDX_entry *pIDX) { return pIDX->IDX_time_zone; }
962
963double TCMgr::GetStationLat(IDX_entry *pIDX) { return pIDX->IDX_lat; }
964
965double TCMgr::GetStationLon(IDX_entry *pIDX) { return pIDX->IDX_lon; }
966
967int TCMgr::GetNextBigEvent(time_t *tm, int idx) {
968 float tcvalue[1];
969 float dir;
970 bool ret;
971 double p, q;
972 int flags = 0, slope = 0;
973 ret = GetTideOrCurrent(*tm, idx, tcvalue[0], dir);
974 p = tcvalue[0];
975 *tm += 60;
976 ret = GetTideOrCurrent(*tm, idx, tcvalue[0], dir);
977 q = tcvalue[0];
978 *tm += 60;
979 if (p < q) slope = 1;
980 while (1) {
981 if ((slope == 1 && q < p) || (slope == 0 && p < q)) {
982 /* Tide event */
983 flags |= (1 << slope);
984 }
985 if (flags) {
986 *tm -= 60;
987 if (flags < 4) *tm -= 60;
988 return flags;
989 }
990 p = q;
991 ret = GetTideOrCurrent(*tm, idx, tcvalue[0], dir);
992 if (!ret) return 0; // Harmonics file error, data not available
993 q = tcvalue[0];
994 *tm += 60;
995 }
996}
997
998std::wstring TCMgr::GetTidalEventStr(int station_id, wxDateTime ref_dt,
999 double lat, double lon, int dt_type) {
1000 IDX_entry *idx = (IDX_entry *)GetIDX_entry(station_id);
1001 time_t dtmtt = ref_dt.FromUTC().GetTicks();
1002 int event = GetNextBigEvent(&dtmtt, station_id);
1003 wxDateTime event_dt = wxDateTime(dtmtt).MakeUTC();
1004
1005 std::wstring event_str;
1006 if (event == 1) {
1007 event_str = _("LW").ToStdWstring();
1008 } else if (event == 2) {
1009 event_str = _("HW").ToStdWstring();
1010 } else {
1011 event_str = _("Unavailable").ToStdWstring();
1012 }
1013
1014 if (event > 0) {
1015 event_str.append(L": ");
1016 event_str.append(
1017 toUsrDateTime(event_dt, dt_type, lon).FormatISOCombined(' '));
1018 }
1019
1020 return event_str;
1021}
1022
1023std::map<double, const IDX_entry *> TCMgr::GetStationsForLL(double xlat,
1024 double xlon) const {
1025 std::map<double, const IDX_entry *> x;
1026 const IDX_entry *lpIDX;
1027
1028 for (int j = 1; j < Get_max_IDX() + 1; j++) {
1029 lpIDX = GetIDX_entry(j);
1030 char type = lpIDX->IDX_type;
1031 wxString locnx(lpIDX->IDX_station_name, wxConvUTF8);
1032
1033 if (type == 't' || type == 'T') {
1034 double brg, dist;
1035 DistanceBearingMercator(xlat, xlon, lpIDX->IDX_lat, lpIDX->IDX_lon, &brg,
1036 &dist);
1037 x.emplace(std::make_pair(dist, lpIDX));
1038 }
1039 }
1040
1041 return x;
1042}
1043
1044int TCMgr::GetStationIDXbyName(const wxString &prefix, double xlat,
1045 double xlon) const {
1046 const IDX_entry *lpIDX;
1047 int jx = 0;
1048 wxString locn;
1049 double distx = 100000.;
1050
1051 int jmax = Get_max_IDX();
1052
1053 for (int j = 1; j < Get_max_IDX() + 1; j++) {
1054 lpIDX = GetIDX_entry(j);
1055 char type = lpIDX->IDX_type; // Entry "TCtcIUu" identifier
1056 wxString locnx(lpIDX->IDX_station_name, wxConvUTF8);
1057
1058 if (((type == 't') || (type == 'T')) // only Tides
1059 && (locnx.StartsWith(prefix))) {
1060 double brg, dist;
1061 DistanceBearingMercator(xlat, xlon, lpIDX->IDX_lat, lpIDX->IDX_lon, &brg,
1062 &dist);
1063 if (dist < distx) {
1064 distx = dist;
1065 jx = j;
1066 }
1067 }
1068 } // end for loop
1069 //} // end if @~~ found in WP
1070 return (jx);
1071}
1072
1073int TCMgr::GetStationIDXbyNameType(const wxString &prefix, double xlat,
1074 double xlon, char type) const {
1075 const IDX_entry *lpIDX;
1076 int jx = 0;
1077 wxString locn;
1078 double distx = 100000.;
1079
1080 // if (prp->m_MarkName.Find("@~~") != wxNOT_FOUND) {
1081 // tide_form = prp->m_MarkName.Mid(prp->m_MarkName.Find("@~~")+3);
1082 int jmax = Get_max_IDX();
1083
1084 for (int j = 1; j < Get_max_IDX() + 1; j++) {
1085 lpIDX = GetIDX_entry(j);
1086 char typep = lpIDX->IDX_type; // Entry "TCtcIUu" identifier
1087 wxString locnx(lpIDX->IDX_station_name, wxConvUTF8);
1088
1089 if ((type == typep) && (locnx.StartsWith(prefix))) {
1090 double brg, dist;
1091 DistanceBearingMercator(xlat, xlon, lpIDX->IDX_lat, lpIDX->IDX_lon, &brg,
1092 &dist);
1093 if (dist < distx) {
1094 distx = dist;
1095 jx = j;
1096 }
1097 }
1098 } // end for loop
1099 return (jx);
1100}
1101
1102/* $Id: tide_db_default.h 1092 2006-11-16 03:02:42Z flaterco $ */
1103
1104// #include "tcd.h"
1105
1106/*****************************************************************************
1107 *
1108 * DISTRIBUTION STATEMENT
1109 *
1110 * This source file is unclassified, distribution unlimited, public
1111 * domain. It is distributed in the hope that it will be useful, but
1112 * WITHOUT ANY WARRANTY; without even the implied warranty of
1113 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
1114 *
1115 ******************************************************************************/
1116
1117#define DEFAULT_HEADER_SIZE 4096
1118#define DEFAULT_NUMBER_OF_RECORDS 0
1119#define DEFAULT_LEVEL_UNIT_TYPES 5
1120#define DEFAULT_DIR_UNIT_TYPES 3
1121#define DEFAULT_RESTRICTION_TYPES 2
1122#define DEFAULT_RESTRICTION_BITS 4
1123#define DEFAULT_TZFILES 406
1124#define DEFAULT_TZFILE_BITS 10
1125#define DEFAULT_COUNTRIES 240
1126#define DEFAULT_COUNTRY_BITS 9
1127#define DEFAULT_DATUM_TYPES 61
1128#define DEFAULT_DATUM_BITS 7
1129#define DEFAULT_LEGALESES 1
1130#define DEFAULT_LEGALESE_BITS 4
1131#define DEFAULT_SPEED_SCALE 10000000
1132#define DEFAULT_EQUILIBRIUM_SCALE 100
1133#define DEFAULT_NODE_SCALE 10000
1134#define DEFAULT_AMPLITUDE_BITS 19
1135#define DEFAULT_AMPLITUDE_SCALE 10000
1136#define DEFAULT_EPOCH_BITS 16
1137#define DEFAULT_EPOCH_SCALE 100
1138#define DEFAULT_RECORD_TYPE_BITS 4
1139#define DEFAULT_LATITUDE_BITS 25
1140#define DEFAULT_LATITUDE_SCALE 100000
1141#define DEFAULT_LONGITUDE_BITS 26
1142#define DEFAULT_LONGITUDE_SCALE 100000
1143#define DEFAULT_RECORD_SIZE_BITS 16
1144#define DEFAULT_STATION_BITS 18
1145#define DEFAULT_DATUM_OFFSET_BITS 28
1146#define DEFAULT_DATUM_OFFSET_SCALE 10000
1147#define DEFAULT_DATE_BITS 27
1148#define DEFAULT_MONTHS_ON_STATION_BITS 10
1149#define DEFAULT_CONFIDENCE_VALUE_BITS 4
1150#define DEFAULT_NUMBER_OF_CONSTITUENTS_BITS 8
1151#define DEFAULT_TIME_BITS 13
1152#define DEFAULT_LEVEL_ADD_BITS 17
1153#define DEFAULT_LEVEL_ADD_SCALE 1000
1154#define DEFAULT_LEVEL_MULTIPLY_BITS 16
1155#define DEFAULT_LEVEL_MULTIPLY_SCALE 1000
1156#define DEFAULT_DIRECTION_BITS 9
1157#define DEFAULT_CONSTITUENT_SIZE 10
1158#define DEFAULT_LEVEL_UNIT_SIZE 15
1159#define DEFAULT_DIR_UNIT_SIZE 15
1160#define DEFAULT_RESTRICTION_SIZE 30
1161#define DEFAULT_DATUM_SIZE 70
1162#define DEFAULT_LEGALESE_SIZE 70
1163#define DEFAULT_TZFILE_SIZE 30
1164#define DEFAULT_COUNTRY_SIZE 50
1165
1166/* Stuff for inferring constituents (NAVO short duration tide stations). */
1167
1168#define INFERRED_SEMI_DIURNAL_COUNT 10
1169#define INFERRED_DIURNAL_COUNT 10
1170
1171#ifdef __MSVC__
1172#pragma warning(disable : 4305) // conversion loss, double to float
1173#endif
1174
1175const NV_CHAR *inferred_semi_diurnal[INFERRED_SEMI_DIURNAL_COUNT] = {
1176 "N2", "NU2", "MU2", "2N2", "LDA2", "T2", "R2", "L2", "K2", "KJ2"};
1177const NV_CHAR *inferred_diurnal[INFERRED_DIURNAL_COUNT] = {
1178 "OO1", "M1", "J1", "RHO1", "Q1", "2Q1", "P1", "PI1", "PHI1", "PSI1"};
1179NV_FLOAT32 semi_diurnal_coeff[INFERRED_SEMI_DIURNAL_COUNT] = {
1180 .1759, .0341, .0219, .0235, .0066, .0248, .0035, .0251, .1151, .0064};
1181NV_FLOAT32 diurnal_coeff[INFERRED_DIURNAL_COUNT] = {
1182 .0163, .0209, .0297, .0142, .0730, .0097, .1755, .0103, .0076, .0042};
1183
1184/* These represent M2 and O1. */
1185
1186NV_FLOAT32 coeff[2] = {.9085, .3771};
1187
1188/* The following lookup tables are only used for initialization
1189 * purposes and in the pull-down menus in TideEditor. It should be
1190 * possible to change them without breaking existing TCD files. TCD
1191 * files embed their own lookup tables.
1192 */
1193
1194/* Level unit names */
1195
1196NV_CHAR level_unit[DEFAULT_LEVEL_UNIT_TYPES][DEFAULT_LEVEL_UNIT_SIZE] = {
1197 "Unknown", "feet", "meters", "knots", "knots^2"};
1198
1199/* Direction unit names */
1200
1201NV_CHAR dir_unit[DEFAULT_DIR_UNIT_TYPES][DEFAULT_DIR_UNIT_SIZE] = {
1202 "Unknown", "degrees true", "degrees"};
1203
1204/* Restriction types */
1205
1206NV_CHAR restriction[DEFAULT_RESTRICTION_TYPES][DEFAULT_RESTRICTION_SIZE] = {
1207 "Public Domain", "DoD/DoD Contractors Only"};
1208
1209/* Legaleses */
1210
1211NV_CHAR legalese[DEFAULT_LEGALESES][DEFAULT_LEGALESE_SIZE] = {"NULL"};
1212
1213/* # Datum names */
1214
1215NV_CHAR datum[DEFAULT_DATUM_TYPES][DEFAULT_DATUM_SIZE] = {
1216 "Unknown",
1217 "Mean Sea Level",
1218 "Mean Low Water",
1219 "Mean Lower Low Water",
1220 "Mean High Water",
1221 "Mean Higher High Water",
1222 "Mean Lower High Water",
1223 "Mean Higher Low Water",
1224 "Mean Low Water Springs",
1225 "Mean Lower Low Water Springs",
1226 "Mean Low Water Neaps",
1227 "Mean High Water Neaps",
1228 "Mean High Water Springs",
1229 "Mean Higher High Water Springs",
1230 "Indian Spring Low Water",
1231 "Equatorial Spring Low Water",
1232 "Lowest Normal Low Water",
1233 "Lowest Low Water",
1234 "Lowest Possible Low Water",
1235 "Lowest Astronomical Tide",
1236 "International Great Lakes Datum(1955)",
1237 "Lower Low Water, Large Tide",
1238 "Lowest Normal Tide",
1239 "Higher High Water, Large Tide",
1240 "Mean Water Level",
1241 "Higher High Water, Mean Tide",
1242 "Lower Low Water, Mean Tide",
1243 "Mean Tide Level",
1244 "World Geodetic System (1984)",
1245 "National Geodetic Vertical Datum",
1246 "Gulf Coast Low Water Datum",
1247 "Approximate Level of Mean Sea Level",
1248 "Approximate Level of Mean Low Water",
1249 "Approximate Level of Mean Lower Low Water",
1250 "Approximate Level of Mean High Water",
1251 "Approximate Level of Mean Higher High Water",
1252 "Approximate Level of Mean Lower High Water",
1253 "Approximate Level of Mean Higher Low Water",
1254 "Approximate Level of Mean Low Water Springs",
1255 "Approximate Level of Mean Lower Low Water Springs",
1256 "Approximate Level of Mean Low Water Neaps",
1257 "Approximate Level of Mean High Water Neaps",
1258 "Approximate Level of Mean High Water Springs",
1259 "Approximate Level of Mean Higher High Water Springs",
1260 "Approximate Level of Indian Spring Low Water",
1261 "Approximate Level of Equatorial Spring Low Water",
1262 "Approximate Level of Lowest Normal Low Water",
1263 "Approximate Level of Lowest Low Water",
1264 "Approximate Level of Lowest Possible Low Water",
1265 "Approximate Level of Lowest Astronomical Tide",
1266 "Approximate Level of International Great Lakes Datum (1955)",
1267 "Approximate Level of Lower Low Water, Large Tide",
1268 "Approximate Level of Lowest Normal Tide",
1269 "Approximate Level of Higher High Water, Large Tide",
1270 "Approximate Level of Mean Water Level",
1271 "Approximate Level of Higher High Water, Mean Tide",
1272 "Approximate Level of Lower Low Water, Mean Tide",
1273 "Approximate Level of Mean Tide Level",
1274 "Approximate Level of World Geodetic System (1984)",
1275 "Approximate Level of National Geodetic Vertical Datum",
1276 "Approximate Level of Gulf Coast Low Water Datum"};
1277
1278/* # Country names from ISO 3166-1:1999 2-character country code list */
1279
1280NV_CHAR country[DEFAULT_COUNTRIES][DEFAULT_COUNTRY_SIZE] = {
1281 "Unknown",
1282 "Afghanistan",
1283 "Albania",
1284 "Algeria",
1285 "Andorra",
1286 "Angola",
1287 "Anguilla",
1288 "Antarctica",
1289 "Antigua & Barbuda",
1290 "Argentina",
1291 "Armenia",
1292 "Aruba",
1293 "Australia",
1294 "Austria",
1295 "Azerbaijan",
1296 "Bahamas",
1297 "Bahrain",
1298 "Bangladesh",
1299 "Barbados",
1300 "Belarus",
1301 "Belgium",
1302 "Belize",
1303 "Benin",
1304 "Bermuda",
1305 "Bhutan",
1306 "Bolivia",
1307 "Bosnia & Herzegovina",
1308 "Botswana",
1309 "Bouvet Island",
1310 "Brazil",
1311 "Britain (UK)",
1312 "British Indian Ocean Territory",
1313 "Brunei",
1314 "Bulgaria",
1315 "Burkina Faso",
1316 "Burundi",
1317 "Cambodia",
1318 "Cameroon",
1319 "Canada",
1320 "Cape Verde",
1321 "Cayman Islands",
1322 "Central African Rep.",
1323 "Chad",
1324 "Chile",
1325 "China",
1326 "Christmas Island",
1327 "Cocos (Keeling) Islands",
1328 "Colombia",
1329 "Comoros",
1330 "Congo (Dem. Rep.)",
1331 "Congo (Rep.)",
1332 "Cook Islands",
1333 "Costa Rica",
1334 "Cote d'Ivoire",
1335 "Croatia",
1336 "Cuba",
1337 "Cyprus",
1338 "Czech Republic",
1339 "Denmark",
1340 "Djibouti",
1341 "Dominica",
1342 "Dominican Republic",
1343 "East Timor",
1344 "Ecuador",
1345 "Egypt",
1346 "El Salvador",
1347 "Equatorial Guinea",
1348 "Eritrea",
1349 "Estonia",
1350 "Ethiopia",
1351 "Faeroe Islands",
1352 "Falkland Islands",
1353 "Fiji",
1354 "Finland",
1355 "France",
1356 "French Guiana",
1357 "French Polynesia",
1358 "French Southern & Antarctic Lands",
1359 "Gabon",
1360 "Gambia",
1361 "Georgia",
1362 "Germany",
1363 "Ghana",
1364 "Gibraltar",
1365 "Greece",
1366 "Greenland",
1367 "Grenada",
1368 "Guadeloupe",
1369 "Guam",
1370 "Guatemala",
1371 "Guinea",
1372 "Guinea-Bissau",
1373 "Guyana",
1374 "Haiti",
1375 "Heard Island & McDonald Islands",
1376 "Honduras",
1377 "Hong Kong",
1378 "Hungary",
1379 "Iceland",
1380 "India",
1381 "Indonesia",
1382 "Iran",
1383 "Iraq",
1384 "Ireland",
1385 "Israel",
1386 "Italy",
1387 "Jamaica",
1388 "Japan",
1389 "Jordan",
1390 "Kazakhstan",
1391 "Kenya",
1392 "Kiribati",
1393 "Korea (North)",
1394 "Korea (South)",
1395 "Kuwait",
1396 "Kyrgyzstan",
1397 "Laos",
1398 "Latvia",
1399 "Lebanon",
1400 "Lesotho",
1401 "Liberia",
1402 "Libya",
1403 "Liechtenstein",
1404 "Lithuania",
1405 "Luxembourg",
1406 "Macau",
1407 "Macedonia",
1408 "Madagascar",
1409 "Malawi",
1410 "Malaysia",
1411 "Maldives",
1412 "Mali",
1413 "Malta",
1414 "Marshall Islands",
1415 "Martinique",
1416 "Mauritania",
1417 "Mauritius",
1418 "Mayotte",
1419 "Mexico",
1420 "Micronesia",
1421 "Moldova",
1422 "Monaco",
1423 "Mongolia",
1424 "Montserrat",
1425 "Morocco",
1426 "Mozambique",
1427 "Myanmar (Burma)",
1428 "Namibia",
1429 "Nauru",
1430 "Nepal",
1431 "Netherlands",
1432 "Netherlands Antilles",
1433 "New Caledonia",
1434 "New Zealand",
1435 "Nicaragua",
1436 "Niger",
1437 "Nigeria",
1438 "Niue",
1439 "Norfolk Island",
1440 "Northern Mariana Islands",
1441 "Norway",
1442 "Oman",
1443 "Pakistan",
1444 "Palau",
1445 "Palestine",
1446 "Panama",
1447 "Papua New Guinea",
1448 "Paraguay",
1449 "Peru",
1450 "Philippines",
1451 "Pitcairn",
1452 "Poland",
1453 "Portugal",
1454 "Puerto Rico",
1455 "Qatar",
1456 "Reunion",
1457 "Romania",
1458 "Russia",
1459 "Rwanda",
1460 "Samoa (American)",
1461 "Samoa (Western)",
1462 "San Marino",
1463 "Sao Tome & Principe",
1464 "Saudi Arabia",
1465 "Senegal",
1466 "Seychelles",
1467 "Sierra Leone",
1468 "Singapore",
1469 "Slovakia",
1470 "Slovenia",
1471 "Solomon Islands",
1472 "Somalia",
1473 "South Africa",
1474 "South Georgia & the South Sandwich Islands",
1475 "Spain",
1476 "Sri Lanka",
1477 "St Helena",
1478 "St Kitts & Nevis",
1479 "St Lucia",
1480 "St Pierre & Miquelon",
1481 "St Vincent",
1482 "Sudan",
1483 "Suriname",
1484 "Svalbard & Jan Mayen",
1485 "Swaziland",
1486 "Sweden",
1487 "Switzerland",
1488 "Syria",
1489 "Taiwan",
1490 "Tajikistan",
1491 "Tanzania",
1492 "Thailand",
1493 "Togo",
1494 "Tokelau",
1495 "Tonga",
1496 "Trinidad & Tobago",
1497 "Tunisia",
1498 "Turkey",
1499 "Turkmenistan",
1500 "Turks & Caicos Is",
1501 "Tuvalu",
1502 "Uganda",
1503 "Ukraine",
1504 "United Arab Emirates",
1505 "United States",
1506 "Uruguay",
1507 "US minor outlying islands",
1508 "Uzbekistan",
1509 "Vanuatu",
1510 "Vatican City",
1511 "Venezuela",
1512 "Vietnam",
1513 "Virgin Islands (UK)",
1514 "Virgin Islands (US)",
1515 "Wallis & Futuna",
1516 "Western Sahara",
1517 "Yemen",
1518 "Yugoslavia",
1519 "Zambia",
1520 "Zimbabwe"};
1521
1522/* # Time zones extracted from tzdata2002? . */
1523
1524NV_CHAR tzfile[DEFAULT_TZFILES][DEFAULT_TZFILE_SIZE] = {
1525 "Unknown",
1526 ":Africa/Abidjan",
1527 ":Africa/Accra",
1528 ":Africa/Addis_Ababa",
1529 ":Africa/Algiers",
1530 ":Africa/Asmera",
1531 ":Africa/Bamako",
1532 ":Africa/Bangui",
1533 ":Africa/Banjul",
1534 ":Africa/Bissau",
1535 ":Africa/Blantyre",
1536 ":Africa/Brazzaville",
1537 ":Africa/Bujumbura",
1538 ":Africa/Cairo",
1539 ":Africa/Casablanca",
1540 ":Africa/Ceuta",
1541 ":Africa/Conakry",
1542 ":Africa/Dakar",
1543 ":Africa/Dar_es_Salaam",
1544 ":Africa/Djibouti",
1545 ":Africa/Douala",
1546 ":Africa/El_Aaiun",
1547 ":Africa/Freetown",
1548 ":Africa/Gaborone",
1549 ":Africa/Harare",
1550 ":Africa/Johannesburg",
1551 ":Africa/Kampala",
1552 ":Africa/Khartoum",
1553 ":Africa/Kigali",
1554 ":Africa/Kinshasa",
1555 ":Africa/Lagos",
1556 ":Africa/Libreville",
1557 ":Africa/Lome",
1558 ":Africa/Luanda",
1559 ":Africa/Lubumbashi",
1560 ":Africa/Lusaka",
1561 ":Africa/Malabo",
1562 ":Africa/Maputo",
1563 ":Africa/Maseru",
1564 ":Africa/Mbabane",
1565 ":Africa/Mogadishu",
1566 ":Africa/Monrovia",
1567 ":Africa/Nairobi",
1568 ":Africa/Ndjamena",
1569 ":Africa/Niamey",
1570 ":Africa/Nouakchott",
1571 ":Africa/Ouagadougou",
1572 ":Africa/Porto-Novo",
1573 ":Africa/Sao_Tome",
1574 ":Africa/Timbuktu",
1575 ":Africa/Tripoli",
1576 ":Africa/Tunis",
1577 ":Africa/Windhoek",
1578 ":America/Adak",
1579 ":America/Anchorage",
1580 ":America/Anguilla",
1581 ":America/Antigua",
1582 ":America/Araguaina",
1583 ":America/Aruba",
1584 ":America/Asuncion",
1585 ":America/Atka",
1586 ":America/Barbados",
1587 ":America/Belem",
1588 ":America/Belize",
1589 ":America/Boa_Vista",
1590 ":America/Bogota",
1591 ":America/Boise",
1592 ":America/Buenos_Aires",
1593 ":America/Cambridge_Bay",
1594 ":America/Cancun",
1595 ":America/Caracas",
1596 ":America/Catamarca",
1597 ":America/Cayenne",
1598 ":America/Cayman",
1599 ":America/Chicago",
1600 ":America/Chihuahua",
1601 ":America/Cordoba",
1602 ":America/Costa_Rica",
1603 ":America/Cuiaba",
1604 ":America/Curacao",
1605 ":America/Danmarkshavn",
1606 ":America/Dawson",
1607 ":America/Dawson_Creek",
1608 ":America/Denver",
1609 ":America/Detroit",
1610 ":America/Dominica",
1611 ":America/Edmonton",
1612 ":America/Eirunepe",
1613 ":America/El_Salvador",
1614 ":America/Ensenada",
1615 ":America/Fortaleza",
1616 ":America/Glace_Bay",
1617 ":America/Godthab",
1618 ":America/Goose_Bay",
1619 ":America/Grand_Turk",
1620 ":America/Grenada",
1621 ":America/Guadeloupe",
1622 ":America/Guatemala",
1623 ":America/Guayaquil",
1624 ":America/Guyana",
1625 ":America/Halifax",
1626 ":America/Havana",
1627 ":America/Hermosillo",
1628 ":America/Indiana/Knox",
1629 ":America/Indiana/Marengo",
1630 ":America/Indianapolis",
1631 ":America/Indiana/Vevay",
1632 ":America/Inuvik",
1633 ":America/Iqaluit",
1634 ":America/Jamaica",
1635 ":America/Jujuy",
1636 ":America/Juneau",
1637 ":America/Kentucky/Monticello",
1638 ":America/La_Paz",
1639 ":America/Lima",
1640 ":America/Los_Angeles",
1641 ":America/Louisville",
1642 ":America/Maceio",
1643 ":America/Managua",
1644 ":America/Manaus",
1645 ":America/Martinique",
1646 ":America/Mazatlan",
1647 ":America/Mendoza",
1648 ":America/Menominee",
1649 ":America/Merida",
1650 ":America/Mexico_City",
1651 ":America/Miquelon",
1652 ":America/Monterrey",
1653 ":America/Montevideo",
1654 ":America/Montreal",
1655 ":America/Montserrat",
1656 ":America/Nassau",
1657 ":America/New_York",
1658 ":America/Nipigon",
1659 ":America/Nome",
1660 ":America/Noronha",
1661 ":America/North_Dakota/Center",
1662 ":America/Panama",
1663 ":America/Pangnirtung",
1664 ":America/Paramaribo",
1665 ":America/Phoenix",
1666 ":America/Port-au-Prince",
1667 ":America/Port_of_Spain",
1668 ":America/Porto_Velho",
1669 ":America/Puerto_Rico",
1670 ":America/Rainy_River",
1671 ":America/Rankin_Inlet",
1672 ":America/Recife",
1673 ":America/Regina",
1674 ":America/Rio_Branco",
1675 ":America/Santiago",
1676 ":America/Santo_Domingo",
1677 ":America/Sao_Paulo",
1678 ":America/Scoresbysund",
1679 ":America/Shiprock",
1680 ":America/St_Johns",
1681 ":America/St_Kitts",
1682 ":America/St_Lucia",
1683 ":America/St_Thomas",
1684 ":America/St_Vincent",
1685 ":America/Swift_Current",
1686 ":America/Tegucigalpa",
1687 ":America/Thule",
1688 ":America/Thunder_Bay",
1689 ":America/Tijuana",
1690 ":America/Tortola",
1691 ":America/Vancouver",
1692 ":America/Whitehorse",
1693 ":America/Winnipeg",
1694 ":America/Yakutat",
1695 ":America/Yellowknife",
1696 ":Antarctica/Casey",
1697 ":Antarctica/Davis",
1698 ":Antarctica/DumontDUrville",
1699 ":Antarctica/Mawson",
1700 ":Antarctica/McMurdo",
1701 ":Antarctica/Palmer",
1702 ":Antarctica/South_Pole",
1703 ":Antarctica/Syowa",
1704 ":Antarctica/Vostok",
1705 ":Arctic/Longyearbyen",
1706 ":Asia/Aden",
1707 ":Asia/Almaty",
1708 ":Asia/Amman",
1709 ":Asia/Anadyr",
1710 ":Asia/Aqtau",
1711 ":Asia/Aqtobe",
1712 ":Asia/Ashgabat",
1713 ":Asia/Baghdad",
1714 ":Asia/Bahrain",
1715 ":Asia/Baku",
1716 ":Asia/Bangkok",
1717 ":Asia/Beirut",
1718 ":Asia/Bishkek",
1719 ":Asia/Brunei",
1720 ":Asia/Calcutta",
1721 ":Asia/Choibalsan",
1722 ":Asia/Chongqing",
1723 ":Asia/Colombo",
1724 ":Asia/Damascus",
1725 ":Asia/Dhaka",
1726 ":Asia/Dili",
1727 ":Asia/Dubai",
1728 ":Asia/Dushanbe",
1729 ":Asia/Gaza",
1730 ":Asia/Harbin",
1731 ":Asia/Hong_Kong",
1732 ":Asia/Hovd",
1733 ":Asia/Irkutsk",
1734 ":Asia/Jakarta",
1735 ":Asia/Jayapura",
1736 ":Asia/Jerusalem",
1737 ":Asia/Kabul",
1738 ":Asia/Kamchatka",
1739 ":Asia/Karachi",
1740 ":Asia/Kashgar",
1741 ":Asia/Katmandu",
1742 ":Asia/Krasnoyarsk",
1743 ":Asia/Kuala_Lumpur",
1744 ":Asia/Kuching",
1745 ":Asia/Kuwait",
1746 ":Asia/Macau",
1747 ":Asia/Magadan",
1748 ":Asia/Makassar",
1749 ":Asia/Manila",
1750 ":Asia/Muscat",
1751 ":Asia/Nicosia",
1752 ":Asia/Novosibirsk",
1753 ":Asia/Omsk",
1754 ":Asia/Oral",
1755 ":Asia/Phnom_Penh",
1756 ":Asia/Pontianak",
1757 ":Asia/Pyongyang",
1758 ":Asia/Qatar",
1759 ":Asia/Qyzylorda",
1760 ":Asia/Rangoon",
1761 ":Asia/Riyadh",
1762 ":Asia/Saigon",
1763 ":Asia/Sakhalin",
1764 ":Asia/Samarkand",
1765 ":Asia/Seoul",
1766 ":Asia/Shanghai",
1767 ":Asia/Singapore",
1768 ":Asia/Taipei",
1769 ":Asia/Tashkent",
1770 ":Asia/Tbilisi",
1771 ":Asia/Tehran",
1772 ":Asia/Thimphu",
1773 ":Asia/Tokyo",
1774 ":Asia/Ulaanbaatar",
1775 ":Asia/Urumqi",
1776 ":Asia/Vientiane",
1777 ":Asia/Vladivostok",
1778 ":Asia/Yakutsk",
1779 ":Asia/Yekaterinburg",
1780 ":Asia/Yerevan",
1781 ":Atlantic/Azores",
1782 ":Atlantic/Bermuda",
1783 ":Atlantic/Canary",
1784 ":Atlantic/Cape_Verde",
1785 ":Atlantic/Faeroe",
1786 ":Atlantic/Jan_Mayen",
1787 ":Atlantic/Madeira",
1788 ":Atlantic/Reykjavik",
1789 ":Atlantic/South_Georgia",
1790 ":Atlantic/Stanley",
1791 ":Atlantic/St_Helena",
1792 ":Australia/Adelaide",
1793 ":Australia/Brisbane",
1794 ":Australia/Broken_Hill",
1795 ":Australia/Darwin",
1796 ":Australia/Hobart",
1797 ":Australia/Lindeman",
1798 ":Australia/Lord_Howe",
1799 ":Australia/Melbourne",
1800 ":Australia/Perth",
1801 ":Australia/Sydney",
1802 ":Etc/GMT",
1803 ":Etc/GMT-1",
1804 ":Etc/GMT+1",
1805 ":Etc/GMT-10",
1806 ":Etc/GMT+10",
1807 ":Etc/GMT-11",
1808 ":Etc/GMT+11",
1809 ":Etc/GMT-12",
1810 ":Etc/GMT+12",
1811 ":Etc/GMT-13",
1812 ":Etc/GMT-14",
1813 ":Etc/GMT-2",
1814 ":Etc/GMT+2",
1815 ":Etc/GMT-3",
1816 ":Etc/GMT+3",
1817 ":Etc/GMT-4",
1818 ":Etc/GMT+4",
1819 ":Etc/GMT-5",
1820 ":Etc/GMT+5",
1821 ":Etc/GMT-6",
1822 ":Etc/GMT+6",
1823 ":Etc/GMT-7",
1824 ":Etc/GMT+7",
1825 ":Etc/GMT-8",
1826 ":Etc/GMT+8",
1827 ":Etc/GMT-9",
1828 ":Etc/GMT+9",
1829 ":Etc/UCT",
1830 ":Etc/UTC",
1831 ":Europe/Amsterdam",
1832 ":Europe/Andorra",
1833 ":Europe/Athens",
1834 ":Europe/Belfast",
1835 ":Europe/Belgrade",
1836 ":Europe/Berlin",
1837 ":Europe/Bratislava",
1838 ":Europe/Brussels",
1839 ":Europe/Bucharest",
1840 ":Europe/Budapest",
1841 ":Europe/Chisinau",
1842 ":Europe/Copenhagen",
1843 ":Europe/Dublin",
1844 ":Europe/Gibraltar",
1845 ":Europe/Helsinki",
1846 ":Europe/Istanbul",
1847 ":Europe/Kaliningrad",
1848 ":Europe/Kiev",
1849 ":Europe/Lisbon",
1850 ":Europe/Ljubljana",
1851 ":Europe/London",
1852 ":Europe/Luxembourg",
1853 ":Europe/Madrid",
1854 ":Europe/Malta",
1855 ":Europe/Minsk",
1856 ":Europe/Monaco",
1857 ":Europe/Moscow",
1858 ":Europe/Oslo",
1859 ":Europe/Paris",
1860 ":Europe/Prague",
1861 ":Europe/Riga",
1862 ":Europe/Rome",
1863 ":Europe/Samara",
1864 ":Europe/San_Marino",
1865 ":Europe/Sarajevo",
1866 ":Europe/Simferopol",
1867 ":Europe/Skopje",
1868 ":Europe/Sofia",
1869 ":Europe/Stockholm",
1870 ":Europe/Tallinn",
1871 ":Europe/Tirane",
1872 ":Europe/Uzhgorod",
1873 ":Europe/Vaduz",
1874 ":Europe/Vatican",
1875 ":Europe/Vienna",
1876 ":Europe/Vilnius",
1877 ":Europe/Warsaw",
1878 ":Europe/Zagreb",
1879 ":Europe/Zaporozhye",
1880 ":Europe/Zurich",
1881 ":Indian/Antananarivo",
1882 ":Indian/Chagos",
1883 ":Indian/Christmas",
1884 ":Indian/Cocos",
1885 ":Indian/Comoro",
1886 ":Indian/Kerguelen",
1887 ":Indian/Mahe",
1888 ":Indian/Maldives",
1889 ":Indian/Mauritius",
1890 ":Indian/Mayotte",
1891 ":Indian/Reunion",
1892 ":Pacific/Apia",
1893 ":Pacific/Auckland",
1894 ":Pacific/Chatham",
1895 ":Pacific/Easter",
1896 ":Pacific/Efate",
1897 ":Pacific/Enderbury",
1898 ":Pacific/Fakaofo",
1899 ":Pacific/Fiji",
1900 ":Pacific/Funafuti",
1901 ":Pacific/Galapagos",
1902 ":Pacific/Gambier",
1903 ":Pacific/Guadalcanal",
1904 ":Pacific/Guam",
1905 ":Pacific/Honolulu",
1906 ":Pacific/Johnston",
1907 ":Pacific/Kiritimati",
1908 ":Pacific/Kosrae",
1909 ":Pacific/Kwajalein",
1910 ":Pacific/Majuro",
1911 ":Pacific/Marquesas",
1912 ":Pacific/Midway",
1913 ":Pacific/Nauru",
1914 ":Pacific/Niue",
1915 ":Pacific/Norfolk",
1916 ":Pacific/Noumea",
1917 ":Pacific/Pago_Pago",
1918 ":Pacific/Palau",
1919 ":Pacific/Pitcairn",
1920 ":Pacific/Ponape",
1921 ":Pacific/Port_Moresby",
1922 ":Pacific/Rarotonga",
1923 ":Pacific/Saipan",
1924 ":Pacific/Tahiti",
1925 ":Pacific/Tarawa",
1926 ":Pacific/Tongatapu",
1927 ":Pacific/Truk",
1928 ":Pacific/Wake",
1929 ":Pacific/Wallis",
1930 ":Pacific/Yap"};
1931
1932/* $Id: tide_db.c 3744 2010-08-17 22:34:46Z flaterco $ */
1933
1934// #include "tcd.h"
1935// #include "tide_db_header.h"
1936// #include "tide_db_default.h"
1937
1938/* This should be done with stdbool.h, but VC doesn't have it. */
1939/* Using crappy old int, must be careful not to 'require' a 64-bit value. */
1940#ifndef require
1941#define require(expr) \
1942 { \
1943 int require_expr; \
1944 require_expr = (int)(expr); \
1945 assert(require_expr); \
1946 }
1947#endif
1948
1949#include <stdio.h>
1950#include <stdlib.h>
1951#include <string.h>
1952#include <errno.h>
1953#include <time.h>
1954#include <math.h>
1955#include <ctype.h>
1956#include <assert.h>
1957
1958#ifdef HAVE_UNISTD_H
1959#include <unistd.h>
1960#endif
1961
1962#ifdef HAVE_IO_H
1963#include <io.h>
1964#endif
1965
1966/****************************************************************************
1967
1968 DISTRIBUTION STATEMENT
1969
1970 This source file is unclassified, distribution unlimited, public
1971 domain. It is distributed in the hope that it will be useful, but
1972 WITHOUT ANY WARRANTY; without even the implied warranty of
1973 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
1974
1975*****************************************************************************/
1976
1977/* Some of the following commentary is out of date. See the new
1978 documentation in libtcd.html. */
1979
1980/****************************************************************************
1981
1982 Tide Constituent Database API
1983
1984
1985 Author : Jan C. Depner (depnerj@navo.navy.mil)
1986
1987 Date : 08/01/02
1988 (First day of Micro$oft's "Licensing 6" policy - P.T. Barnum was
1989 right!!!)
1990
1991 Purpose : To replace the ASCII/XML formatted harmonic constituent data
1992 files, used in Dave Flater's (http://www.flaterco.com/xtide/)
1993 exceptionally fine open-source XTide program, with a fast,
1994 efficient binary format. In addition, we wanted to replace the
1995 Naval Oceanographic Office's (http://www.navo.navy.mil)
1996 antiquated ASCII format harmonic constituent data file due to
1997 problems with configuration management of the file. The
1998 resulting database will become a Navy OAML (Oceanographic and
1999 Atmospheric Master Library) standard harmonic tide constituent
2000 database.
2001
2002 Design : The following describes the database file and some of the
2003 rationale behind the design.
2004
2005 First question - Why didn't I use PostgreSQL or MySQL? Mostly
2006 portability. What? PostgreSQL runs on everything! Yes, but it doesn't
2007 come installed on everything. This would have meant that the poor,
2008 benighted Micro$oft borgs would have had to actually load a software
2009 package. In addition, the present harmonics/offset files only contain
2010 a total of 6,409 stations. It hardly seemed worth the effort (or overhead)
2011 of a fullblown RDBMS to handle this. Second question - Why binary and not
2012 ASCII or XML? This actually gets into philosophy. At NAVO we have used an
2013 ASCII harmonic constituent file for years (we were founded in 1830 and I
2014 think that that's when they designed the file). We have about fifty
2015 million copies floating around and each one is slightly different. Why?
2016 Because they're ASCII and everyone thinks they know what they're doing so
2017 they tend to modify the file. Same problem with XML, it's still ASCII.
2018 We wanted a file that people weren't going to mess with and that we could
2019 version control. We also wanted a file that was small and fast. This is
2020 very difficult to do with ASCII. The big slowdown with the old format
2021 was I/O and parsing. Third question - will it run on any OS? Hopefully,
2022 yes. After twenty-five years of working with low bidder systems I've
2023 worked on almost every OS known to man. Once you've been bitten by big
2024 endian vs little endian or IEEE floating point format vs VAX floating
2025 point format or byte addressable memory vs word addressable memory or 32
2026 bit word vs 36 bit word vs 48 bit word vs 64 bit word sizes you get the
2027 message. All of the data in the file is stored either as ASCII text or
2028 scaled integers (32 bits or smaller), bit-packed and stuffed into an
2029 unsigned character buffer for I/O. No endian issues, no floating point
2030 issues, no word size issues, no memory mapping issues. I will be testing
2031 this on x86 Linux, HP-UX, and Micro$oft Windoze. By the time you read
2032 this it will be portable to those systems at least.
2033
2034 Now, on to the file layout. As much as I dislike ASCII it is occasionally
2035 handy to be able to see some information about a file without having to
2036 resort to a special purpose program. With that in mind I made the first
2037 part of the header of the file ASCII. The following is an example of the
2038 ASCII portion of the header:
2039
2040 [VERSION] = PFM Software - tide_db V1.00 - 08/01/02
2041 [LAST MODIFIED] = Thu Aug 1 02:46:29 2002
2042 [HEADER SIZE] = 4096
2043 [NUMBER OF RECORDS] = 10652
2044 [START YEAR] = 1970
2045 [NUMBER OF YEARS] = 68
2046 [SPEED BITS] = 31
2047 [SPEED SCALE] = 10000000
2048 [SPEED OFFSET] = -410667
2049 [EQUILIBRIUM BITS] = 16
2050 [EQUILIBRIUM SCALE] = 100
2051 [EQUILIBRIUM OFFSET] = 0
2052 [NODE BITS] = 15
2053 [NODE SCALE] = 10000
2054 [NODE OFFSET] = -3949
2055 [AMPLITUDE BITS] = 19
2056 [AMPLITUDE SCALE] = 10000
2057 [EPOCH BITS] = 16
2058 [EPOCH SCALE] = 100
2059 [RECORD TYPE BITS] = 4
2060 [LATITUDE BITS] = 25
2061 [LATITUDE SCALE] = 100000
2062 [LONGITUDE BITS] = 26
2063 [LONGITUDE SCALE] = 100000
2064 [RECORD SIZE BITS] = 12
2065 [STATION BITS] = 18
2066 [DATUM OFFSET BITS] = 32
2067 [DATUM OFFSET SCALE] = 10000
2068 [DATE BITS] = 27
2069 [MONTHS ON STATION BITS] = 10
2070 [CONFIDENCE VALUE BITS] = 4
2071 [TIME BITS] = 13
2072 [LEVEL ADD BITS] = 16
2073 [LEVEL ADD SCALE] = 100
2074 [LEVEL MULTIPLY BITS] = 16
2075 [LEVEL MULTIPLY SCALE] = 1000
2076 [DIRECTION BITS] = 9
2077 [LEVEL UNIT BITS] = 3
2078 [LEVEL UNIT TYPES] = 6
2079 [LEVEL UNIT SIZE] = 15
2080 [DIRECTION UNIT BITS] = 2
2081 [DIRECTION UNIT TYPES] = 3
2082 [DIRECTION UNIT SIZE] = 15
2083 [RESTRICTION BITS] = 4
2084 [RESTRICTION TYPES] = 2
2085 [RESTRICTION SIZE] = 30
2086 [PEDIGREE BITS] = 6
2087 [PEDIGREE TYPES] = 13
2088 [PEDIGREE SIZE] = 60
2089 [DATUM BITS] = 7
2090 [DATUM TYPES] = 61
2091 [DATUM SIZE] = 70
2092 [CONSTITUENT BITS] = 8
2093 [CONSTITUENTS] = 173
2094 [CONSTITUENT SIZE] = 10
2095 [COUNTRY BITS] = 9
2096 [COUNTRIES] = 240
2097 [COUNTRY SIZE] = 50
2098 [TZFILE BITS] = 10
2099 [TZFILES] = 449
2100 [TZFILE SIZE] = 30
2101 [END OF FILE] = 2585170
2102 [END OF ASCII HEADER DATA]
2103
2104 Most of these values will make sense in the context of the following
2105 description of the rest of the file. Some caveats on the data storage -
2106 if no SCALE is listed for a field, the scale is 1. If no BITS field is
2107 listed, this is a variable length character field and is stored as 8 bit
2108 ASCII characters. If no OFFSET is listed, the offset is 0. Offsets are
2109 scaled. All SIZE fields refer to the maximum length, in characters, of a
2110 variable length character field. Some of the BITS fields are calculated
2111 while others are hardwired (see code). For instance, [DIRECTION BITS] is
2112 hardwired because it is an integer field whose value can only be from 0 to
2113 361 (361 = no direction flag). [NODE BITS], on the other hand, is
2114 calculated on creation by checking the min, max, and range of all of the
2115 node factor values. The number of bits needed is easily calculated by
2116 taking the log of the adjusted, scaled range, dividing by the log of 2 and
2117 adding 1. Immediately following the ASCII portion of the header is a 32
2118 bit checksum of the ASCII portion of the header. Why? Because some
2119 genius always gets the idea that he/she can modify the header with a text
2120 or hex editor. Go figure.
2121
2122 The rest of the header is as follows :
2123
2124 [LEVEL UNIT TYPES] fields of [LEVEL UNIT SIZE] characters, each field
2125 is internally 0 terminated (anything after the zero is garbage)
2126
2127 [DIRECTION UNIT TYPES] fields of [DIRECTION UNIT SIZE] characters, 0
2128 terminated
2129
2130 [RESTRICTION TYPES] fields of [RESTRICTION SIZE] characters, 0
2131 terminated
2132
2133 [PEDIGREE TYPES] fields of [PEDIGREE SIZE] characters, 0 terminated
2134
2135 [TZFILES] fields of [TZFILE SIZE] characters, 0 terminated
2136
2137 [COUNTRIES] fields of [COUNTRY SIZE] characters, 0 terminated
2138
2139 [DATUM TYPES] fields of [DATUM SIZE] characters, 0 terminated
2140
2141 [CONSTITUENTS] fields of [CONSTITUENT SIZE] characters, 0 terminated
2142 Yes, I know, I wasted some space with these fields but I wasn't
2143 worried about a couple of hundred bytes.
2144
2145 [CONSTITUENTS] fields of [SPEED BITS], speed values (scaled and offset)
2146
2147 [CONSTITUENTS] groups of [NUMBER OF YEARS] fields of
2148 [EQUILIBRIUM BITS], equilibrium arguments (scaled and offset)
2149
2150 [CONSTITUENTS] groups of [NUMBER OF YEARS] fields of [NODE BITS], node
2151 factors (scaled and offset)
2152
2153
2154 Finally, the data. At present there are two types of records in the file.
2155 These are reference stations (record type 1) and subordinate stations
2156 (record type 2). Reference stations contain a set of constituents while
2157 subordinate stations contain a number of offsets to be applied to the
2158 reference station that they are associated with. Note that reference
2159 stations (record type 1) may, in actuality, be subordinate stations, albeit
2160 with a set of constituents. All of the records have the following subset
2161 of information stored as the first part of the record:
2162
2163 [RECORD SIZE BITS] - record size in bytes
2164 [RECORD TYPE BITS] - record type (1 or 2)
2165 [LATITUDE BITS] - latitude (degrees, south negative, scaled & offset)
2166 [LONGITUDE BITS] - longitude (degrees, west negative, scaled & offset)
2167 [TZFILE BITS] - index into timezone array (retrieved from header)
2168 variable size - station name, 0 terminated
2169 [STATION BITS] - record number of reference station or -1
2170 [COUNTRY_BITS] index into country array (retrieved from header)
2171 [PEDIGREE BITS] - index into pedigree array (retrieved from header)
2172 variable size - source, 0 terminated
2173 [RESTRICTION BITS] - index into restriction array
2174 variable size - comments, may contain LFs to indicate newline (no CRs)
2175
2176
2177 These are the rest of the fields for record type 1:
2178
2179 [LEVEL UNIT BITS] - index into level units array
2180 [DATUM OFFSET BITS] - datum offset (scaled)
2181 [DATUM BITS] - index into datum name array
2182 [TIME BITS] - time zone offset from GMT0 (meridian, integer +/-HHMM)
2183 [DATE BITS] - expiration date, (integer YYYYMMDD, default is 0)
2184 [MONTHS ON STATION BITS] - months on station
2185 [DATE BITS] - last date on station, default is 0
2186 [CONFIDENCE BITS] - confidence value (TBD)
2187 [CONSTITUENT BITS] - "N", number of constituents for this station
2188
2189 N groups of:
2190 [CONSTITUENT BITS] - constituent number
2191 [AMPLITUDE BITS] - amplitude (scaled & offset)
2192 [EPOCH BITS] - epoch (scaled & offset)
2193
2194
2195 These are the rest of the fields for record type 2:
2196
2197 [LEVEL UNIT BITS] - leveladd units, index into level_units array
2198 [DIRECTION UNIT BITS] - direction units, index into dir_units array
2199 [LEVEL UNIT BITS] - avglevel units, index into level_units array
2200 [TIME BITS] - min timeadd (integer +/-HHMM) or 0
2201 [LEVEL ADD BITS] - min leveladd (scaled) or 0
2202 [LEVEL MULTIPLY BITS] - min levelmultiply (scaled) or 0
2203 [LEVEL ADD BITS] - min avglevel (scaled) or 0
2204 [DIRECTION BITS] - min direction (0-360 or 361 for no direction)
2205 [TIME BITS] - max timeadd (integer +/-HHMM) or 0
2206 [LEVEL ADD BITS] - max leveladd (scaled) or 0
2207 [LEVEL MULTIPLY BITS] - max levelmultiply (scaled) or 0
2208 [LEVEL ADD BITS] - max avglevel (scaled) or 0
2209 [DIRECTION BITS] - max direction (0-360 or 361 for no direction)
2210 [TIME BITS] - floodbegins (integer +/-HHMM) or NULLSLACKOFFSET
2211 [TIME BITS] - ebbbegins (integer +/-HHMM) or NULLSLACKOFFSET
2212
2213
2214 Back to philosophy! When you design a database of any kind the first
2215 thing you should ask yourself is "Self, how am I going to access this
2216 data most of the time?". If you answer yourself out loud you should
2217 consider seeing a shrink. 99 and 44/100ths percent of the time this
2218 database is going to be read to get station data. The other 66/100ths
2219 percent of the time it will be created/modified. Variable length records
2220 are no problem on retrieval. They are no problem to create. They can be
2221 a major pain in the backside if you have to modify/delete them. Since we
2222 shouldn't be doing too much editing of the data (usually just adding
2223 records) this is a pretty fair design. At some point though we are going
2224 to want to modify or delete a record. There are two possibilities here.
2225 We can dump the database to an ASCII file or files using restore_tide_db,
2226 use a text editor to modify them, and then rebuild the database. The
2227 other possibility is to modify the record in place. This is OK if you
2228 don't change a variable length field but what if you want to change the
2229 station name or add a couple of constituents? With the design as is we
2230 have to read the remainder of the file from the end of the record to be
2231 modified, write the modified record, rewrite the remainder of the file,
2232 and then change the end_of_file pointer in the header. So, which fields
2233 are going to be a problem? Changes to station name, source, comments, or
2234 the number of constituents for a station will require a resizing of the
2235 database. Changes to any of the other fields can be done in place. The
2236 worst thing that you can do though is to delete a record. Not just
2237 because the file has to be resized but because it might be a reference
2238 record with subordinate stations. These would have to be deleted as well.
2239 The delete_tide_record function will do just that so make sure you check
2240 before you call it. You might not want to do that.
2241
2242 Another point to note is that when you open the database the records are
2243 indexed at that point. This takes about half a second on a dual 450.
2244 Most applications use the header part of the record very often and
2245 the rest of the record only if they are going to actually produce
2246 predicted tides. For instance, XTide plots all of the stations on a
2247 world map or globe and lists all of the station names. It also needs the
2248 timezone up front. To save re-indexing to get these values I save them
2249 in memory. The only time an application needs to actually read an entire
2250 record is when you want to do the prediction. Otherwise just use
2251 get_partial_tide_record or get_next_partial_tide_record to yank the good
2252 stuff out of memory.
2253
2254 'Nuff said?
2255
2256
2257 See libtcd.html for changelog.
2258
2259*****************************************************************************/
2260
2261/* Maintenance by DWF */
2262
2263/* Function prototypes. */
2264
2265NV_U_INT32 calculate_bits(NV_U_INT32 value);
2266void bit_pack(NV_U_BYTE *, NV_U_INT32, NV_U_INT32, NV_INT32);
2267NV_U_INT32 bit_unpack(NV_U_BYTE *, NV_U_INT32, NV_U_INT32);
2268NV_INT32 signed_bit_unpack(NV_U_BYTE buffer[], NV_U_INT32 start,
2269 NV_U_INT32 numbits);
2270
2271/* Global variables. */
2272
2273typedef struct {
2274 NV_INT32 address;
2275 NV_U_INT32 record_size;
2276 NV_U_INT16 tzfile;
2277 NV_INT32 reference_station;
2278 NV_INT32 lat;
2279 NV_INT32 lon;
2280 NV_U_BYTE record_type;
2281 NV_CHAR *name;
2282} TIDE_INDEX;
2283
2284static FILE *fp = NULL;
2285static TIDE_INDEX *tindex = NULL;
2286static NV_BOOL modified = NVFalse;
2287static NV_INT32 current_record, current_index;
2288static NV_CHAR filename[MONOLOGUE_LENGTH];
2289
2290/*****************************************************************************\
2291 Checked fread and fwrite wrappers
2292 DWF 2007-12-02
2293
2294 Fedora package compiles generate warnings for invoking these
2295 functions without checking the return.
2296\*****************************************************************************/
2297
2298static void chk_fread(void *ptr, size_t size, size_t nmemb, FILE *stream) {
2299 size_t ret;
2300 ret = fread(ptr, size, nmemb, stream);
2301 if (ret != nmemb) {
2302 // LOG_ERROR ("libtcd unexpected error: fread failed\n");
2303 // LOG_ERROR ("nmemb = %lu, got %lu\n", nmemb, ret);
2304 throw std::runtime_error("tcmgr file read exception");
2305 }
2306}
2307
2308static void chk_fwrite(const void *ptr, size_t size, size_t nmemb,
2309 FILE *stream) {
2310 size_t ret;
2311 ret = fwrite(ptr, size, nmemb, stream);
2312 if (ret != nmemb) {
2313 // LOG_ERROR ("libtcd unexpected error: fwrite failed\n");
2314 // LOG_ERROR ("nmemb = %lu, got %lu\n", nmemb, ret);
2315 // LOG_ERROR ("The database is probably corrupt now.\n");
2316 throw std::runtime_error("tcmgr file read exception");
2317 }
2318}
2319
2320/*****************************************************************************\
2321
2322 Function dump_tide_record - prints out all of the fields in the
2323 input tide record
2324
2325 Synopsis dump_tide_record (rec);
2326
2327 TIDE_RECORD *rec pointer to the tide record
2328
2329 Returns void
2330
2331 Author Jan C. Depner
2332 Date 08/01/02
2333
2334 See libtcd.html for changelog.
2335
2336\*****************************************************************************/
2337
2338void dump_tide_record(const TIDE_RECORD *rec) {
2339 NV_U_INT32 i;
2340
2341 assert(rec);
2342
2343 LOG_ERROR("\n\nRecord number = %d\n", rec->header.record_number);
2344 LOG_ERROR("Record size = %u\n", rec->header.record_size);
2345 LOG_ERROR("Record type = %u\n", rec->header.record_type);
2346 LOG_ERROR("Latitude = %f\n", rec->header.latitude);
2347 LOG_ERROR("Longitude = %f\n", rec->header.longitude);
2348 LOG_ERROR("Reference station = %d\n", rec->header.reference_station);
2349 LOG_ERROR("Tzfile = %s\n", get_tzfile(rec->header.tzfile));
2350 LOG_ERROR("Name = %s\n", rec->header.name);
2351
2352 LOG_ERROR("Country = %s\n", get_country(rec->country));
2353 LOG_ERROR("Source = %s\n", rec->source);
2354 LOG_ERROR("Restriction = %s\n", get_restriction(rec->restriction));
2355 LOG_ERROR("Comments = %s\n", rec->comments);
2356 LOG_ERROR("Notes = %s\n", rec->notes);
2357 LOG_ERROR("Legalese = %s\n", get_legalese(rec->legalese));
2358 LOG_ERROR("Station ID context = %s\n", rec->station_id_context);
2359 LOG_ERROR("Station ID = %s\n", rec->station_id);
2360 LOG_ERROR("Date imported = %d\n", rec->date_imported);
2361 LOG_ERROR("Xfields = %s\n", rec->xfields);
2362
2363 LOG_ERROR("Direction units = %s\n", get_dir_units(rec->direction_units));
2364 LOG_ERROR("Min direction = %d\n", rec->min_direction);
2365 LOG_ERROR("Max direction = %d\n", rec->max_direction);
2366 LOG_ERROR("Level units = %s\n", get_level_units(rec->level_units));
2367
2368 if (rec->header.record_type == REFERENCE_STATION) {
2369 LOG_ERROR("Datum offset = %f\n", rec->datum_offset);
2370 LOG_ERROR("Datum = %s\n", get_datum(rec->datum));
2371 LOG_ERROR("Zone offset = %d\n", rec->zone_offset);
2372 LOG_ERROR("Expiration date = %d\n", rec->expiration_date);
2373 LOG_ERROR("Months on station = %d\n", rec->months_on_station);
2374 LOG_ERROR("Last date on station = %d\n", rec->last_date_on_station);
2375 LOG_ERROR("Confidence = %d\n", rec->confidence);
2376 for (i = 0; i < hd.pub.constituents; ++i) {
2377 if (rec->amplitude[i] != 0.0 || rec->epoch[i] != 0.0) {
2378 LOG_ERROR("Amplitude[%d] = %f\n", i, rec->amplitude[i]);
2379 LOG_ERROR("Epoch[%d] = %f\n", i, rec->epoch[i]);
2380 }
2381 }
2382 }
2383
2384 else if (rec->header.record_type == SUBORDINATE_STATION) {
2385 LOG_ERROR("Min time add = %d\n", rec->min_time_add);
2386 LOG_ERROR("Min level add = %f\n", rec->min_level_add);
2387 LOG_ERROR("Min level multiply = %f\n", rec->min_level_multiply);
2388 LOG_ERROR("Max time add = %d\n", rec->max_time_add);
2389 LOG_ERROR("Max level add = %f\n", rec->max_level_add);
2390 LOG_ERROR("Max level multiply = %f\n", rec->max_level_multiply);
2391 LOG_ERROR("Flood begins = %d\n", rec->flood_begins);
2392 LOG_ERROR("Ebb begins = %d\n", rec->ebb_begins);
2393 }
2394}
2395
2396/*****************************************************************************\
2397
2398 Function write_protect - prevent trying to modify TCD files of
2399 an earlier version. Nothing to do with file locking.
2400
2401 David Flater, 2004-10-14.
2402
2403\*****************************************************************************/
2404
2405static void write_protect() {
2406 if (hd.pub.major_rev < LIBTCD_MAJOR_REV) {
2407 LOG_ERROR(
2408 "libtcd error: can't modify TCD files created by earlier version. "
2409 "Use\nrewrite_tide_db to upgrade the TCD file.\n");
2410 exit(-1);
2411 }
2412}
2413
2414/*****************************************************************************\
2415
2416 Function get_country - gets the country field for record "num"
2417
2418 Synopsis get_country (num);
2419
2420 NV_INT32 num tide record number
2421
2422 Returns NV_CHAR * country name (associated with
2423 ISO 3166-1:1999 2-character
2424 country code
2425
2426 Author Jan C. Depner
2427 Date 08/01/02
2428
2429 See libtcd.html for changelog.
2430
2431\*****************************************************************************/
2432
2433const NV_CHAR *get_country(NV_INT32 num) {
2434 if (!fp) {
2435 LOG_ERROR(
2436 "libtcd error: attempt to access database when database not open\n");
2437 exit(-1);
2438 }
2439 if (num >= 0 && num < (NV_INT32)hd.pub.countries) return (hd.country[num]);
2440 return ("Unknown");
2441}
2442
2443/*****************************************************************************\
2444
2445 Function get_tzfile - gets the time zone name for record "num"
2446
2447 Synopsis get_tzfile (num);
2448
2449 NV_INT32 num tide record number
2450
2451 Returns NV_CHAR * time zone name used in TZ variable
2452
2453 Author Jan C. Depner
2454 Date 08/01/02
2455
2456 See libtcd.html for changelog.
2457
2458\*****************************************************************************/
2459
2460const NV_CHAR *get_tzfile(NV_INT32 num) {
2461 if (!fp) {
2462 LOG_ERROR(
2463 "libtcd error: attempt to access database when database not open\n");
2464 exit(-1);
2465 }
2466 if (num >= 0 && num < (NV_INT32)hd.pub.tzfiles) return (hd.tzfile[num]);
2467 return ("Unknown");
2468}
2469
2470/*****************************************************************************\
2471
2472 Function get_station - get the name of the station for record "num"
2473
2474 Synopsis get_station (num);
2475
2476 NV_INT32 num tide record number
2477
2478 Returns NV_CHAR * station name
2479
2480 Author Jan C. Depner
2481 Date 08/01/02
2482
2483 See libtcd.html for changelog.
2484
2485\*****************************************************************************/
2486
2487const NV_CHAR *get_station(NV_INT32 num) {
2488 if (!fp) {
2489 LOG_ERROR(
2490 "libtcd error: attempt to access database when database not open\n");
2491 exit(-1);
2492 }
2493 if (num >= 0 && num < (NV_INT32)hd.pub.number_of_records)
2494 return (tindex[num].name);
2495 return ("Unknown");
2496}
2497
2498/*****************************************************************************\
2499
2500 Function get_constituent - get the constituent name for constituent
2501 number "num"
2502
2503 Synopsis get_constituent (num);
2504
2505 NV_INT32 num constituent number
2506
2507 Returns NV_CHAR * constituent name
2508
2509 Author Jan C. Depner
2510 Date 08/01/02
2511
2512 See libtcd.html for changelog.
2513
2514\*****************************************************************************/
2515
2516const NV_CHAR *get_constituent(NV_INT32 num) {
2517 if (!fp) {
2518 LOG_ERROR(
2519 "libtcd error: attempt to access database when database not open\n");
2520 exit(-1);
2521 }
2522 if (num >= 0 && num < (NV_INT32)hd.pub.constituents)
2523 return (hd.constituent[num]);
2524 return ("Unknown");
2525}
2526
2527/*****************************************************************************\
2528
2529 Function get_level_units - get the level units for level units
2530 number "num"
2531
2532 Synopsis get_level_units (num);
2533
2534 NV_INT32 num level units number
2535
2536 Returns NV_CHAR * units (ex. "meters");
2537
2538 Author Jan C. Depner
2539 Date 08/01/02
2540
2541 See libtcd.html for changelog.
2542
2543\*****************************************************************************/
2544
2545const NV_CHAR *get_level_units(NV_INT32 num) {
2546 if (!fp) {
2547 LOG_ERROR(
2548 "libtcd error: attempt to access database when database not open\n");
2549 exit(-1);
2550 }
2551 if (num >= 0 && num < (NV_INT32)hd.pub.level_unit_types)
2552 return (hd.level_unit[num]);
2553 return ("Unknown");
2554}
2555
2556/*****************************************************************************\
2557
2558 Function get_dir_units - get the direction units for direction
2559 units number "num"
2560
2561 Synopsis get_dir_units (num);
2562
2563 NV_INT32 num direction units number
2564
2565 Returns NV_CHAR * units (ex. "degrees true");
2566
2567 Author Jan C. Depner
2568 Date 08/01/02
2569
2570 See libtcd.html for changelog.
2571
2572\*****************************************************************************/
2573
2574const NV_CHAR *get_dir_units(NV_INT32 num) {
2575 if (!fp) {
2576 LOG_ERROR(
2577 "libtcd error: attempt to access database when database not open\n");
2578 exit(-1);
2579 }
2580 if (num >= 0 && num < (NV_INT32)hd.pub.dir_unit_types)
2581 return (hd.dir_unit[num]);
2582 return ("Unknown");
2583}
2584
2585/*****************************************************************************\
2586
2587 Function get_restriction - gets the restriction description for
2588 restriction number "num"
2589
2590 Synopsis get_restriction (num);
2591
2592 NV_INT32 num restriction number
2593
2594 Returns NV_CHAR * restriction (ex. "PUBLIC DOMAIN");
2595
2596 Author Jan C. Depner
2597 Date 08/01/02
2598
2599 See libtcd.html for changelog.
2600
2601\*****************************************************************************/
2602
2603const NV_CHAR *get_restriction(NV_INT32 num) {
2604 if (!fp) {
2605 LOG_ERROR(
2606 "libtcd error: attempt to access database when database not open\n");
2607 exit(-1);
2608 }
2609 if (num >= 0 && num < (NV_INT32)hd.pub.restriction_types)
2610 return (hd.restriction[num]);
2611 return ("Unknown");
2612}
2613
2614/*****************************************************************************\
2615
2616 Function get_pedigree - gets the pedigree description for pedigree
2617 number "num"
2618
2619 Synopsis get_pedigree (num);
2620
2621 NV_INT32 num pedigree number
2622
2623 Returns NV_CHAR * pedigree description
2624
2625 Author Jan C. Depner
2626 Date 08/01/02
2627
2628 See libtcd.html for changelog.
2629
2630\*****************************************************************************/
2631
2632#ifdef COMPAT114
2633NV_CHAR *get_pedigree(NV_INT32 num) { return "Unknown"; }
2634#endif
2635
2636/*****************************************************************************\
2637
2638 Function get_datum - gets the datum name for datum number "num"
2639
2640 Synopsis get_datum (num);
2641
2642 NV_INT32 num datum number
2643
2644 Returns NV_CHAR * datum name
2645
2646 Author Jan C. Depner
2647 Date 08/01/02
2648
2649 See libtcd.html for changelog.
2650
2651\*****************************************************************************/
2652
2653const NV_CHAR *get_datum(NV_INT32 num) {
2654 if (!fp) {
2655 LOG_ERROR(
2656 "libtcd error: attempt to access database when database not open\n");
2657 exit(-1);
2658 }
2659 if (num >= 0 && num < (NV_INT32)hd.pub.datum_types) return (hd.datum[num]);
2660 return ("Unknown");
2661}
2662
2663/*****************************************************************************\
2664DWF 2004-10-14
2665\*****************************************************************************/
2666const NV_CHAR *get_legalese(NV_INT32 num) {
2667 if (!fp) {
2668 LOG_ERROR(
2669 "libtcd error: attempt to access database when database not open\n");
2670 exit(-1);
2671 }
2672 if (num >= 0 && num < (NV_INT32)hd.pub.legaleses) return (hd.legalese[num]);
2673 return ("Unknown");
2674}
2675
2676/*****************************************************************************\
2677
2678 Function get_speed - gets the speed value for constituent number
2679 "num"
2680
2681 Synopsis get_speed (num);
2682
2683 NV_INT32 num constituent number
2684
2685 Returns NV_FLOAT64 speed
2686
2687 Author Jan C. Depner
2688 Date 08/01/02
2689
2690 See libtcd.html for changelog.
2691
2692\*****************************************************************************/
2693
2694NV_FLOAT64 get_speed(NV_INT32 num) {
2695 if (!fp) {
2696 LOG_ERROR(
2697 "libtcd error: attempt to access database when database not open\n");
2698 exit(-1);
2699 }
2700 assert(num >= 0 && num < (NV_INT32)hd.pub.constituents);
2701 return hd.speed[num];
2702}
2703
2704/*****************************************************************************\
2705
2706 Function get_equilibrium - gets the equilibrium value for
2707 constituent number "num" and year "year"
2708
2709 Synopsis get_equilibrium (num, year);
2710
2711 NV_INT32 num constituent number
2712 NV_INT32 year year
2713
2714 Returns NV_FLOAT32 equilibrium argument
2715
2716 Author Jan C. Depner
2717 Date 08/01/02
2718
2719 See libtcd.html for changelog.
2720
2721\*****************************************************************************/
2722
2723NV_FLOAT32 get_equilibrium(NV_INT32 num, NV_INT32 year) {
2724 if (!fp) {
2725 LOG_ERROR(
2726 "libtcd error: attempt to access database when database not open\n");
2727 exit(-1);
2728 }
2729 assert(num >= 0 && num < (NV_INT32)hd.pub.constituents && year >= 0 &&
2730 year < (NV_INT32)hd.pub.number_of_years);
2731 return hd.equilibrium[num][year];
2732}
2733
2734/*****************************************************************************\
2735 DWF 2004-10-04
2736\*****************************************************************************/
2737NV_FLOAT32 *get_equilibriums(NV_INT32 num) {
2738 if (!fp) {
2739 LOG_ERROR(
2740 "libtcd error: attempt to access database when database not open\n");
2741 exit(-1);
2742 }
2743 assert(num >= 0 && num < (NV_INT32)hd.pub.constituents);
2744 return hd.equilibrium[num];
2745}
2746
2747/*****************************************************************************\
2748
2749 Function get_node_factor - gets the node factor value for
2750 constituent number "num" and year "year"
2751
2752 Synopsis get_node_factor (num, year);
2753
2754 NV_INT32 num constituent number
2755 NV_INT32 year year
2756
2757 Returns NV_FLOAT32 node factor
2758
2759 Author Jan C. Depner
2760 Date 08/01/02
2761
2762 See libtcd.html for changelog.
2763
2764\*****************************************************************************/
2765
2766NV_FLOAT32 get_node_factor(NV_INT32 num, NV_INT32 year) {
2767 if (!fp) {
2768 LOG_ERROR(
2769 "libtcd error: attempt to access database when database not open\n");
2770 exit(-1);
2771 }
2772 assert(num >= 0 && num < (NV_INT32)hd.pub.constituents && year >= 0 &&
2773 year < (NV_INT32)hd.pub.number_of_years);
2774 return hd.node_factor[num][year];
2775}
2776
2777/*****************************************************************************\
2778 DWF 2004-10-04
2779\*****************************************************************************/
2780NV_FLOAT32 *get_node_factors(NV_INT32 num) {
2781 if (!fp) {
2782 LOG_ERROR(
2783 "libtcd error: attempt to access database when database not open\n");
2784 exit(-1);
2785 }
2786 assert(num >= 0 && num < (NV_INT32)hd.pub.constituents);
2787 return hd.node_factor[num];
2788}
2789
2790/*****************************************************************************\
2791
2792 Function get_partial_tide_record - gets "header" portion of record
2793 "num" from the index that is stored in memory. This is
2794 way faster than reading it again and we have to read it
2795 to set up the index. This costs a bit in terms of
2796 memory but most applications use this data far more than
2797 the rest of the record.
2798
2799 Synopsis get_partial_tide_record (num, rec);
2800
2801 NV_INT32 num record number
2802 TIDE_STATION_HEADER *rec header portion of the record
2803
2804 Returns NV_BOOL NVTrue if successful
2805
2806 Author Jan C. Depner
2807 Date 08/01/02
2808
2809 See libtcd.html for changelog.
2810
2811\*****************************************************************************/
2812
2813NV_BOOL get_partial_tide_record(NV_INT32 num, TIDE_STATION_HEADER *rec) {
2814 if (!fp) {
2815 LOG_ERROR(
2816 "libtcd error: attempt to access database when database not open\n");
2817 return NVFalse;
2818 }
2819
2820 if (num < 0 || num >= (NV_INT32)hd.pub.number_of_records) return (NVFalse);
2821
2822 assert(rec);
2823
2824 rec->record_number = num;
2825 rec->record_size = tindex[num].record_size;
2826 rec->record_type = tindex[num].record_type;
2827 rec->latitude = (NV_FLOAT64)tindex[num].lat / hd.latitude_scale;
2828 rec->longitude = (NV_FLOAT64)tindex[num].lon / hd.longitude_scale;
2829 rec->reference_station = tindex[num].reference_station;
2830 rec->tzfile = tindex[num].tzfile;
2831 strcpy(rec->name, tindex[num].name);
2832
2833 current_index = num;
2834
2835 return (NVTrue);
2836}
2837
2838/*****************************************************************************\
2839
2840 Function get_next_partial_tide_record - gets "header" portion of
2841 the next record from the index that is stored in memory.
2842
2843 Synopsis get_next_partial_tide_record (rec);
2844
2845 TIDE_STATION_HEADER *rec header portion of the record
2846
2847 Returns NV_INT32 record number or -1 on failure
2848
2849 Author Jan C. Depner
2850 Date 08/01/02
2851
2852 See libtcd.html for changelog.
2853
2854\*****************************************************************************/
2855
2856NV_INT32 get_next_partial_tide_record(TIDE_STATION_HEADER *rec) {
2857 if (!get_partial_tide_record(current_index + 1, rec)) return (-1);
2858
2859 return (current_index);
2860}
2861
2862/*****************************************************************************\
2863
2864 Function get_nearest_partial_tide_record - gets "header" portion of
2865 the record closest geographically to the input position.
2866
2867 Synopsis get_nearest_partial_tide_record (lat, lon, rec);
2868
2869 NV_FLOAT64 lat latitude
2870 NV_FLOAT64 lon longitude
2871 TIDE_STATION_HEADER *rec header portion of the record
2872
2873 Returns NV_INT32 record number or -1 on failure
2874
2875 Author Jan C. Depner
2876 Date 08/01/02
2877
2878 See libtcd.html for changelog.
2879
2880\*****************************************************************************/
2881
2882NV_INT32 get_nearest_partial_tide_record(NV_FLOAT64 lat, NV_FLOAT64 lon,
2883 TIDE_STATION_HEADER *rec) {
2884 NV_FLOAT64 diff, min_diff, lt, ln;
2885 NV_U_INT32 i, shortest = 0;
2886
2887 min_diff = 999999999.9;
2888 for (i = 0; i < hd.pub.number_of_records; ++i) {
2889 lt = (NV_FLOAT64)tindex[i].lat / hd.latitude_scale;
2890 ln = (NV_FLOAT64)tindex[i].lon / hd.longitude_scale;
2891
2892 diff = sqrt((lat - lt) * (lat - lt) + (lon - ln) * (lon - ln));
2893
2894 if (diff < min_diff) {
2895 min_diff = diff;
2896 shortest = i;
2897 }
2898 }
2899
2900 if (!get_partial_tide_record(shortest, rec)) return (-1);
2901 return (shortest);
2902}
2903
2904/*****************************************************************************\
2905
2906 Function get_time - converts a time string in +/-HH:MM form to an
2907 integer in +/-HHMM form
2908
2909 Synopsis get_time (string);
2910
2911 NV_CHAR *string time string
2912
2913 Returns NV_INT32 time
2914
2915 Author Jan C. Depner
2916 Date 08/01/02
2917
2918 See libtcd.html for changelog.
2919
2920\*****************************************************************************/
2921
2922NV_INT32 get_time(const NV_CHAR *string) {
2923 NV_INT32 hour, minute, hhmm;
2924
2925 assert(string);
2926 sscanf(string, "%d:%d", &hour, &minute);
2927
2928 /* Trying to deal with negative 0 (-00:45). */
2929
2930 if (string[0] == '-') {
2931 if (hour < 0) hour = -hour;
2932
2933 hhmm = -(hour * 100 + minute);
2934 } else {
2935 hhmm = hour * 100 + minute;
2936 }
2937
2938 return (hhmm);
2939}
2940
2941/*****************************************************************************\
2942
2943 Function ret_time - converts a time value in +/-HHMM form to a
2944 time string in +/-HH:MM form
2945
2946 Synopsis ret_time (time);
2947
2948 NV_INT32 time
2949
2950 Returns NV_CHAR * time string
2951
2952 Author Jan C. Depner
2953 Date 08/01/02
2954
2955 See libtcd.html for changelog.
2956
2957\*****************************************************************************/
2958
2959NV_CHAR *ret_time(NV_INT32 time) {
2960 NV_INT32 hour, minute;
2961 static NV_CHAR tname[16];
2962
2963 hour = abs(time) / 100;
2964 assert(hour <= 99999 && hour >= -99999); /* 9 chars: +99999:99 */
2965 minute = abs(time) % 100;
2966
2967 if (time < 0) {
2968 sprintf(tname, "-%02d:%02d", hour, minute);
2969 } else {
2970 sprintf(tname, "+%02d:%02d", hour, minute);
2971 }
2972
2973 return tname;
2974}
2975
2976/*****************************************************************************\
2977 DWF 2004-10-04
2978\*****************************************************************************/
2979NV_CHAR *ret_time_neat(NV_INT32 time) {
2980 NV_INT32 hour, minute;
2981 static NV_CHAR tname[16];
2982
2983 hour = abs(time) / 100;
2984 assert(hour <= 99999 && hour >= -99999); /* 9 chars: +99999:99 */
2985 minute = abs(time) % 100;
2986
2987 if (time < 0)
2988 sprintf(tname, "-%d:%02d", hour, minute);
2989 else if (time > 0)
2990 sprintf(tname, "+%d:%02d", hour, minute);
2991 else
2992 strcpy(tname, "0:00");
2993
2994 return tname;
2995}
2996
2997/*****************************************************************************\
2998 DWF 2004-10-04
2999\*****************************************************************************/
3000NV_CHAR *ret_date(NV_U_INT32 date) {
3001 static NV_CHAR tname[30];
3002 if (!date)
3003 strcpy(tname, "NULL");
3004 else {
3005 unsigned y, m, d;
3006 y = date / 10000;
3007 date %= 10000;
3008 m = date / 100;
3009 d = date % 100;
3010 sprintf(tname, "%4u-%02u-%02u", y, m, d);
3011 }
3012 return tname;
3013}
3014
3015/*****************************************************************************\
3016
3017 Function get_tide_db_header - gets the public portion of the tide
3018 database header
3019
3020 Synopsis get_tide_db_header ();
3021
3022 Returns DB_HEADER_PUBLIC public tide header
3023
3024 Author Jan C. Depner
3025 Date 08/01/02
3026
3027 See libtcd.html for changelog.
3028
3029\*****************************************************************************/
3030
3031DB_HEADER_PUBLIC get_tide_db_header() {
3032 if (!fp) {
3033 LOG_ERROR(
3034 "libtcd error: attempt to access database when database not open\n");
3035 exit(-1);
3036 }
3037 return (hd.pub);
3038}
3039
3040/*****************************************************************************\
3041 DWF 2004-09-30
3042 Prevent buffer overflows for MONOLOGUE_LENGTH strings.
3043\*****************************************************************************/
3044static void boundscheck_monologue(const NV_CHAR *string) {
3045 assert(string);
3046 if (strlen(string) >= MONOLOGUE_LENGTH) {
3047 // LOG_ERROR ("libtcd fatal error: static buffer size exceeded\n");
3048 // LOG_ERROR ("Buffer is size MONOLOGUE_LENGTH (%u)\n",
3049 // MONOLOGUE_LENGTH);
3050 // LOG_ERROR ("String is length %lu\n", strlen(string));
3051 // LOG_ERROR ("The offending string is:\n%s\n", string);
3052 exit(-1);
3053 }
3054}
3055
3056/*****************************************************************************\
3057 DWF 2004-09-30
3058 Prevent buffer overflows for ONELINER_LENGTH strings.
3059\*****************************************************************************/
3060static void boundscheck_oneliner(const NV_CHAR *string) {
3061 assert(string);
3062 if (strlen(string) >= ONELINER_LENGTH) {
3063 // LOG_ERROR ("libtcd fatal error: static buffer size exceeded\n");
3064 // LOG_ERROR ("Buffer is size ONELINER_LENGTH (%u)\n",
3065 // ONELINER_LENGTH);
3066 // LOG_ERROR ("String is length %lu\n", strlen(string));
3067 // LOG_ERROR ("The offending string is:\n%s\n", string);
3068 exit(-1);
3069 }
3070}
3071
3072/*****************************************************************************\
3073
3074 Function clip_string - removes leading and trailing spaces from
3075 search strings.
3076
3077 Synopsis clip_string (string);
3078
3079 NV_CHAR *string search string
3080
3081 Returns NV_CHAR * clipped string
3082
3083 Author Jan C. Depner
3084 Date 09/16/02
3085
3086 See libtcd.html for changelog.
3087
3088\*****************************************************************************/
3089
3090static NV_CHAR *clip_string(const NV_CHAR *string) {
3091 static NV_CHAR new_string[MONOLOGUE_LENGTH];
3092 NV_INT32 i, l, start = -1, end = -1;
3093
3094 boundscheck_monologue(string);
3095 new_string[0] = '\0';
3096
3097 l = (int)strlen(string);
3098 if (l) {
3099 for (i = 0; i < l; ++i) {
3100 if (string[i] != ' ') {
3101 start = i;
3102 break;
3103 }
3104 }
3105 for (i = l - 1; i >= start; --i) {
3106 if (string[i] != ' ' && string[i] != 10 && string[i] != 13) {
3107 end = i;
3108 break;
3109 }
3110 }
3111 if (start > -1 && end > -1 && end >= start) {
3112 strncpy(new_string, string + start, end - start + 1);
3113 new_string[end - start + 1] = '\0';
3114 }
3115 }
3116 return new_string;
3117}
3118
3119/*****************************************************************************\
3120
3121 Function search_station - returns record numbers of all stations
3122 that have the string "string" anywhere in the station
3123 name. This search is case insensitive. When no more
3124 records are found it returns -1;
3125
3126 Synopsis search_station (string);
3127
3128 NV_CHAR *string search string
3129
3130 Returns NV_INT32 record number or -1 when no more
3131 matches
3132
3133 Author Jan C. Depner
3134 Date 08/01/02
3135
3136 See libtcd.html for changelog.
3137
3138\*****************************************************************************/
3139
3140NV_INT32 search_station(const NV_CHAR *string) {
3141 static NV_CHAR last_search[ONELINER_LENGTH];
3142 static NV_U_INT32 j = 0;
3143 NV_U_INT32 i;
3144 NV_CHAR name[ONELINER_LENGTH], search[ONELINER_LENGTH];
3145
3146 if (!fp) {
3147 LOG_ERROR(
3148 "libtcd error: attempt to access database when database not open\n");
3149 return -1;
3150 }
3151
3152 boundscheck_oneliner(string);
3153
3154 for (i = 0; i < strlen(string) + 1; ++i) search[i] = tolower(string[i]);
3155
3156 if (strcmp(search, last_search)) j = 0;
3157
3158 strcpy(last_search, search);
3159
3160 while (j < hd.pub.number_of_records) {
3161 for (i = 0; i < strlen(tindex[j].name) + 1; ++i)
3162 name[i] = tolower(tindex[j].name[i]);
3163
3164 ++j;
3165 if (strstr(name, search)) return (j - 1);
3166 }
3167
3168 j = 0;
3169 return -1;
3170}
3171
3172/*****************************************************************************\
3173
3174 Function find_station - finds the record number of the station
3175 that has name "name"
3176
3177 Synopsis find_station (name);
3178
3179 NV_CHAR *name station name
3180
3181 Returns NV_INT32 record number
3182
3183 Author Jan C. Depner
3184 Date 08/01/02
3185
3186 See libtcd.html for changelog.
3187
3188\*****************************************************************************/
3189
3190NV_INT32 find_station(const NV_CHAR *name) {
3191 NV_U_INT32 i;
3192
3193 if (!fp) {
3194 LOG_ERROR(
3195 "libtcd error: attempt to access database when database not open\n");
3196 return -1;
3197 }
3198
3199 assert(name);
3200 for (i = 0; i < hd.pub.number_of_records; ++i) {
3201 if (!strcmp(name, tindex[i].name)) return (i);
3202 }
3203
3204 return (-1);
3205}
3206
3207/*****************************************************************************\
3208
3209 Function find_tzfile - gets the timezone number (index into
3210 tzfile array) given the tzfile name
3211
3212 Synopsis find_tzfile (name);
3213
3214 NV_CHAR *name tzfile name
3215
3216 Returns NV_INT32 tzfile number
3217
3218 Author Jan C. Depner
3219 Date 08/01/02
3220
3221 See libtcd.html for changelog.
3222
3223\*****************************************************************************/
3224
3225NV_INT32 find_tzfile(const NV_CHAR *name) {
3226 NV_INT32 j;
3227 NV_U_INT32 i;
3228 NV_CHAR *temp;
3229
3230 if (!fp) {
3231 LOG_ERROR(
3232 "libtcd error: attempt to access database when database not open\n");
3233 return -1;
3234 }
3235
3236 temp = clip_string(name);
3237
3238 j = -1;
3239 for (i = 0; i < hd.pub.tzfiles; ++i) {
3240 if (!strcmp(temp, get_tzfile(i))) {
3241 j = i;
3242 break;
3243 }
3244 }
3245
3246 return (j);
3247}
3248
3249/*****************************************************************************\
3250
3251 Function find_country - gets the timezone number (index into
3252 country array) given the country name
3253
3254 Synopsis find_country (name);
3255
3256 NV_CHAR *name country name
3257
3258 Returns NV_INT32 country number
3259
3260 Author Jan C. Depner
3261 Date 08/01/02
3262
3263 See libtcd.html for changelog.
3264
3265\*****************************************************************************/
3266
3267NV_INT32 find_country(const NV_CHAR *name) {
3268 NV_INT32 j;
3269 NV_U_INT32 i;
3270 NV_CHAR *temp;
3271
3272 if (!fp) {
3273 LOG_ERROR(
3274 "libtcd error: attempt to access database when database not open\n");
3275 return -1;
3276 }
3277
3278 temp = clip_string(name);
3279
3280 j = -1;
3281 for (i = 0; i < hd.pub.countries; ++i) {
3282 if (!strcmp(temp, get_country(i))) {
3283 j = i;
3284 break;
3285 }
3286 }
3287
3288 return (j);
3289}
3290
3291/*****************************************************************************\
3292
3293 Function find_level_units - gets the index into the level_units
3294 array given the level units name
3295
3296 Synopsis find_level_units (name);
3297
3298 NV_CHAR *name units name (ex. "meters")
3299
3300 Returns NV_INT32 units number
3301
3302 Author Jan C. Depner
3303 Date 08/01/02
3304
3305 See libtcd.html for changelog.
3306
3307\*****************************************************************************/
3308
3309NV_INT32 find_level_units(const NV_CHAR *name) {
3310 NV_INT32 j;
3311 NV_U_INT32 i;
3312 NV_CHAR *temp;
3313
3314 if (!fp) {
3315 LOG_ERROR(
3316 "libtcd error: attempt to access database when database not open\n");
3317 return -1;
3318 }
3319
3320 temp = clip_string(name);
3321
3322 j = -1;
3323 for (i = 0; i < hd.pub.level_unit_types; ++i) {
3324 if (!strcmp(get_level_units(i), temp)) {
3325 j = i;
3326 break;
3327 }
3328 }
3329
3330 return (j);
3331}
3332
3333/*****************************************************************************\
3334
3335 Function find_dir_units - gets the index into the dir_units
3336 array given the direction units name
3337
3338 Synopsis find_dir_units (name);
3339
3340 NV_CHAR *name units name (ex. "degrees true")
3341
3342 Returns NV_INT32 units number
3343
3344 Author Jan C. Depner
3345 Date 08/01/02
3346
3347 See libtcd.html for changelog.
3348
3349\*****************************************************************************/
3350
3351NV_INT32 find_dir_units(const NV_CHAR *name) {
3352 NV_INT32 j;
3353 NV_U_INT32 i;
3354 NV_CHAR *temp;
3355
3356 if (!fp) {
3357 LOG_ERROR(
3358 "libtcd error: attempt to access database when database not open\n");
3359 return -1;
3360 }
3361
3362 temp = clip_string(name);
3363
3364 j = -1;
3365 for (i = 0; i < hd.pub.dir_unit_types; ++i) {
3366 if (!strcmp(get_dir_units(i), temp)) {
3367 j = i;
3368 break;
3369 }
3370 }
3371
3372 return (j);
3373}
3374
3375/*****************************************************************************\
3376
3377 Function find_pedigree - gets the index into the pedigree array
3378 given the pedigree name
3379
3380 Synopsis find_pedigree (name);
3381
3382 NV_CHAR *name pedigree name
3383
3384 Returns NV_INT32 pedigree number
3385
3386 Author Jan C. Depner
3387 Date 08/01/02
3388
3389 See libtcd.html for changelog.
3390
3391\*****************************************************************************/
3392
3393#ifdef COMPAT114
3394NV_INT32 find_pedigree(const NV_CHAR *name) { return 0; }
3395#endif
3396
3397/*****************************************************************************\
3398
3399 Function find_datum - gets the index into the datum array given the
3400 datum name
3401
3402 Synopsis find_datum (name);
3403
3404 NV_CHAR *name datum name
3405
3406 Returns NV_INT32 datum number
3407
3408 Author Jan C. Depner
3409 Date 08/01/02
3410
3411 See libtcd.html for changelog.
3412
3413\*****************************************************************************/
3414
3415NV_INT32 find_datum(const NV_CHAR *name) {
3416 NV_INT32 j;
3417 NV_U_INT32 i;
3418 NV_CHAR *temp;
3419
3420 if (!fp) {
3421 LOG_ERROR(
3422 "libtcd error: attempt to access database when database not open\n");
3423 return -1;
3424 }
3425
3426 temp = clip_string(name);
3427
3428 j = -1;
3429 for (i = 0; i < hd.pub.datum_types; ++i) {
3430 if (!strcmp(get_datum(i), temp)) {
3431 j = i;
3432 break;
3433 }
3434 }
3435
3436 return (j);
3437}
3438
3439/*****************************************************************************\
3440 DWF 2004-10-14
3441\*****************************************************************************/
3442NV_INT32 find_legalese(const NV_CHAR *name) {
3443 NV_INT32 j;
3444 NV_U_INT32 i;
3445 NV_CHAR *temp;
3446
3447 if (!fp) {
3448 LOG_ERROR(
3449 "libtcd error: attempt to access database when database not open\n");
3450 return -1;
3451 }
3452
3453 temp = clip_string(name);
3454
3455 j = -1;
3456 for (i = 0; i < hd.pub.legaleses; ++i) {
3457 if (!strcmp(get_legalese(i), temp)) {
3458 j = i;
3459 break;
3460 }
3461 }
3462
3463 return (j);
3464}
3465
3466/*****************************************************************************\
3467
3468 Function find_constituent - gets the index into the constituent
3469 arrays for the named constituent.
3470
3471 Synopsis find_constituent (name);
3472
3473 NV_CHAR *name constituent name (ex. M2)
3474
3475 Returns NV_INT32 index into constituent arrays or -1
3476 on failure
3477
3478 Author Jan C. Depner
3479 Date 08/01/02
3480
3481 See libtcd.html for changelog.
3482
3483\*****************************************************************************/
3484
3485NV_INT32 find_constituent(const NV_CHAR *name) {
3486 NV_U_INT32 i;
3487 NV_CHAR *temp;
3488
3489 if (!fp) {
3490 LOG_ERROR(
3491 "libtcd error: attempt to access database when database not open\n");
3492 return -1;
3493 }
3494
3495 temp = clip_string(name);
3496
3497 for (i = 0; i < hd.pub.constituents; ++i) {
3498 if (!strcmp(get_constituent(i), temp)) return (i);
3499 }
3500
3501 return (-1);
3502}
3503
3504/*****************************************************************************\
3505
3506 Function find_restriction - gets the index into the restriction
3507 array given the restriction name
3508
3509 Synopsis find_restriction (name);
3510
3511 NV_CHAR *name restriction name
3512
3513 Returns NV_INT32 restriction number
3514
3515 Author Jan C. Depner
3516 Date 08/01/02
3517
3518 See libtcd.html for changelog.
3519
3520\*****************************************************************************/
3521
3522NV_INT32 find_restriction(const NV_CHAR *name) {
3523 NV_INT32 j;
3524 NV_U_INT32 i;
3525 NV_CHAR *temp;
3526
3527 if (!fp) {
3528 LOG_ERROR(
3529 "libtcd error: attempt to access database when database not open\n");
3530 return -1;
3531 }
3532
3533 temp = clip_string(name);
3534
3535 j = -1;
3536 for (i = 0; i < hd.pub.restriction_types; ++i) {
3537 if (!strcmp(get_restriction(i), temp)) {
3538 j = i;
3539 break;
3540 }
3541 }
3542 return (j);
3543}
3544
3545/*****************************************************************************\
3546
3547 Function set_speed - sets the speed value for constituent "num"
3548
3549 Synopsis set_speed (num, value);
3550
3551 NV_INT32 num constituent number
3552 NV_FLOAT64 value speed value
3553
3554 Returns void
3555
3556 Author Jan C. Depner
3557 Date 08/01/02
3558
3559 See libtcd.html for changelog.
3560
3561\*****************************************************************************/
3562
3563void set_speed(NV_INT32 num, NV_FLOAT64 value) {
3564 if (!fp) {
3565 LOG_ERROR(
3566 "libtcd error: attempt to access database when database not open\n");
3567 exit(-1);
3568 }
3569 write_protect();
3570 assert(num >= 0 && num < (NV_INT32)hd.pub.constituents);
3571 if (value < 0.0) {
3572 LOG_ERROR("libtcd set_speed: somebody tried to set a negative speed (%f)\n",
3573 value);
3574 exit(-1);
3575 }
3576 hd.speed[num] = value;
3577 modified = NVTrue;
3578}
3579
3580/*****************************************************************************\
3581
3582 Function set_equilibrium - sets the equilibrium argument for
3583 constituent "num" and year "year"
3584
3585 Synopsis set_equilibrium (num, year, value);
3586
3587 NV_INT32 num constituent number
3588 NV_INT32 year year
3589 NV_FLOAT64 value equilibrium argument
3590
3591 Returns void
3592
3593 Author Jan C. Depner
3594 Date 08/01/02
3595
3596 See libtcd.html for changelog.
3597
3598\*****************************************************************************/
3599
3600void set_equilibrium(NV_INT32 num, NV_INT32 year, NV_FLOAT32 value) {
3601 if (!fp) {
3602 LOG_ERROR(
3603 "libtcd error: attempt to access database when database not open\n");
3604 exit(-1);
3605 }
3606 write_protect();
3607 assert(num >= 0 && num < (NV_INT32)hd.pub.constituents && year >= 0 &&
3608 year < (NV_INT32)hd.pub.number_of_years);
3609 hd.equilibrium[num][year] = value;
3610 modified = NVTrue;
3611}
3612
3613/*****************************************************************************\
3614
3615 Function set_node_factor - sets the node factor for constituent
3616 "num" and year "year"
3617
3618 Synopsis set_node_factor (num, year, value);
3619
3620 NV_INT32 num constituent number
3621 NV_INT32 year year
3622 NV_FLOAT64 value node factor
3623
3624 Returns void
3625
3626 Author Jan C. Depner
3627 Date 08/01/02
3628
3629 See libtcd.html for changelog.
3630
3631\*****************************************************************************/
3632
3633void set_node_factor(NV_INT32 num, NV_INT32 year, NV_FLOAT32 value) {
3634 if (!fp) {
3635 LOG_ERROR(
3636 "libtcd error: attempt to access database when database not open\n");
3637 exit(-1);
3638 }
3639 write_protect();
3640 assert(num >= 0 && num < (NV_INT32)hd.pub.constituents && year >= 0 &&
3641 year < (NV_INT32)hd.pub.number_of_years);
3642 if (value <= 0.0) {
3643 LOG_ERROR(
3644 "libtcd set_node_factor: somebody tried to set a negative or zero node "
3645 "factor (%f)\n",
3646 value);
3647 exit(-1);
3648 }
3649 hd.node_factor[num][year] = value;
3650 modified = NVTrue;
3651}
3652
3653/*****************************************************************************\
3654
3655 Function add_pedigree - adds a new pedigree to the database
3656
3657 Synopsis add_pedigree (name, db);
3658
3659 NV_CHAR *name new pedigree string
3660 DB_HEADER_PUBLIC *db modified header
3661
3662 Returns NV_INT32 new pedigree index
3663
3664 Author Jan C. Depner
3665 Date 09/20/02
3666
3667 See libtcd.html for changelog.
3668
3669\*****************************************************************************/
3670
3671#ifdef COMPAT114
3672NV_INT32 add_pedigree(const NV_CHAR *name, const DB_HEADER_PUBLIC *db) {
3673 return 0;
3674}
3675#endif
3676
3677/*****************************************************************************\
3678
3679 Function add_tzfile - adds a new tzfile to the database
3680
3681 Synopsis add_tzfile (name, db);
3682
3683 NV_CHAR *name new tzfile string
3684 DB_HEADER_PUBLIC *db modified header
3685
3686 Returns NV_INT32 new tzfile index
3687
3688 Author Jan C. Depner
3689 Date 09/20/02
3690
3691 See libtcd.html for changelog.
3692
3693\*****************************************************************************/
3694
3695NV_INT32 add_tzfile(const NV_CHAR *name, DB_HEADER_PUBLIC *db) {
3696 NV_CHAR *c_name;
3697
3698 if (!fp) {
3699 LOG_ERROR(
3700 "libtcd error: attempt to access database when database not open\n");
3701 exit(-1);
3702 }
3703 write_protect();
3704
3705 assert(name);
3706 if (strlen(name) + 1 > hd.tzfile_size) {
3707 LOG_ERROR("libtcd error: tzfile exceeds size limit (%u).\n",
3708 hd.tzfile_size);
3709 LOG_ERROR("The offending input is: %s\n", name);
3710 exit(-1);
3711 }
3712
3713 if (hd.pub.tzfiles == hd.max_tzfiles) {
3714 LOG_ERROR("You have exceeded the maximum number of tzfile types!\n");
3715 LOG_ERROR("You cannot add any new tzfile types.\n");
3716 LOG_ERROR("Modify the DEFAULT_TZFILE_BITS and rebuild the database.\n");
3717 exit(-1);
3718 }
3719
3720 c_name = clip_string(name);
3721
3722 hd.tzfile[hd.pub.tzfiles] =
3723 (NV_CHAR *)calloc(strlen(c_name) + 1, sizeof(NV_CHAR));
3724
3725 if (hd.tzfile[hd.pub.tzfiles] == NULL) {
3726 perror("Allocating new tzfile string");
3727 exit(-1);
3728 }
3729
3730 strcpy(hd.tzfile[hd.pub.tzfiles++], c_name);
3731 if (db) *db = hd.pub;
3732 modified = NVTrue;
3733 return (hd.pub.tzfiles - 1);
3734}
3735
3736/*****************************************************************************\
3737
3738 Function add_country - adds a new country to the database
3739
3740 Synopsis add_country (name, db);
3741
3742 NV_CHAR *name new country string
3743 DB_HEADER_PUBLIC *db modified header
3744
3745 Returns NV_INT32 new country index
3746
3747 Author Jan C. Depner
3748 Date 09/20/02
3749
3750 See libtcd.html for changelog.
3751
3752\*****************************************************************************/
3753
3754NV_INT32 add_country(const NV_CHAR *name, DB_HEADER_PUBLIC *db) {
3755 NV_CHAR *c_name;
3756
3757 if (!fp) {
3758 LOG_ERROR(
3759 "libtcd error: attempt to access database when database not open\n");
3760 exit(-1);
3761 }
3762 write_protect();
3763
3764 assert(name);
3765 if (strlen(name) + 1 > hd.country_size) {
3766 LOG_ERROR("libtcd error: country exceeds size limit (%u).\n",
3767 hd.country_size);
3768 LOG_ERROR("The offending input is: %s\n", name);
3769 exit(-1);
3770 }
3771
3772 if (hd.pub.countries == hd.max_countries) {
3773 LOG_ERROR("You have exceeded the maximum number of country names!\n");
3774 LOG_ERROR("You cannot add any new country names.\n");
3775 LOG_ERROR("Modify the DEFAULT_COUNTRY_BITS and rebuild the database.\n");
3776 exit(-1);
3777 }
3778
3779 c_name = clip_string(name);
3780
3781 hd.country[hd.pub.countries] =
3782 (NV_CHAR *)calloc(strlen(c_name) + 1, sizeof(NV_CHAR));
3783
3784 if (hd.country[hd.pub.countries] == NULL) {
3785 perror("Allocating new country string");
3786 exit(-1);
3787 }
3788
3789 strcpy(hd.country[hd.pub.countries++], c_name);
3790 if (db) *db = hd.pub;
3791 modified = NVTrue;
3792 return (hd.pub.countries - 1);
3793}
3794
3795/*****************************************************************************\
3796
3797 Function add_datum - adds a new datum to the database
3798
3799 Synopsis add_datum (name, db);
3800
3801 NV_CHAR *name new datum string
3802 DB_HEADER_PUBLIC *db modified header
3803
3804 Returns NV_INT32 new datum index
3805
3806 Author Jan C. Depner
3807 Date 09/20/02
3808
3809 See libtcd.html for changelog.
3810
3811\*****************************************************************************/
3812
3813NV_INT32 add_datum(const NV_CHAR *name, DB_HEADER_PUBLIC *db) {
3814 NV_CHAR *c_name;
3815
3816 if (!fp) {
3817 LOG_ERROR(
3818 "libtcd error: attempt to access database when database not open\n");
3819 exit(-1);
3820 }
3821 write_protect();
3822
3823 assert(name);
3824 if (strlen(name) + 1 > hd.datum_size) {
3825 LOG_ERROR("libtcd error: datum exceeds size limit (%u).\n", hd.datum_size);
3826 LOG_ERROR("The offending input is: %s\n", name);
3827 exit(-1);
3828 }
3829
3830 if (hd.pub.datum_types == hd.max_datum_types) {
3831 LOG_ERROR("You have exceeded the maximum number of datum types!\n");
3832 LOG_ERROR("You cannot add any new datum types.\n");
3833 LOG_ERROR("Modify the DEFAULT_DATUM_BITS and rebuild the database.\n");
3834 exit(-1);
3835 }
3836
3837 c_name = clip_string(name);
3838
3839 hd.datum[hd.pub.datum_types] =
3840 (NV_CHAR *)calloc(strlen(c_name) + 1, sizeof(NV_CHAR));
3841
3842 if (hd.datum[hd.pub.datum_types] == NULL) {
3843 perror("Allocating new datum string");
3844 exit(-1);
3845 }
3846
3847 strcpy(hd.datum[hd.pub.datum_types++], c_name);
3848 if (db) *db = hd.pub;
3849 modified = NVTrue;
3850 return (hd.pub.datum_types - 1);
3851}
3852
3853/*****************************************************************************\
3854 DWF 2004-10-14
3855\*****************************************************************************/
3856NV_INT32 add_legalese(const NV_CHAR *name, DB_HEADER_PUBLIC *db) {
3857 NV_CHAR *c_name;
3858
3859 if (!fp) {
3860 LOG_ERROR(
3861 "libtcd error: attempt to access database when database not open\n");
3862 exit(-1);
3863 }
3864 write_protect();
3865
3866 assert(name);
3867 if (strlen(name) + 1 > hd.legalese_size) {
3868 LOG_ERROR("libtcd error: legalese exceeds size limit (%u).\n",
3869 hd.legalese_size);
3870 LOG_ERROR("The offending input is: %s\n", name);
3871 exit(-1);
3872 }
3873
3874 if (hd.pub.legaleses == hd.max_legaleses) {
3875 LOG_ERROR("You have exceeded the maximum number of legaleses!\n");
3876 LOG_ERROR("You cannot add any new legaleses.\n");
3877 LOG_ERROR("Modify the DEFAULT_LEGALESE_BITS and rebuild the database.\n");
3878 exit(-1);
3879 }
3880
3881 c_name = clip_string(name);
3882
3883 hd.legalese[hd.pub.legaleses] =
3884 (NV_CHAR *)calloc(strlen(c_name) + 1, sizeof(NV_CHAR));
3885
3886 if (hd.legalese[hd.pub.legaleses] == NULL) {
3887 perror("Allocating new legalese string");
3888 exit(-1);
3889 }
3890
3891 strcpy(hd.legalese[hd.pub.legaleses++], c_name);
3892 if (db) *db = hd.pub;
3893 modified = NVTrue;
3894 return (hd.pub.legaleses - 1);
3895}
3896
3897/*****************************************************************************\
3898
3899 Function add_restriction - adds a new restriction to the database
3900
3901 Synopsis add_restriction (name, db);
3902
3903 NV_CHAR *name new restriction string
3904 DB_HEADER_PUBLIC *db modified header
3905
3906 Returns NV_INT32 new restriction index
3907
3908 Author Jan C. Depner
3909 Date 09/20/02
3910
3911 See libtcd.html for changelog.
3912
3913\*****************************************************************************/
3914
3915NV_INT32 add_restriction(const NV_CHAR *name, DB_HEADER_PUBLIC *db) {
3916 NV_CHAR *c_name;
3917
3918 if (!fp) {
3919 LOG_ERROR(
3920 "libtcd error: attempt to access database when database not open\n");
3921 exit(-1);
3922 }
3923 write_protect();
3924
3925 assert(name);
3926 if (strlen(name) + 1 > hd.restriction_size) {
3927 LOG_ERROR("libtcd error: restriction exceeds size limit (%u).\n",
3928 hd.restriction_size);
3929 LOG_ERROR("The offending input is: %s\n", name);
3930 exit(-1);
3931 }
3932
3933 if (hd.pub.restriction_types == hd.max_restriction_types) {
3934 LOG_ERROR("You have exceeded the maximum number of restriction types!\n");
3935 LOG_ERROR("You cannot add any new restriction types.\n");
3936 LOG_ERROR(
3937 "Modify the DEFAULT_RESTRICTION_BITS and rebuild the database.\n");
3938 exit(-1);
3939 }
3940
3941 c_name = clip_string(name);
3942
3943 hd.restriction[hd.pub.restriction_types] =
3944 (NV_CHAR *)calloc(strlen(c_name) + 1, sizeof(NV_CHAR));
3945
3946 if (hd.restriction[hd.pub.restriction_types] == NULL) {
3947 perror("Allocating new restriction string");
3948 exit(-1);
3949 }
3950
3951 strcpy(hd.restriction[hd.pub.restriction_types++], c_name);
3952 if (db) *db = hd.pub;
3953 modified = NVTrue;
3954 return (hd.pub.restriction_types - 1);
3955}
3956
3957/*****************************************************************************\
3958 DWF 2004-10-04
3959\*****************************************************************************/
3960NV_INT32 find_or_add_restriction(const NV_CHAR *name, DB_HEADER_PUBLIC *db) {
3961 NV_INT32 ret;
3962 ret = find_restriction(name);
3963 if (ret < 0) ret = add_restriction(name, db);
3964 assert(ret >= 0);
3965 return ret;
3966}
3967
3968/*****************************************************************************\
3969 DWF 2004-10-04
3970\*****************************************************************************/
3971NV_INT32 find_or_add_tzfile(const NV_CHAR *name, DB_HEADER_PUBLIC *db) {
3972 NV_INT32 ret;
3973 ret = find_tzfile(name);
3974 if (ret < 0) ret = add_tzfile(name, db);
3975 assert(ret >= 0);
3976 return ret;
3977}
3978
3979/*****************************************************************************\
3980 DWF 2004-10-04
3981\*****************************************************************************/
3982NV_INT32 find_or_add_country(const NV_CHAR *name, DB_HEADER_PUBLIC *db) {
3983 NV_INT32 ret;
3984 ret = find_country(name);
3985 if (ret < 0) ret = add_country(name, db);
3986 assert(ret >= 0);
3987 return ret;
3988}
3989
3990/*****************************************************************************\
3991 DWF 2004-10-04
3992\*****************************************************************************/
3993NV_INT32 find_or_add_datum(const NV_CHAR *name, DB_HEADER_PUBLIC *db) {
3994 NV_INT32 ret;
3995 ret = find_datum(name);
3996 if (ret < 0) ret = add_datum(name, db);
3997 assert(ret >= 0);
3998 return ret;
3999}
4000
4001/*****************************************************************************\
4002 DWF 2004-10-14
4003\*****************************************************************************/
4004NV_INT32 find_or_add_legalese(const NV_CHAR *name, DB_HEADER_PUBLIC *db) {
4005 NV_INT32 ret;
4006 ret = find_legalese(name);
4007 if (ret < 0) ret = add_legalese(name, db);
4008 assert(ret >= 0);
4009 return ret;
4010}
4011
4012/*****************************************************************************\
4013
4014 Function check_simple - checks tide record to see if it is a
4015 "simple" subordinate station.
4016
4017 Synopsis check_simple (rec);
4018
4019 TIDE_RECORD rec tide record
4020
4021 Returns NV_BOOL NVTrue if "simple"
4022
4023 Author Jan C. Depner
4024 Date 08/01/02
4025
4026 See libtcd.html for changelog.
4027
4028 "Simplified" type 2 records were done away with 2003-03-27 per the
4029 discussion in http://www.flaterco.com/xtide/tcd_notes.html. This
4030 function is now of interest only in restore_tide_db, which uses it
4031 to determine which XML format to output. Deprecated here, moved
4032 to restore_tide_db.
4033
4034\*****************************************************************************/
4035
4036#ifdef COMPAT114
4037NV_BOOL check_simple(TIDE_RECORD rec) {
4038 if (rec.max_time_add == rec.min_time_add &&
4039 rec.max_level_add == rec.min_level_add &&
4040 rec.max_level_multiply == rec.min_level_multiply &&
4041 rec.max_avg_level == 0 && rec.min_avg_level == 0 &&
4042 rec.max_direction == 361 && rec.min_direction == 361 &&
4043 rec.flood_begins == NULLSLACKOFFSET && rec.ebb_begins == NULLSLACKOFFSET)
4044 return (NVTrue);
4045
4046 return (NVFalse);
4047}
4048#endif
4049
4050/*****************************************************************************\
4051
4052 Function header_checksum - compute the checksum for the ASCII
4053 portion of the database header
4054
4055 Synopsis header_checksum ();
4056
4057 Returns NV_U_INT32 checksum value
4058
4059 Author Jan C. Depner
4060 Date 08/01/02
4061
4062 See libtcd.html for changelog.
4063
4064\*****************************************************************************/
4065
4066static NV_U_INT32 header_checksum() {
4067 NV_U_INT32 checksum, i, save_pos;
4068 NV_U_BYTE *buf;
4069 NV_U_INT32 crc_table[256] = {
4070 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F,
4071 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
4072 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2,
4073 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
4074 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
4075 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
4076 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C,
4077 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
4078 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423,
4079 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
4080 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106,
4081 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
4082 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D,
4083 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
4084 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,
4085 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
4086 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7,
4087 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
4088 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA,
4089 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
4090 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81,
4091 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
4092 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84,
4093 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
4094 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
4095 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
4096 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E,
4097 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
4098 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55,
4099 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
4100 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28,
4101 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
4102 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F,
4103 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
4104 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
4105 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
4106 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69,
4107 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
4108 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC,
4109 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
4110 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693,
4111 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
4112 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D};
4113
4114 if (!fp) {
4115 LOG_ERROR(
4116 "libtcd error: attempt to access database when database not open\n");
4117 exit(-1);
4118 }
4119
4120 save_pos = ftell(fp);
4121
4122 fseek(fp, 0, SEEK_SET);
4123
4124 if ((buf = (NV_U_BYTE *)calloc(hd.header_size, sizeof(NV_U_BYTE))) == NULL) {
4125 perror("Allocating checksum buffer");
4126 exit(-1);
4127 }
4128
4129 checksum = ~0;
4130
4131 assert(hd.header_size > 0);
4132 chk_fread(buf, hd.header_size, 1, fp);
4133 for (i = 0; i < (NV_U_INT32)hd.header_size; ++i) {
4134 checksum = crc_table[(checksum ^ buf[i]) & 0xff] ^ (checksum >> 8);
4135 }
4136 checksum ^= ~0;
4137
4138 free(buf);
4139
4140 fseek(fp, save_pos, SEEK_SET);
4141
4142 return (checksum);
4143}
4144
4145/*****************************************************************************\
4146
4147 Function old_header_checksum - compute the old-style checksum for
4148 the ASCII portion of the database header just in case this
4149 is a pre 1.02 file.
4150
4151 Synopsis old_header_checksum ();
4152
4153 Returns NV_U_INT32 checksum value
4154
4155 Author Jan C. Depner
4156 Date 11/15/02
4157
4158\*****************************************************************************/
4159
4160#ifdef COMPAT114
4161static NV_U_INT32 old_header_checksum() {
4162 NV_U_INT32 checksum, i, save_pos;
4163 NV_U_BYTE *buf;
4164
4165 if (!fp) {
4166 LOG_ERROR(
4167 "libtcd error: attempt to access database when database not open\n");
4168 exit(-1);
4169 }
4170
4171 save_pos = ftell(fp);
4172
4173 checksum = 0;
4174
4175 fseek(fp, 0, SEEK_SET);
4176
4177 if ((buf = (NV_U_BYTE *)calloc(hd.header_size, sizeof(NV_U_BYTE))) == NULL) {
4178 perror("Allocating checksum buffer");
4179 exit(-1);
4180 }
4181
4182 chk_fread(buf, hd.header_size, 1, fp);
4183
4184 for (i = 0; i < hd.header_size; ++i) checksum += buf[i];
4185
4186 free(buf);
4187
4188 fseek(fp, save_pos, SEEK_SET);
4189
4190 return (checksum);
4191}
4192#endif
4193
4194/*****************************************************************************\
4195 DWF 2004-10-01
4196 Get current time in preferred format.
4197\*****************************************************************************/
4198static NV_CHAR *curtime() {
4199 static NV_CHAR buf[ONELINER_LENGTH];
4200 time_t t = time(NULL);
4201 require(strftime(buf, ONELINER_LENGTH, "%Y-%m-%d %H:%M %Z", localtime(&t)) >
4202 0);
4203 return buf;
4204}
4205
4206/*****************************************************************************\
4207 DWF 2004-10-15
4208 Calculate bytes for number of bits.
4209\*****************************************************************************/
4210static NV_U_INT32 bits2bytes(NV_U_INT32 nbits) {
4211 if (nbits % 8) return nbits / 8 + 1;
4212 return nbits / 8;
4213}
4214
4215/*****************************************************************************\
4216
4217 Function write_tide_db_header - writes the database header to the
4218 file
4219
4220 Synopsis write_tide_db_header ();
4221
4222 Returns void
4223
4224 Author Jan C. Depner
4225 Date 08/01/02
4226
4227 See libtcd.html for changelog.
4228
4229\*****************************************************************************/
4230
4231static void write_tide_db_header() {
4232 NV_U_INT32 i, size, pos;
4233 NV_INT32 start, temp_int;
4234 static NV_CHAR zero = 0;
4235 NV_U_BYTE *buf, checksum_c[4];
4236
4237 if (!fp) {
4238 LOG_ERROR(
4239 "libtcd error: attempt to access database when database not open\n");
4240 exit(-1);
4241 }
4242 write_protect();
4243
4244 fseek(fp, 0, SEEK_SET);
4245
4246 fprintf(fp, "[VERSION] = %s\n", LIBTCD_VERSION);
4247 fprintf(fp, "[MAJOR REV] = %u\n", LIBTCD_MAJOR_REV);
4248 fprintf(fp, "[MINOR REV] = %u\n", LIBTCD_MINOR_REV);
4249
4250 fprintf(fp, "[LAST MODIFIED] = %s\n", curtime());
4251
4252 fprintf(fp, "[HEADER SIZE] = %u\n", hd.header_size);
4253 fprintf(fp, "[NUMBER OF RECORDS] = %u\n", hd.pub.number_of_records);
4254
4255 fprintf(fp, "[START YEAR] = %d\n", hd.pub.start_year);
4256 fprintf(fp, "[NUMBER OF YEARS] = %u\n", hd.pub.number_of_years);
4257
4258 fprintf(fp, "[SPEED BITS] = %u\n", hd.speed_bits);
4259 fprintf(fp, "[SPEED SCALE] = %u\n", hd.speed_scale);
4260 fprintf(fp, "[SPEED OFFSET] = %d\n", hd.speed_offset);
4261 fprintf(fp, "[EQUILIBRIUM BITS] = %u\n", hd.equilibrium_bits);
4262 fprintf(fp, "[EQUILIBRIUM SCALE] = %u\n", hd.equilibrium_scale);
4263 fprintf(fp, "[EQUILIBRIUM OFFSET] = %d\n", hd.equilibrium_offset);
4264 fprintf(fp, "[NODE BITS] = %u\n", hd.node_bits);
4265 fprintf(fp, "[NODE SCALE] = %u\n", hd.node_scale);
4266 fprintf(fp, "[NODE OFFSET] = %d\n", hd.node_offset);
4267 fprintf(fp, "[AMPLITUDE BITS] = %u\n", hd.amplitude_bits);
4268 fprintf(fp, "[AMPLITUDE SCALE] = %u\n", hd.amplitude_scale);
4269 fprintf(fp, "[EPOCH BITS] = %u\n", hd.epoch_bits);
4270 fprintf(fp, "[EPOCH SCALE] = %u\n", hd.epoch_scale);
4271
4272 fprintf(fp, "[RECORD TYPE BITS] = %u\n", hd.record_type_bits);
4273 fprintf(fp, "[LATITUDE BITS] = %u\n", hd.latitude_bits);
4274 fprintf(fp, "[LATITUDE SCALE] = %u\n", hd.latitude_scale);
4275 fprintf(fp, "[LONGITUDE BITS] = %u\n", hd.longitude_bits);
4276 fprintf(fp, "[LONGITUDE SCALE] = %u\n", hd.longitude_scale);
4277 fprintf(fp, "[RECORD SIZE BITS] = %u\n", hd.record_size_bits);
4278
4279 fprintf(fp, "[STATION BITS] = %u\n", hd.station_bits);
4280
4281 fprintf(fp, "[DATUM OFFSET BITS] = %u\n", hd.datum_offset_bits);
4282 fprintf(fp, "[DATUM OFFSET SCALE] = %u\n", hd.datum_offset_scale);
4283 fprintf(fp, "[DATE BITS] = %u\n", hd.date_bits);
4284 fprintf(fp, "[MONTHS ON STATION BITS] = %u\n", hd.months_on_station_bits);
4285 fprintf(fp, "[CONFIDENCE VALUE BITS] = %u\n", hd.confidence_value_bits);
4286
4287 fprintf(fp, "[TIME BITS] = %u\n", hd.time_bits);
4288 fprintf(fp, "[LEVEL ADD BITS] = %u\n", hd.level_add_bits);
4289 fprintf(fp, "[LEVEL ADD SCALE] = %u\n", hd.level_add_scale);
4290 fprintf(fp, "[LEVEL MULTIPLY BITS] = %u\n", hd.level_multiply_bits);
4291 fprintf(fp, "[LEVEL MULTIPLY SCALE] = %u\n", hd.level_multiply_scale);
4292 fprintf(fp, "[DIRECTION BITS] = %u\n", hd.direction_bits);
4293
4294 fprintf(fp, "[LEVEL UNIT BITS] = %u\n", hd.level_unit_bits);
4295 fprintf(fp, "[LEVEL UNIT TYPES] = %u\n", hd.pub.level_unit_types);
4296 fprintf(fp, "[LEVEL UNIT SIZE] = %u\n", hd.level_unit_size);
4297
4298 fprintf(fp, "[DIRECTION UNIT BITS] = %u\n", hd.dir_unit_bits);
4299 fprintf(fp, "[DIRECTION UNIT TYPES] = %u\n", hd.pub.dir_unit_types);
4300 fprintf(fp, "[DIRECTION UNIT SIZE] = %u\n", hd.dir_unit_size);
4301
4302 fprintf(fp, "[RESTRICTION BITS] = %u\n", hd.restriction_bits);
4303 fprintf(fp, "[RESTRICTION TYPES] = %u\n", hd.pub.restriction_types);
4304 fprintf(fp, "[RESTRICTION SIZE] = %u\n", hd.restriction_size);
4305
4306 fprintf(fp, "[DATUM BITS] = %u\n", hd.datum_bits);
4307 fprintf(fp, "[DATUM TYPES] = %u\n", hd.pub.datum_types);
4308 fprintf(fp, "[DATUM SIZE] = %u\n", hd.datum_size);
4309
4310 fprintf(fp, "[LEGALESE BITS] = %u\n", hd.legalese_bits);
4311 fprintf(fp, "[LEGALESE TYPES] = %u\n", hd.pub.legaleses);
4312 fprintf(fp, "[LEGALESE SIZE] = %u\n", hd.legalese_size);
4313
4314 fprintf(fp, "[CONSTITUENT BITS] = %u\n", hd.constituent_bits);
4315 fprintf(fp, "[CONSTITUENTS] = %u\n", hd.pub.constituents);
4316 fprintf(fp, "[CONSTITUENT SIZE] = %u\n", hd.constituent_size);
4317
4318 fprintf(fp, "[TZFILE BITS] = %u\n", hd.tzfile_bits);
4319 fprintf(fp, "[TZFILES] = %u\n", hd.pub.tzfiles);
4320 fprintf(fp, "[TZFILE SIZE] = %u\n", hd.tzfile_size);
4321
4322 fprintf(fp, "[COUNTRY BITS] = %u\n", hd.country_bits);
4323 fprintf(fp, "[COUNTRIES] = %u\n", hd.pub.countries);
4324 fprintf(fp, "[COUNTRY SIZE] = %u\n", hd.country_size);
4325
4326 fprintf(fp, "[END OF FILE] = %u\n", hd.end_of_file);
4327 fprintf(fp, "[END OF ASCII HEADER DATA]\n");
4328
4329 /* Fill the remainder of the [HEADER SIZE] ASCII header with zeroes. */
4330
4331 start = ftell(fp);
4332 assert(start >= 0);
4333 for (i = start; i < hd.header_size; ++i) chk_fwrite(&zero, 1, 1, fp);
4334 fflush(fp);
4335
4336 /* Compute and save the checksum. */
4337
4338 bit_pack(checksum_c, 0, 32, header_checksum());
4339 chk_fwrite(checksum_c, 4, 1, fp);
4340
4341 /* NOTE : Using strcpy for character strings (no endian issue). */
4342
4343 /* Write level units. */
4344
4345 pos = 0;
4346 size = hd.pub.level_unit_types * hd.level_unit_size;
4347
4348 if ((buf = (NV_U_BYTE *)calloc(size, sizeof(NV_U_BYTE))) == NULL) {
4349 perror("Allocating unit write buffer");
4350 exit(-1);
4351 }
4352 memset(buf, 0, size);
4353
4354 for (i = 0; i < hd.pub.level_unit_types; ++i) {
4355 assert(strlen(hd.level_unit[i]) + 1 <= hd.level_unit_size);
4356 strcpy((NV_CHAR *)&buf[pos], hd.level_unit[i]);
4357 pos += hd.level_unit_size;
4358 }
4359
4360 chk_fwrite(buf, pos, 1, fp);
4361 free(buf);
4362
4363 /* Write direction units. */
4364
4365 pos = 0;
4366 size = hd.pub.dir_unit_types * hd.dir_unit_size;
4367
4368 if ((buf = (NV_U_BYTE *)calloc(size, sizeof(NV_U_BYTE))) == NULL) {
4369 perror("Allocating unit write buffer");
4370 exit(-1);
4371 }
4372 memset(buf, 0, size);
4373
4374 for (i = 0; i < hd.pub.dir_unit_types; ++i) {
4375 assert(strlen(hd.dir_unit[i]) + 1 <= hd.dir_unit_size);
4376 strcpy((NV_CHAR *)&buf[pos], hd.dir_unit[i]);
4377 pos += hd.dir_unit_size;
4378 }
4379
4380 chk_fwrite(buf, pos, 1, fp);
4381 free(buf);
4382
4383 /* Write restrictions. */
4384
4385 pos = 0;
4386 size = hd.max_restriction_types * hd.restriction_size;
4387
4388 if ((buf = (NV_U_BYTE *)calloc(size, sizeof(NV_U_BYTE))) == NULL) {
4389 perror("Allocating restriction write buffer");
4390 exit(-1);
4391 }
4392 memset(buf, 0, size);
4393
4394 for (i = 0; i < hd.max_restriction_types; ++i) {
4395 if (i == hd.pub.restriction_types) break;
4396 assert(strlen(hd.restriction[i]) + 1 <= hd.restriction_size);
4397 strcpy((NV_CHAR *)&buf[pos], hd.restriction[i]);
4398 pos += hd.restriction_size;
4399 }
4400 memcpy(&buf[pos], "__END__", 7);
4401
4402 chk_fwrite(buf, size, 1, fp);
4403 free(buf);
4404
4405 /* Write tzfiles. */
4406
4407 pos = 0;
4408 size = hd.max_tzfiles * hd.tzfile_size;
4409
4410 if ((buf = (NV_U_BYTE *)calloc(size, sizeof(NV_U_BYTE))) == NULL) {
4411 perror("Allocating tzfile write buffer");
4412 exit(-1);
4413 }
4414 memset(buf, 0, size);
4415
4416 for (i = 0; i < hd.max_tzfiles; ++i) {
4417 if (i == hd.pub.tzfiles) break;
4418 assert(strlen(hd.tzfile[i]) + 1 <= hd.tzfile_size);
4419 strcpy((NV_CHAR *)&buf[pos], hd.tzfile[i]);
4420 pos += hd.tzfile_size;
4421 }
4422 memcpy(&buf[pos], "__END__", 7);
4423
4424 chk_fwrite(buf, size, 1, fp);
4425 free(buf);
4426
4427 /* Write countries. */
4428
4429 pos = 0;
4430 size = hd.max_countries * hd.country_size;
4431
4432 if ((buf = (NV_U_BYTE *)calloc(size, sizeof(NV_U_BYTE))) == NULL) {
4433 perror("Allocating country write buffer");
4434 exit(-1);
4435 }
4436 memset(buf, 0, size);
4437
4438 for (i = 0; i < hd.max_countries; ++i) {
4439 if (i == hd.pub.countries) break;
4440 assert(strlen(hd.country[i]) + 1 <= hd.country_size);
4441 strcpy((NV_CHAR *)&buf[pos], hd.country[i]);
4442 pos += hd.country_size;
4443 }
4444 memcpy(&buf[pos], "__END__", 7);
4445
4446 chk_fwrite(buf, size, 1, fp);
4447 free(buf);
4448
4449 /* Write datums. */
4450
4451 pos = 0;
4452 size = hd.max_datum_types * hd.datum_size;
4453
4454 if ((buf = (NV_U_BYTE *)calloc(size, sizeof(NV_U_BYTE))) == NULL) {
4455 perror("Allocating datum write buffer");
4456 exit(-1);
4457 }
4458 memset(buf, 0, size);
4459
4460 for (i = 0; i < hd.max_datum_types; ++i) {
4461 if (i == hd.pub.datum_types) break;
4462 assert(strlen(hd.datum[i]) + 1 <= hd.datum_size);
4463 strcpy((NV_CHAR *)&buf[pos], hd.datum[i]);
4464 pos += hd.datum_size;
4465 }
4466 memcpy(&buf[pos], "__END__", 7);
4467
4468 chk_fwrite(buf, size, 1, fp);
4469 free(buf);
4470
4471 /* Write legaleses. */
4472
4473 pos = 0;
4474 size = hd.max_legaleses * hd.legalese_size;
4475
4476 if ((buf = (NV_U_BYTE *)calloc(size, sizeof(NV_U_BYTE))) == NULL) {
4477 perror("Allocating legalese write buffer");
4478 exit(-1);
4479 }
4480 memset(buf, 0, size);
4481
4482 for (i = 0; i < hd.max_legaleses; ++i) {
4483 if (i == hd.pub.legaleses) break;
4484 assert(strlen(hd.legalese[i]) + 1 <= hd.legalese_size);
4485 strcpy((NV_CHAR *)&buf[pos], hd.legalese[i]);
4486 pos += hd.legalese_size;
4487 }
4488 memcpy(&buf[pos], "__END__", 7);
4489
4490 chk_fwrite(buf, size, 1, fp);
4491 free(buf);
4492
4493 /* Write constituent names. */
4494
4495 pos = 0;
4496 size = hd.pub.constituents * hd.constituent_size;
4497
4498 if ((buf = (NV_U_BYTE *)calloc(size, sizeof(NV_U_BYTE))) == NULL) {
4499 perror("Allocating constituent write buffer");
4500 exit(-1);
4501 }
4502 memset(buf, 0, size);
4503
4504 for (i = 0; i < hd.pub.constituents; ++i) {
4505 assert(strlen(hd.constituent[i]) + 1 <= hd.constituent_size);
4506 strcpy((NV_CHAR *)&buf[pos], hd.constituent[i]);
4507 pos += hd.constituent_size;
4508 }
4509
4510 chk_fwrite(buf, pos, 1, fp);
4511 free(buf);
4512
4513 /* NOTE : Using bit_pack for integers. */
4514
4515 /* Write speeds. */
4516
4517 pos = 0;
4518 size = bits2bytes(hd.pub.constituents * hd.speed_bits);
4519
4520 if ((buf = (NV_U_BYTE *)calloc(size, sizeof(NV_U_BYTE))) == NULL) {
4521 perror("Allocating speed write buffer");
4522 exit(-1);
4523 }
4524 memset(buf, 0, size);
4525
4526 for (i = 0; i < hd.pub.constituents; ++i) {
4527 temp_int = NINT(hd.speed[i] * hd.speed_scale) - hd.speed_offset;
4528 assert(temp_int >= 0);
4529 bit_pack(buf, pos, hd.speed_bits, temp_int);
4530 pos += hd.speed_bits;
4531 }
4532
4533 chk_fwrite(buf, size, 1, fp);
4534 free(buf);
4535
4536 /* Write equilibrium arguments. */
4537
4538 pos = 0;
4539 size = bits2bytes(hd.pub.constituents * hd.pub.number_of_years *
4540 hd.equilibrium_bits);
4541
4542 if ((buf = (NV_U_BYTE *)calloc(size, sizeof(NV_U_BYTE))) == NULL) {
4543 perror("Allocating equilibrium write buffer");
4544 exit(-1);
4545 }
4546 memset(buf, 0, size);
4547
4548 for (i = 0; i < hd.pub.constituents; ++i) {
4549 NV_U_INT32 j;
4550 for (j = 0; j < hd.pub.number_of_years; ++j) {
4551 temp_int = NINT(hd.equilibrium[i][j] * hd.equilibrium_scale) -
4552 hd.equilibrium_offset;
4553 assert(temp_int >= 0);
4554 bit_pack(buf, pos, hd.equilibrium_bits, temp_int);
4555 pos += hd.equilibrium_bits;
4556 }
4557 }
4558
4559 chk_fwrite(buf, size, 1, fp);
4560 free(buf);
4561
4562 /* Write node factors. */
4563
4564 pos = 0;
4565 size =
4566 bits2bytes(hd.pub.constituents * hd.pub.number_of_years * hd.node_bits);
4567
4568 if ((buf = (NV_U_BYTE *)calloc(size, sizeof(NV_U_BYTE))) == NULL) {
4569 perror("Allocating node write buffer");
4570 exit(-1);
4571 }
4572 memset(buf, 0, size);
4573
4574 for (i = 0; i < hd.pub.constituents; ++i) {
4575 NV_U_INT32 j;
4576 for (j = 0; j < hd.pub.number_of_years; ++j) {
4577 temp_int = NINT(hd.node_factor[i][j] * hd.node_scale) - hd.node_offset;
4578 assert(temp_int >= 0);
4579 bit_pack(buf, pos, hd.node_bits, temp_int);
4580 pos += hd.node_bits;
4581 }
4582 }
4583
4584 chk_fwrite(buf, size, 1, fp);
4585 free(buf);
4586}
4587
4588/*****************************************************************************\
4589
4590 Function unpack_string - Safely unpack a string into a
4591 fixed-length buffer.
4592
4593 Synopsis unpack_string (buf, bufsize, pos, outbuf, outbuflen, desc);
4594
4595 NV_U_BYTE *buf input buffer
4596 NV_U_INT32 bufsize size of input buffer in bytes
4597 NV_U_INT32 *pos current bit-position in buf
4598 (in-out parameter)
4599 NV_CHAR *outbuf fixed-length string-buffer
4600 NV_U_INT32 outbuflen size of outbuf in bytes
4601 NV_CHAR *desc description of the field being
4602 unpacked for use in warning
4603 messages when truncation occurs
4604
4605 Returns void
4606
4607 Author David Flater
4608 Date 2004-09-30
4609
4610 pos will be left at the start of the next field even if the string
4611 gets truncated.
4612
4613\*****************************************************************************/
4614
4615static void unpack_string(NV_U_BYTE *buf, NV_U_INT32 bufsize, NV_U_INT32 *pos,
4616 NV_CHAR *outbuf, NV_U_INT32 outbuflen,
4617 const NV_CHAR *desc) {
4618 NV_U_INT32 i;
4619 NV_CHAR c = 'x';
4620 assert(buf);
4621 assert(pos);
4622 assert(outbuf);
4623 assert(desc);
4624 assert(outbuflen);
4625 --outbuflen;
4626 bufsize <<= 3;
4627 for (i = 0; c; ++i) {
4628 assert(*pos < bufsize); /* Catch unterminated strings */
4629 c = bit_unpack(buf, *pos, 8);
4630 (*pos) += 8;
4631 if (i < outbuflen) {
4632 outbuf[i] = c;
4633 } else if (i == outbuflen) {
4634 outbuf[i] = '\0';
4635 if (c) {
4636 LOG_ERROR("libtcd warning: truncating overlong %s\n", desc);
4637 LOG_ERROR("The offending string starts with:\n%s\n", outbuf);
4638 }
4639 }
4640 }
4641}
4642
4643/*****************************************************************************\
4644
4645 Function unpack_partial_tide_record - unpacks the "header" portion
4646 of a tide record from the supplied buffer
4647
4648 Synopsis unpack_partial_tide_record (buf, rec, pos);
4649
4650 NV_U_BYTE *buf input buffer
4651 NV_U_INT32 bufsize size of input buffer in bytes
4652 TIDE_RECORD *rec tide record
4653 NV_U_INT32 *pos final position in buffer after
4654 unpacking the header
4655
4656 Returns void
4657
4658 Author Jan C. Depner
4659 Date 08/01/02
4660
4661 See libtcd.html for changelog.
4662
4663\*****************************************************************************/
4664
4665static void unpack_partial_tide_record(NV_U_BYTE *buf, NV_U_INT32 bufsize,
4666 TIDE_RECORD *rec, NV_U_INT32 *pos) {
4667 NV_INT32 temp_int;
4668
4669 assert(buf);
4670 assert(rec);
4671 assert(pos);
4672
4673 *pos = 0;
4674
4675 rec->header.record_size = bit_unpack(buf, *pos, hd.record_size_bits);
4676 *pos += hd.record_size_bits;
4677
4678 rec->header.record_type = bit_unpack(buf, *pos, hd.record_type_bits);
4679 *pos += hd.record_type_bits;
4680
4681 temp_int = signed_bit_unpack(buf, *pos, hd.latitude_bits);
4682 rec->header.latitude = (NV_FLOAT64)temp_int / hd.latitude_scale;
4683 *pos += hd.latitude_bits;
4684
4685 temp_int = signed_bit_unpack(buf, *pos, hd.longitude_bits);
4686 rec->header.longitude = (NV_FLOAT64)temp_int / hd.longitude_scale;
4687 *pos += hd.longitude_bits;
4688
4689 /* This ordering doesn't match everywhere else but there's no technical
4690 reason to change it from its V1 ordering. */
4691
4692 rec->header.tzfile = bit_unpack(buf, *pos, hd.tzfile_bits);
4693 *pos += hd.tzfile_bits;
4694
4695 unpack_string(buf, bufsize, pos, rec->header.name, ONELINER_LENGTH,
4696 "station name");
4697
4698 rec->header.reference_station = signed_bit_unpack(buf, *pos, hd.station_bits);
4699 *pos += hd.station_bits;
4700
4701 assert(*pos <= bufsize * 8);
4702}
4703
4704/*****************************************************************************\
4705
4706 Function read_partial_tide_record - reads the "header" portion
4707 of a tide record from the database. This is used to index
4708 the database on opening.
4709
4710 Synopsis read_partial_tide_record (num, rec);
4711
4712 NV_INT32 num record number
4713 TIDE_RECORD *rec tide record
4714
4715 Returns NV_INT32 record number read
4716
4717 Author Jan C. Depner
4718 Date 08/01/02
4719
4720 See libtcd.html for changelog.
4721
4722\*****************************************************************************/
4723
4724static NV_INT32 read_partial_tide_record(NV_INT32 num, TIDE_RECORD *rec) {
4725 NV_U_BYTE *buf;
4726 NV_U_INT32 maximum_possible_size, pos;
4727
4728 if (!fp) {
4729 LOG_ERROR(
4730 "libtcd error: attempt to access database when database not open\n");
4731 exit(-1);
4732 }
4733
4734 assert(rec);
4735
4736 /* Read just the record size, record type, position, time zone, and
4737 name. */
4738
4739 maximum_possible_size = hd.record_size_bits + hd.record_type_bits +
4740 hd.latitude_bits + hd.longitude_bits +
4741 hd.tzfile_bits + (ONELINER_LENGTH * 8) +
4742 hd.station_bits;
4743 maximum_possible_size = bits2bytes(maximum_possible_size);
4744
4745 if ((buf = (NV_U_BYTE *)calloc(maximum_possible_size, sizeof(NV_U_BYTE))) ==
4746 NULL) {
4747 perror("Allocating partial tide record buffer");
4748 exit(-1);
4749 }
4750
4751 current_record = num;
4752 fseek(fp, tindex[num].address, SEEK_SET);
4753 /* DWF 2007-12-02: This is the one place where a short read would not
4754 necessarily mean catastrophe. We don't know how long the partial
4755 record actually is yet, and it's possible that the full record will
4756 be shorter than maximum_possible_size. */
4757 size_t size = fread(buf, 1, maximum_possible_size, fp);
4758 unpack_partial_tide_record(buf, size, rec, &pos);
4759 free(buf);
4760 return (num);
4761}
4762
4763/*****************************************************************************\
4764
4765 Function read_tide_db_header - reads the tide database header
4766
4767 Synopsis read_tide_db_header ();
4768
4769 Returns NV_BOOL NVTrue if header is correct
4770
4771 Author Jan C. Depner
4772 Date 08/01/02
4773
4774 See libtcd.html for changelog.
4775
4776\*****************************************************************************/
4777
4778static NV_BOOL read_tide_db_header() {
4779 NV_INT32 temp_int;
4780 NV_CHAR varin[ONELINER_LENGTH], *info;
4781 NV_U_INT32 utemp, i, j, pos, size, key_count;
4782 NV_U_BYTE *buf, checksum_c[5];
4783 TIDE_RECORD rec;
4784
4785 if (!fp) {
4786 LOG_ERROR(
4787 "libtcd error: attempt to access database when database not open\n");
4788 exit(-1);
4789 }
4790
4791 strcpy(hd.pub.version, "NO VERSION");
4792
4793 /* Compute the number of key phrases there are to match. */
4794 key_count = sizeof(keys) / sizeof(KEY);
4795
4796 /* Zero out the header structure. */
4797 memset(&hd, 0, sizeof(hd));
4798
4799 /* Handle the ASCII header data. */
4800 while (fgets(varin, sizeof(varin), fp) != NULL) {
4801 if (strlen(varin) == ONELINER_LENGTH - 1) {
4802 if (varin[ONELINER_LENGTH - 2] != '\n') {
4803 LOG_ERROR("libtcd error: header line too long, begins with:\n");
4804 LOG_ERROR("%s\n", varin);
4805 LOG_ERROR("in file %s\n", filename);
4806 LOG_ERROR("Configured limit is %u\n", ONELINER_LENGTH - 1);
4807 fclose(fp);
4808 return NVFalse;
4809 }
4810 }
4811
4812 if (strstr(varin, "[END OF ASCII HEADER DATA]")) break;
4813
4814 /* All other lines must be field = value */
4815 info = strchr(varin, '=');
4816 if (!info) {
4817 LOG_ERROR("libtcd error: invalid tide db header line:\n");
4818 LOG_ERROR("%s", varin);
4819 LOG_ERROR("in file %s\n", filename);
4820 fclose(fp);
4821 return NVFalse;
4822 }
4823 ++info;
4824
4825 /* Scan the fields per "keys" defined in tide_db_header.h. */
4826 for (i = 0; i < key_count; ++i) {
4827 if (strstr(varin, keys[i].keyphrase)) {
4828 if (!strcmp(keys[i].datatype, "cstr"))
4829 strcpy((char *)keys[i].address.cstr, clip_string(info));
4830 else if (!strcmp(keys[i].datatype, "i32")) {
4831 if (sscanf(info, "%d", keys[i].address.i32) != 1) {
4832 LOG_ERROR("libtcd error: invalid tide db header line:\n");
4833 LOG_ERROR("%s", varin);
4834 LOG_ERROR("in file %s\n", filename);
4835 fclose(fp);
4836 return NVFalse;
4837 }
4838 } else if (!strcmp(keys[i].datatype, "ui32")) {
4839 if (sscanf(info, "%u", keys[i].address.ui32) != 1) {
4840 LOG_ERROR("libtcd error: invalid tide db header line:\n");
4841 LOG_ERROR("%s", varin);
4842 LOG_ERROR("in file %s\n", filename);
4843 fclose(fp);
4844 return NVFalse;
4845 }
4846 } else
4847 assert(0);
4848 }
4849 }
4850 }
4851
4852 /* We didn't get a valid version string. */
4853
4854 if (!strcmp(hd.pub.version, "NO VERSION")) {
4855 LOG_ERROR("libtcd error: no version found in tide db header\n");
4856 LOG_ERROR("in file %s\n", filename);
4857 fclose(fp);
4858 return NVFalse;
4859 }
4860
4861 /* If no major or minor rev, they're 0 (pre-1.99) */
4862 if (hd.pub.major_rev > LIBTCD_MAJOR_REV) {
4863 LOG_ERROR(
4864 "libtcd error: major revision in TCD file (%u) exceeds major revision "
4865 "of\n",
4866 hd.pub.major_rev);
4867 LOG_ERROR("libtcd (%u). You must upgrade libtcd to read this file.\n",
4868 LIBTCD_MAJOR_REV);
4869 fclose(fp);
4870 return NVFalse;
4871 }
4872
4873 /* Move to end of ASCII header. */
4874 fseek(fp, hd.header_size, SEEK_SET);
4875
4876 /* Read and check the checksum. */
4877
4878 chk_fread(checksum_c, 4, 1, fp);
4879 utemp = bit_unpack(checksum_c, 0, 32);
4880
4881 if (utemp != header_checksum()) {
4882#ifdef COMPAT114
4883 if (utemp != old_header_checksum()) {
4884 LOG_ERROR("libtcd error: header checksum error in file %s\n", filename);
4885 LOG_ERROR(
4886 "Someone may have modified the ASCII portion of the header (don't do that),\n\
4887or it may just be corrupt.\n");
4888 fclose(fp);
4889 return NVFalse;
4890 }
4891#else
4892 LOG_ERROR("libtcd error: header checksum error in file %s\n", filename);
4893 LOG_ERROR(
4894 "Someone may have modified the ASCII portion of the header (don't do that),\n\
4895or it may be an ancient pre-version-1.02 TCD file, or it may just be corrupt.\n\
4896Pre-version-1.02 TCD files can be read by building libtcd with COMPAT114\n\
4897defined.\n");
4898 fclose(fp);
4899 return NVFalse;
4900#endif
4901 }
4902 fseek(fp, hd.header_size + 4, SEEK_SET);
4903
4904 /* Set the max possible restriction types based on the number of bits
4905 used. */
4906
4907 hd.max_restriction_types = NINT(pow(2.0, (NV_FLOAT64)hd.restriction_bits));
4908
4909 /* Set the max possible tzfiles based on the number of bits used. */
4910
4911 hd.max_tzfiles = NINT(pow(2.0, (NV_FLOAT64)hd.tzfile_bits));
4912
4913 /* Set the max possible countries based on the number of bits used. */
4914
4915 hd.max_countries = NINT(pow(2.0, (NV_FLOAT64)hd.country_bits));
4916
4917 /* Set the max possible datum types based on the number of bits
4918 used. */
4919
4920 hd.max_datum_types = NINT(pow(2.0, (NV_FLOAT64)hd.datum_bits));
4921
4922 /* Set the max possible legaleses based on the number of bits
4923 used. */
4924
4925 if (hd.pub.major_rev < 2)
4926 hd.max_legaleses = 1;
4927 else
4928 hd.max_legaleses = NINT(pow(2.0, (NV_FLOAT64)hd.legalese_bits));
4929
4930 /* NOTE : Using strcpy for character strings (no endian issue). */
4931
4932 /* Read level units. */
4933
4934 hd.level_unit =
4935 (NV_CHAR **)calloc(hd.pub.level_unit_types, sizeof(NV_CHAR *));
4936
4937 if ((buf = (NV_U_BYTE *)calloc(hd.level_unit_size, sizeof(NV_U_BYTE))) ==
4938 NULL) {
4939 perror("Allocating level unit read buffer");
4940 exit(-1);
4941 }
4942
4943 for (i = 0; i < hd.pub.level_unit_types; ++i) {
4944 chk_fread(buf, hd.level_unit_size, 1, fp);
4945 hd.level_unit[i] =
4946 (NV_CHAR *)calloc(strlen((char *)buf) + 1, sizeof(NV_CHAR));
4947 strcpy(hd.level_unit[i], (NV_CHAR *)buf);
4948 }
4949 free(buf);
4950
4951 /* Read direction units. */
4952
4953 hd.dir_unit = (NV_CHAR **)calloc(hd.pub.dir_unit_types, sizeof(NV_CHAR *));
4954
4955 if ((buf = (NV_U_BYTE *)calloc(hd.dir_unit_size, sizeof(NV_U_BYTE))) ==
4956 NULL) {
4957 perror("Allocating dir unit read buffer");
4958 exit(-1);
4959 }
4960
4961 for (i = 0; i < hd.pub.dir_unit_types; ++i) {
4962 chk_fread(buf, hd.dir_unit_size, 1, fp);
4963 hd.dir_unit[i] =
4964 (NV_CHAR *)calloc(strlen((char *)buf) + 1, sizeof(NV_CHAR));
4965 strcpy(hd.dir_unit[i], (NV_CHAR *)buf);
4966 }
4967 free(buf);
4968
4969 /* Read restrictions. */
4970
4971 utemp = ftell(fp);
4972 hd.restriction =
4973 (NV_CHAR **)calloc(hd.max_restriction_types, sizeof(NV_CHAR *));
4974
4975 if ((buf = (NV_U_BYTE *)calloc(hd.restriction_size, sizeof(NV_U_BYTE))) ==
4976 NULL) {
4977 perror("Allocating restriction read buffer");
4978 exit(-1);
4979 }
4980
4981 hd.pub.restriction_types = 0;
4982 for (i = 0; i < hd.max_restriction_types; ++i) {
4983 chk_fread(buf, hd.restriction_size, 1, fp);
4984 if (!strcmp((char *)buf, "__END__")) {
4985 hd.pub.restriction_types = i;
4986 break;
4987 }
4988 hd.restriction[i] =
4989 (NV_CHAR *)calloc(strlen((char *)buf) + 1, sizeof(NV_CHAR));
4990 strcpy(hd.restriction[i], (NV_CHAR *)buf);
4991 }
4992 free(buf);
4993 fseek(fp, utemp + hd.max_restriction_types * hd.restriction_size, SEEK_SET);
4994
4995 /* Skip pedigrees. */
4996 if (hd.pub.major_rev < 2)
4997 fseek(fp, hd.pedigree_size * NINT(pow(2.0, (NV_FLOAT64)hd.pedigree_bits)),
4998 SEEK_CUR);
4999 hd.pub.pedigree_types = 1;
5000
5001 /* Read tzfiles. */
5002
5003 utemp = ftell(fp);
5004 hd.tzfile = (NV_CHAR **)calloc(hd.max_tzfiles, sizeof(NV_CHAR *));
5005
5006 if ((buf = (NV_U_BYTE *)calloc(hd.tzfile_size, sizeof(NV_U_BYTE))) == NULL) {
5007 perror("Allocating tzfile read buffer");
5008 exit(-1);
5009 }
5010
5011 hd.pub.tzfiles = 0;
5012 for (i = 0; i < hd.max_tzfiles; ++i) {
5013 chk_fread(buf, hd.tzfile_size, 1, fp);
5014 if (!strcmp((char *)buf, "__END__")) {
5015 hd.pub.tzfiles = i;
5016 break;
5017 }
5018 hd.tzfile[i] = (NV_CHAR *)calloc(strlen((char *)buf) + 1, sizeof(NV_CHAR));
5019 strcpy(hd.tzfile[i], (NV_CHAR *)buf);
5020 }
5021 free(buf);
5022 fseek(fp, utemp + hd.max_tzfiles * hd.tzfile_size, SEEK_SET);
5023
5024 /* Read countries. */
5025
5026 utemp = ftell(fp);
5027 hd.country = (NV_CHAR **)calloc(hd.max_countries, sizeof(NV_CHAR *));
5028
5029 if ((buf = (NV_U_BYTE *)calloc(hd.country_size, sizeof(NV_U_BYTE))) == NULL) {
5030 perror("Allocating country read buffer");
5031 exit(-1);
5032 }
5033
5034 hd.pub.countries = 0;
5035 for (i = 0; i < hd.max_countries; ++i) {
5036 chk_fread(buf, hd.country_size, 1, fp);
5037 if (!strcmp((char *)buf, "__END__")) {
5038 hd.pub.countries = i;
5039 break;
5040 }
5041 hd.country[i] = (NV_CHAR *)calloc(strlen((char *)buf) + 1, sizeof(NV_CHAR));
5042 strcpy(hd.country[i], (NV_CHAR *)buf);
5043 }
5044 free(buf);
5045 fseek(fp, utemp + hd.max_countries * hd.country_size, SEEK_SET);
5046
5047 /* Read datums. */
5048
5049 utemp = ftell(fp);
5050 hd.datum = (NV_CHAR **)calloc(hd.max_datum_types, sizeof(NV_CHAR *));
5051
5052 if ((buf = (NV_U_BYTE *)calloc(hd.datum_size, sizeof(NV_U_BYTE))) == NULL) {
5053 perror("Allocating datum read buffer");
5054 exit(-1);
5055 }
5056
5057 hd.pub.datum_types = 0;
5058 for (i = 0; i < hd.max_datum_types; ++i) {
5059 chk_fread(buf, hd.datum_size, 1, fp);
5060 if (!strcmp((char *)buf, "__END__")) {
5061 hd.pub.datum_types = i;
5062 break;
5063 }
5064 hd.datum[i] = (NV_CHAR *)calloc(strlen((char *)buf) + 1, sizeof(NV_CHAR));
5065 strcpy(hd.datum[i], (NV_CHAR *)buf);
5066 }
5067 free(buf);
5068 fseek(fp, utemp + hd.max_datum_types * hd.datum_size, SEEK_SET);
5069
5070 /* Read legaleses. */
5071
5072 if (hd.pub.major_rev < 2) {
5073 hd.legalese = (NV_CHAR **)malloc(sizeof(NV_CHAR *));
5074 assert(hd.legalese != NULL);
5075 hd.legalese[0] = (NV_CHAR *)malloc(5 * sizeof(NV_CHAR));
5076 assert(hd.legalese[0] != NULL);
5077 strcpy(hd.legalese[0], "NULL");
5078 hd.pub.legaleses = 1;
5079 } else {
5080 utemp = ftell(fp);
5081 hd.legalese = (NV_CHAR **)calloc(hd.max_legaleses, sizeof(NV_CHAR *));
5082
5083 if ((buf = (NV_U_BYTE *)calloc(hd.legalese_size, sizeof(NV_U_BYTE))) ==
5084 NULL) {
5085 perror("Allocating legalese read buffer");
5086 exit(-1);
5087 }
5088
5089 hd.pub.legaleses = 0;
5090 for (i = 0; i < hd.max_legaleses; ++i) {
5091 chk_fread(buf, hd.legalese_size, 1, fp);
5092 if (!strcmp((char *)buf, "__END__")) {
5093 hd.pub.legaleses = i;
5094 break;
5095 }
5096 hd.legalese[i] =
5097 (NV_CHAR *)calloc(strlen((char *)buf) + 1, sizeof(NV_CHAR));
5098 strcpy(hd.legalese[i], (NV_CHAR *)buf);
5099 }
5100 free(buf);
5101 fseek(fp, utemp + hd.max_legaleses * hd.legalese_size, SEEK_SET);
5102 }
5103
5104 /* Read constituent names. */
5105
5106 hd.constituent = (NV_CHAR **)calloc(hd.pub.constituents, sizeof(NV_CHAR *));
5107
5108 if ((buf = (NV_U_BYTE *)calloc(hd.constituent_size, sizeof(NV_U_BYTE))) ==
5109 NULL) {
5110 perror("Allocating constituent read buffer");
5111 exit(-1);
5112 }
5113
5114 for (i = 0; i < hd.pub.constituents; ++i) {
5115 chk_fread(buf, hd.constituent_size, 1, fp);
5116 hd.constituent[i] =
5117 (NV_CHAR *)calloc(strlen((char *)buf) + 1, sizeof(NV_CHAR));
5118 strcpy(hd.constituent[i], (NV_CHAR *)buf);
5119 }
5120 free(buf);
5121
5122 if (hd.speed_offset < 0 || hd.equilibrium_offset < 0 || hd.node_offset < 0) {
5123 LOG_ERROR("libtcd WARNING: File: %s\n", filename);
5124 LOG_ERROR(
5125 "WARNING: This TCD file was created by a pre-version-1.11 libtcd.\n\
5126Versions of libtcd prior to 1.11 contained a serious bug that can result\n\
5127in overflows in the speeds, equilibrium arguments, or node factors. This\n\
5128database should be rebuilt from the original data if possible.\n");
5129 }
5130
5131 /* NOTE: Using bit_unpack to get integers. */
5132
5133 /* Read speeds. */
5134
5135 hd.speed = (NV_FLOAT64 *)calloc(hd.pub.constituents, sizeof(NV_FLOAT64));
5136
5137 pos = 0;
5138 /* wasted byte bug in V1 */
5139 if (hd.pub.major_rev < 2)
5140 size = ((hd.pub.constituents * hd.speed_bits) / 8) + 1;
5141 else
5142 size = bits2bytes(hd.pub.constituents * hd.speed_bits);
5143
5144 if ((buf = (NV_U_BYTE *)calloc(size, sizeof(NV_U_BYTE))) == NULL) {
5145 perror("Allocating speed read buffer");
5146 exit(-1);
5147 }
5148
5149 chk_fread(buf, size, 1, fp);
5150
5151 for (i = 0; i < hd.pub.constituents; ++i) {
5152 temp_int = bit_unpack(buf, pos, hd.speed_bits);
5153 hd.speed[i] = (NV_FLOAT64)(temp_int + hd.speed_offset) / hd.speed_scale;
5154 pos += hd.speed_bits;
5155 assert(hd.speed[i] >= 0.0);
5156 }
5157 free(buf);
5158
5159 /* Read equilibrium arguments. */
5160
5161 hd.equilibrium =
5162 (NV_FLOAT32 **)calloc(hd.pub.constituents, sizeof(NV_FLOAT32 *));
5163
5164 for (i = 0; i < hd.pub.constituents; ++i) {
5165 hd.equilibrium[i] =
5166 (NV_FLOAT32 *)calloc(hd.pub.number_of_years, sizeof(NV_FLOAT32));
5167 }
5168
5169 pos = 0;
5170 /* wasted byte bug in V1 */
5171 if (hd.pub.major_rev < 2)
5172 size =
5173 ((hd.pub.constituents * hd.pub.number_of_years * hd.equilibrium_bits) /
5174 8) +
5175 1;
5176 else
5177 size = bits2bytes(hd.pub.constituents * hd.pub.number_of_years *
5178 hd.equilibrium_bits);
5179
5180 if ((buf = (NV_U_BYTE *)calloc(size, sizeof(NV_U_BYTE))) == NULL) {
5181 perror("Allocating equilibrium read buffer");
5182 exit(-1);
5183 }
5184
5185 chk_fread(buf, size, 1, fp);
5186
5187 for (i = 0; i < hd.pub.constituents; ++i) {
5188 for (j = 0; j < hd.pub.number_of_years; ++j) {
5189 temp_int = bit_unpack(buf, pos, hd.equilibrium_bits);
5190 hd.equilibrium[i][j] =
5191 (NV_FLOAT32)(temp_int + hd.equilibrium_offset) / hd.equilibrium_scale;
5192 pos += hd.equilibrium_bits;
5193 }
5194 }
5195 free(buf);
5196
5197 /* Read node factors. */
5198
5199 hd.node_factor =
5200 (NV_FLOAT32 **)calloc(hd.pub.constituents, sizeof(NV_FLOAT32 *));
5201
5202 for (i = 0; i < hd.pub.constituents; ++i) {
5203 hd.node_factor[i] =
5204 (NV_FLOAT32 *)calloc(hd.pub.number_of_years, sizeof(NV_FLOAT32));
5205 }
5206
5207 pos = 0;
5208 /* wasted byte bug in V1 */
5209 if (hd.pub.major_rev < 2)
5210 size =
5211 ((hd.pub.constituents * hd.pub.number_of_years * hd.node_bits) / 8) + 1;
5212 else
5213 size =
5214 bits2bytes(hd.pub.constituents * hd.pub.number_of_years * hd.node_bits);
5215
5216 if ((buf = (NV_U_BYTE *)calloc(size, sizeof(NV_U_BYTE))) == NULL) {
5217 perror("Allocating node read buffer");
5218 exit(-1);
5219 }
5220
5221 chk_fread(buf, size, 1, fp);
5222
5223 for (i = 0; i < hd.pub.constituents; ++i) {
5224 for (j = 0; j < hd.pub.number_of_years; ++j) {
5225 temp_int = bit_unpack(buf, pos, hd.node_bits);
5226 hd.node_factor[i][j] =
5227 (NV_FLOAT32)(temp_int + hd.node_offset) / hd.node_scale;
5228 pos += hd.node_bits;
5229 assert(hd.node_factor[i][j] > 0.0);
5230 }
5231 }
5232 free(buf);
5233
5234 /* Read the header portion of all of the records in the file and save
5235 the record size, address, and name. */
5236
5237 /* DWF added test for zero 2003-11-16 -- happens on create new db */
5238 if (hd.pub.number_of_records) {
5239 if ((tindex = (TIDE_INDEX *)calloc(hd.pub.number_of_records,
5240 sizeof(TIDE_INDEX))) == NULL) {
5241 perror("Allocating tide index");
5242 exit(-1);
5243 }
5244 /* Set the first address to be immediately after the header */
5245 tindex[0].address = ftell(fp);
5246 } else
5247 tindex = NULL; /* May as well be explicit... */
5248
5249 for (i = 0; i < hd.pub.number_of_records; ++i) {
5250 /* Set the address for the next record so that
5251 read_partial_tide_record will know where to go. */
5252
5253 if (i) tindex[i].address = tindex[i - 1].address + rec.header.record_size;
5254
5255 read_partial_tide_record(i, &rec);
5256
5257 /* Save the header info in the index. */
5258
5259 tindex[i].record_size = rec.header.record_size;
5260 tindex[i].record_type = rec.header.record_type;
5261 tindex[i].reference_station = rec.header.reference_station;
5262 assert(rec.header.tzfile >= 0);
5263 tindex[i].tzfile = rec.header.tzfile;
5264 tindex[i].lat = NINT(rec.header.latitude * hd.latitude_scale);
5265 tindex[i].lon = NINT(rec.header.longitude * hd.longitude_scale);
5266
5267 if ((tindex[i].name = (NV_CHAR *)calloc(strlen(rec.header.name) + 1,
5268 sizeof(NV_CHAR))) == NULL) {
5269 perror("Allocating index name memory");
5270 exit(-1);
5271 }
5272
5273 strcpy(tindex[i].name, rec.header.name);
5274 }
5275
5276 current_record = -1;
5277 current_index = -1;
5278
5279 return (NVTrue);
5280}
5281
5282/*****************************************************************************\
5283
5284 Function open_tide_db - opens the tide database
5285
5286 Synopsis open_tide_db (file);
5287
5288 NV_CHAR *file database file name
5289
5290 Returns NV_BOOL NVTrue if file opened
5291
5292 Author Jan C. Depner
5293 Date 08/01/02
5294
5295 See libtcd.html for changelog.
5296
5297\*****************************************************************************/
5298
5299NV_BOOL open_tide_db(const NV_CHAR *file) {
5300 assert(file);
5301 current_record = -1;
5302 current_index = -1;
5303 if (fp) {
5304 if (!strcmp(file, filename) && !modified)
5305 return NVTrue;
5306 else
5307 close_tide_db();
5308 }
5309 if ((fp = fopen(file, "rb+")) == NULL) {
5310 if ((fp = fopen(file, "rb")) == NULL) return (NVFalse);
5311 }
5312 boundscheck_monologue(file);
5313 strcpy(filename, file);
5314 return (read_tide_db_header());
5315}
5316
5317/*****************************************************************************\
5318
5319 Function close_tide_db - closes the tide database
5320
5321 Synopsis close_tide_db ();
5322
5323 Returns void
5324
5325 Author Jan C. Depner
5326 Date 08/01/02
5327
5328 See libtcd.html for changelog.
5329
5330 If the global modified flag is true, the database header is rewritten
5331 before the database is closed. The modified flag is then cleared.
5332
5333\*****************************************************************************/
5334
5335void close_tide_db() {
5336 NV_U_INT32 i;
5337
5338 if (!fp) {
5339 LOG_ERROR("libtcd warning: close_tide_db called when no database open\n");
5340 return;
5341 }
5342
5343 /* If we've changed something in the file, write the header to reset
5344 the last modified time. */
5345
5346 if (modified) write_tide_db_header();
5347
5348 /* Free all of the temporary memory. */
5349
5350 assert(hd.constituent);
5351 for (i = 0; i < hd.pub.constituents; ++i) {
5352 if (hd.constituent[i] != NULL) free(hd.constituent[i]);
5353 }
5354 free(hd.constituent);
5355 hd.constituent = NULL;
5356
5357 if (hd.speed != NULL) free(hd.speed);
5358
5359 assert(hd.equilibrium);
5360 for (i = 0; i < hd.pub.constituents; ++i) {
5361 if (hd.equilibrium[i] != NULL) free(hd.equilibrium[i]);
5362 }
5363 free(hd.equilibrium);
5364 hd.equilibrium = NULL;
5365
5366 assert(hd.node_factor);
5367 for (i = 0; i < hd.pub.constituents; ++i) {
5368 if (hd.node_factor[i] != NULL) free(hd.node_factor[i]);
5369 }
5370 free(hd.node_factor);
5371 hd.node_factor = NULL;
5372
5373 assert(hd.level_unit);
5374 for (i = 0; i < hd.pub.level_unit_types; ++i) {
5375 if (hd.level_unit[i] != NULL) free(hd.level_unit[i]);
5376 }
5377 free(hd.level_unit);
5378 hd.level_unit = NULL;
5379
5380 assert(hd.dir_unit);
5381 for (i = 0; i < hd.pub.dir_unit_types; ++i) {
5382 if (hd.dir_unit[i] != NULL) free(hd.dir_unit[i]);
5383 }
5384 free(hd.dir_unit);
5385 hd.dir_unit = NULL;
5386
5387 assert(hd.restriction);
5388 for (i = 0; i < hd.max_restriction_types; ++i) {
5389 if (hd.restriction[i] != NULL) free(hd.restriction[i]);
5390 }
5391 free(hd.restriction);
5392 hd.restriction = NULL;
5393
5394 assert(hd.legalese);
5395 for (i = 0; i < hd.max_legaleses; ++i) {
5396 if (hd.legalese[i] != NULL) free(hd.legalese[i]);
5397 }
5398 free(hd.legalese);
5399 hd.legalese = NULL;
5400
5401 assert(hd.tzfile);
5402 for (i = 0; i < hd.max_tzfiles; ++i) {
5403 if (hd.tzfile[i] != NULL) free(hd.tzfile[i]);
5404 }
5405 free(hd.tzfile);
5406 hd.tzfile = NULL;
5407
5408 assert(hd.country);
5409 for (i = 0; i < hd.max_countries; ++i) {
5410 if (hd.country[i] != NULL) free(hd.country[i]);
5411 }
5412 free(hd.country);
5413 hd.country = NULL;
5414
5415 assert(hd.datum);
5416 for (i = 0; i < hd.max_datum_types; ++i) {
5417 if (hd.datum[i] != NULL) free(hd.datum[i]);
5418 }
5419 free(hd.datum);
5420 hd.datum = NULL;
5421
5422 /* tindex will still be null on create_tide_db */
5423 if (tindex) {
5424 for (i = 0; i < hd.pub.number_of_records; ++i) {
5425 if (tindex[i].name) free(tindex[i].name);
5426 }
5427 free(tindex);
5428 tindex = NULL;
5429 }
5430
5431 fclose(fp);
5432 fp = NULL;
5433 modified = NVFalse;
5434
5435 /* Don't nullify the filename; there are places in the code where
5436 open_tide_db (filename) is invoked after close_tide_db(). This
5437 does not break the cache logic in open_tide_db because tindex
5438 is still nullified. */
5439}
5440
5441/*****************************************************************************\
5442
5443 Function create_tide_db - creates the tide database
5444
5445 Synopsis create_tide_db (file, constituents, constituent, speed,
5446 start_year, num_years, equilibrium, node_factor);
5447
5448 NV_CHAR *file database file name
5449 NV_U_INT32 constituents number of constituents
5450 NV_CHAR *constituent[] constituent names
5451 NV_FLOAT64 *speed speed values
5452 NV_INT32 start_year start year
5453 NV_U_INT32 num_years number of years
5454 NV_FLOAT32 *equilibrium[] equilibrium arguments
5455 NV_FLOAT32 *node_factor[] node factors
5456
5457 Returns NV_BOOL NVTrue if file created
5458
5459 Author Jan C. Depner
5460 Date 08/01/02
5461
5462 See libtcd.html for changelog.
5463
5464\*****************************************************************************/
5465
5466NV_BOOL create_tide_db(const NV_CHAR *file, NV_U_INT32 constituents,
5467 NV_CHAR const *const constituent[],
5468 const NV_FLOAT64 *speed, NV_INT32 start_year,
5469 NV_U_INT32 num_years,
5470 NV_FLOAT32 const *const equilibrium[],
5471 NV_FLOAT32 const *const node_factor[]) {
5472 NV_U_INT32 i, j;
5473 NV_FLOAT64 min_value, max_value;
5474 NV_INT32 temp_int;
5475
5476 /* Validate input */
5477 assert(file);
5478 assert(constituent);
5479 assert(speed);
5480 assert(equilibrium);
5481 assert(node_factor);
5482 for (i = 0; i < constituents; ++i) {
5483 if (speed[i] < 0.0) {
5484 LOG_ERROR(
5485 "libtcd create_tide_db: somebody tried to set a negative speed "
5486 "(%f)\n",
5487 speed[i]);
5488 return NVFalse;
5489 }
5490 for (j = 0; j < num_years; ++j) {
5491 if (node_factor[i][j] <= 0.0) {
5492 LOG_ERROR(
5493 "libtcd create_tide_db: somebody tried to set a negative or zero "
5494 "node factor (%f)\n",
5495 node_factor[i][j]);
5496 return NVFalse;
5497 }
5498 }
5499 }
5500
5501 if (fp) close_tide_db();
5502
5503 if ((fp = fopen(file, "wb+")) == NULL) {
5504 perror(file);
5505 return (NVFalse);
5506 }
5507
5508 /* Zero out the header structure. */
5509
5510 memset(&hd, 0, sizeof(hd));
5511
5512 hd.pub.major_rev = LIBTCD_MAJOR_REV;
5513 hd.pub.minor_rev = LIBTCD_MINOR_REV;
5514
5515 hd.header_size = DEFAULT_HEADER_SIZE;
5516 hd.pub.number_of_records = DEFAULT_NUMBER_OF_RECORDS;
5517
5518 hd.pub.start_year = start_year;
5519 hd.pub.number_of_years = num_years;
5520
5521 hd.pub.constituents = constituents;
5522
5523 /* Constituent names. */
5524
5525 hd.constituent = (NV_CHAR **)calloc(hd.pub.constituents, sizeof(NV_CHAR *));
5526 for (i = 0; i < hd.pub.constituents; ++i) {
5527 hd.constituent[i] =
5528 (NV_CHAR *)calloc(strlen(constituent[i]) + 1, sizeof(NV_CHAR));
5529 strcpy(hd.constituent[i], constituent[i]);
5530 }
5531
5532 /* A constituent count is stored with each reference station record,
5533 and it uses constituent_bits, so we need to be able to store
5534 the count itself (not just the values 0..count-1). */
5535 hd.constituent_bits = calculate_bits(hd.pub.constituents);
5536
5537 /* Set all of the speed attributes. */
5538
5539 hd.speed = (NV_FLOAT64 *)calloc(hd.pub.constituents, sizeof(NV_FLOAT64));
5540
5541 hd.speed_scale = DEFAULT_SPEED_SCALE;
5542 min_value = 99999999.0;
5543 max_value = -99999999.0;
5544 for (i = 0; i < hd.pub.constituents; ++i) {
5545 if (speed[i] < min_value) min_value = speed[i];
5546 if (speed[i] > max_value) max_value = speed[i];
5547
5548 hd.speed[i] = speed[i];
5549 }
5550
5551 /* DWF fixed sign reversal 2003-11-16 */
5552 /* DWF harmonized rounding with the way it is done in write_tide_db_header
5553 2007-01-22 */
5554 hd.speed_offset = (NINT(min_value * hd.speed_scale));
5555 temp_int = NINT(max_value * hd.speed_scale) - hd.speed_offset;
5556 assert(temp_int >= 0);
5557 hd.speed_bits = calculate_bits((NV_U_INT32)temp_int);
5558 /* Generally 31. With signed ints we don't have any bits to spare. */
5559 assert(hd.speed_bits < 32);
5560
5561 /* Set all of the equilibrium attributes. */
5562
5563 hd.equilibrium =
5564 (NV_FLOAT32 **)calloc(hd.pub.constituents, sizeof(NV_FLOAT32 *));
5565
5566 hd.equilibrium_scale = DEFAULT_EQUILIBRIUM_SCALE;
5567 min_value = 99999999.0;
5568 max_value = -99999999.0;
5569 for (i = 0; i < hd.pub.constituents; ++i) {
5570 hd.equilibrium[i] =
5571 (NV_FLOAT32 *)calloc(hd.pub.number_of_years, sizeof(NV_FLOAT32));
5572 for (j = 0; j < hd.pub.number_of_years; ++j) {
5573 if (equilibrium[i][j] < min_value) min_value = equilibrium[i][j];
5574 if (equilibrium[i][j] > max_value) max_value = equilibrium[i][j];
5575
5576 hd.equilibrium[i][j] = equilibrium[i][j];
5577 }
5578 }
5579
5580 /* DWF fixed sign reversal 2003-11-16 */
5581 /* DWF harmonized rounding with the way it is done in write_tide_db_header
5582 2007-01-22 */
5583 hd.equilibrium_offset = (NINT(min_value * hd.equilibrium_scale));
5584 temp_int = NINT(max_value * hd.equilibrium_scale) - hd.equilibrium_offset;
5585 assert(temp_int >= 0);
5586 hd.equilibrium_bits = calculate_bits((NV_U_INT32)temp_int);
5587
5588 /* Set all of the node factor attributes. */
5589
5590 hd.node_factor =
5591 (NV_FLOAT32 **)calloc(hd.pub.constituents, sizeof(NV_FLOAT32 *));
5592
5593 hd.node_scale = DEFAULT_NODE_SCALE;
5594 min_value = 99999999.0;
5595 max_value = -99999999.0;
5596 for (i = 0; i < hd.pub.constituents; ++i) {
5597 hd.node_factor[i] =
5598 (NV_FLOAT32 *)calloc(hd.pub.number_of_years, sizeof(NV_FLOAT32));
5599 for (j = 0; j < hd.pub.number_of_years; ++j) {
5600 if (node_factor[i][j] < min_value) min_value = node_factor[i][j];
5601 if (node_factor[i][j] > max_value) max_value = node_factor[i][j];
5602
5603 hd.node_factor[i][j] = node_factor[i][j];
5604 }
5605 }
5606
5607 /* DWF fixed sign reversal 2003-11-16 */
5608 /* DWF harmonized rounding with the way it is done in write_tide_db_header
5609 2007-01-22 */
5610 hd.node_offset = (NINT(min_value * hd.node_scale));
5611 temp_int = NINT(max_value * hd.node_scale) - hd.node_offset;
5612 assert(temp_int >= 0);
5613 hd.node_bits = calculate_bits((NV_U_INT32)temp_int);
5614
5615 /* Default city. */
5616
5617 hd.amplitude_bits = DEFAULT_AMPLITUDE_BITS;
5618 hd.amplitude_scale = DEFAULT_AMPLITUDE_SCALE;
5619 hd.epoch_bits = DEFAULT_EPOCH_BITS;
5620 hd.epoch_scale = DEFAULT_EPOCH_SCALE;
5621
5622 hd.record_type_bits = DEFAULT_RECORD_TYPE_BITS;
5623 hd.latitude_bits = DEFAULT_LATITUDE_BITS;
5624 hd.latitude_scale = DEFAULT_LATITUDE_SCALE;
5625 hd.longitude_bits = DEFAULT_LONGITUDE_BITS;
5626 hd.longitude_scale = DEFAULT_LONGITUDE_SCALE;
5627 hd.record_size_bits = DEFAULT_RECORD_SIZE_BITS;
5628
5629 hd.station_bits = DEFAULT_STATION_BITS;
5630
5631 hd.datum_offset_bits = DEFAULT_DATUM_OFFSET_BITS;
5632 hd.datum_offset_scale = DEFAULT_DATUM_OFFSET_SCALE;
5633 hd.date_bits = DEFAULT_DATE_BITS;
5634 hd.months_on_station_bits = DEFAULT_MONTHS_ON_STATION_BITS;
5635 hd.confidence_value_bits = DEFAULT_CONFIDENCE_VALUE_BITS;
5636
5637 hd.time_bits = DEFAULT_TIME_BITS;
5638 hd.level_add_bits = DEFAULT_LEVEL_ADD_BITS;
5639 hd.level_add_scale = DEFAULT_LEVEL_ADD_SCALE;
5640 hd.level_multiply_bits = DEFAULT_LEVEL_MULTIPLY_BITS;
5641 hd.level_multiply_scale = DEFAULT_LEVEL_MULTIPLY_SCALE;
5642 hd.direction_bits = DEFAULT_DIRECTION_BITS;
5643
5644 hd.constituent_size = DEFAULT_CONSTITUENT_SIZE;
5645 hd.level_unit_size = DEFAULT_LEVEL_UNIT_SIZE;
5646 hd.dir_unit_size = DEFAULT_DIR_UNIT_SIZE;
5647 hd.restriction_size = DEFAULT_RESTRICTION_SIZE;
5648 hd.tzfile_size = DEFAULT_TZFILE_SIZE;
5649 hd.country_size = DEFAULT_COUNTRY_SIZE;
5650 hd.datum_size = DEFAULT_DATUM_SIZE;
5651 hd.legalese_size = DEFAULT_LEGALESE_SIZE;
5652
5653 /* Level units. */
5654
5655 hd.pub.level_unit_types = DEFAULT_LEVEL_UNIT_TYPES;
5656 hd.level_unit_bits = calculate_bits(hd.pub.level_unit_types - 1);
5657
5658 hd.level_unit =
5659 (NV_CHAR **)calloc(hd.pub.level_unit_types, sizeof(NV_CHAR *));
5660 for (i = 0; i < hd.pub.level_unit_types; ++i) {
5661 hd.level_unit[i] =
5662 (NV_CHAR *)calloc(strlen(level_unit[i]) + 1, sizeof(NV_CHAR));
5663 strcpy(hd.level_unit[i], level_unit[i]);
5664 }
5665
5666 /* Direction units. */
5667
5668 hd.pub.dir_unit_types = DEFAULT_DIR_UNIT_TYPES;
5669 hd.dir_unit_bits = calculate_bits(hd.pub.dir_unit_types - 1);
5670
5671 hd.dir_unit = (NV_CHAR **)calloc(hd.pub.dir_unit_types, sizeof(NV_CHAR *));
5672 for (i = 0; i < hd.pub.dir_unit_types; ++i) {
5673 hd.dir_unit[i] =
5674 (NV_CHAR *)calloc(strlen(dir_unit[i]) + 1, sizeof(NV_CHAR));
5675 strcpy(hd.dir_unit[i], dir_unit[i]);
5676 }
5677
5678 /* Restrictions. */
5679
5680 hd.restriction_bits = DEFAULT_RESTRICTION_BITS;
5681 hd.max_restriction_types = NINT(pow(2.0, (NV_FLOAT64)hd.restriction_bits));
5682 hd.pub.restriction_types = DEFAULT_RESTRICTION_TYPES;
5683
5684 hd.restriction =
5685 (NV_CHAR **)calloc(hd.max_restriction_types, sizeof(NV_CHAR *));
5686 for (i = 0; i < hd.max_restriction_types; ++i) {
5687 if (i == hd.pub.restriction_types) break;
5688
5689 hd.restriction[i] =
5690 (NV_CHAR *)calloc(strlen(restriction[i]) + 1, sizeof(NV_CHAR));
5691 strcpy(hd.restriction[i], restriction[i]);
5692 }
5693
5694 /* Legaleses. */
5695
5696 hd.legalese_bits = DEFAULT_LEGALESE_BITS;
5697 hd.max_legaleses = NINT(pow(2.0, (NV_FLOAT64)hd.legalese_bits));
5698 hd.pub.legaleses = DEFAULT_LEGALESES;
5699
5700 hd.legalese = (NV_CHAR **)calloc(hd.max_legaleses, sizeof(NV_CHAR *));
5701 for (i = 0; i < hd.max_legaleses; ++i) {
5702 if (i == hd.pub.legaleses) break;
5703
5704 hd.legalese[i] =
5705 (NV_CHAR *)calloc(strlen(legalese[i]) + 1, sizeof(NV_CHAR));
5706 strcpy(hd.legalese[i], legalese[i]);
5707 }
5708
5709 /* Tzfiles. */
5710
5711 hd.tzfile_bits = DEFAULT_TZFILE_BITS;
5712 hd.max_tzfiles = NINT(pow(2.0, (NV_FLOAT64)hd.tzfile_bits));
5713 hd.pub.tzfiles = DEFAULT_TZFILES;
5714
5715 hd.tzfile = (NV_CHAR **)calloc(hd.max_tzfiles, sizeof(NV_CHAR *));
5716 for (i = 0; i < hd.max_tzfiles; ++i) {
5717 if (i == hd.pub.tzfiles) break;
5718
5719 hd.tzfile[i] = (NV_CHAR *)calloc(strlen(tzfile[i]) + 1, sizeof(NV_CHAR));
5720 strcpy(hd.tzfile[i], tzfile[i]);
5721 }
5722
5723 /* Countries. */
5724
5725 hd.country_bits = DEFAULT_COUNTRY_BITS;
5726 hd.max_countries = NINT(pow(2.0, (NV_FLOAT64)hd.country_bits));
5727 hd.pub.countries = DEFAULT_COUNTRIES;
5728
5729 hd.country = (NV_CHAR **)calloc(hd.max_countries, sizeof(NV_CHAR *));
5730 for (i = 0; i < hd.max_countries; ++i) {
5731 if (i == hd.pub.countries) break;
5732
5733 hd.country[i] = (NV_CHAR *)calloc(strlen(country[i]) + 1, sizeof(NV_CHAR));
5734 strcpy(hd.country[i], country[i]);
5735 }
5736
5737 /* Datums. */
5738
5739 hd.datum_bits = DEFAULT_DATUM_BITS;
5740 hd.max_datum_types = NINT(pow(2.0, (NV_FLOAT64)hd.datum_bits));
5741 hd.pub.datum_types = DEFAULT_DATUM_TYPES;
5742
5743 hd.datum = (NV_CHAR **)calloc(hd.max_datum_types, sizeof(NV_CHAR *));
5744 for (i = 0; i < hd.max_datum_types; ++i) {
5745 if (i == hd.pub.datum_types) break;
5746
5747 hd.datum[i] = (NV_CHAR *)calloc(strlen(datum[i]) + 1, sizeof(NV_CHAR));
5748 strcpy(hd.datum[i], datum[i]);
5749 }
5750
5751 /* Write the header to the file and close. */
5752
5753 modified = NVTrue;
5754 close_tide_db();
5755
5756 /* Re-open it and read the header from the file. */
5757
5758 i = (open_tide_db(file));
5759
5760 /* Set the correct end of file position since the one in the header is
5761 set to 0. */
5762 hd.end_of_file = ftell(fp);
5763 /* DWF 2004-08-15: if the original program exits without adding any
5764 records, that doesn't help! Rewrite the header with correct
5765 end_of_file. */
5766 write_tide_db_header();
5767
5768 return (i);
5769}
5770
5771/*****************************************************************************\
5772 DWF 2004-10-13
5773 Used in check_tide_record.
5774\*****************************************************************************/
5775static NV_BOOL check_date(NV_U_INT32 date) {
5776 if (date) {
5777 unsigned m, d;
5778 date %= 10000;
5779 m = date / 100;
5780 d = date % 100;
5781 if (m < 1 || m > 12 || d < 1 || d > 31) return NVFalse;
5782 }
5783 return NVTrue;
5784}
5785
5786/*****************************************************************************\
5787 DWF 2004-10-13
5788 Returns true iff a record is valid enough to write. Reports all problems
5789 to LOG_ERROR. The checks are not designed to be airtight (e.g., if you
5790 use 360 degrees instead of 0 we'll let it slide).
5791
5792 Mild side effects may occur:
5793 Note that the units-to-level-units COMPAT114 trick is wedged in here.
5794\*****************************************************************************/
5795static NV_BOOL check_tide_record(TIDE_RECORD *rec) {
5796 NV_U_INT32 i;
5797 NV_BOOL ret = NVTrue;
5798
5799 if (!rec) {
5800 LOG_ERROR("libtcd error: null pointer passed to check_tide_record\n");
5801 return NVFalse;
5802 }
5803
5804 /* These are all static fields--if a buffer overflow has occurred on one
5805 of these, other fields might be invalid, but the problem started here. */
5806 boundscheck_oneliner(rec->header.name);
5807 boundscheck_oneliner(rec->source);
5808 boundscheck_monologue(rec->comments);
5809 boundscheck_monologue(rec->notes);
5810 boundscheck_oneliner(rec->station_id_context);
5811 boundscheck_oneliner(rec->station_id);
5812 boundscheck_monologue(rec->xfields);
5813
5814#ifdef COMPAT114
5815 if (rec->header.record_type == REFERENCE_STATION && rec->units > 0)
5816 rec->level_units = rec->units;
5817#endif
5818
5819 if (rec->header.latitude < -90.0 || rec->header.latitude > 90.0 ||
5820 rec->header.longitude < -180.0 || rec->header.longitude > 180.0) {
5821 LOG_ERROR("libtcd error: bad coordinates in tide record\n");
5822 ret = NVFalse;
5823 }
5824
5825 if (rec->header.tzfile < 0 ||
5826 rec->header.tzfile >= (NV_INT32)hd.pub.tzfiles) {
5827 LOG_ERROR("libtcd error: bad tzfile in tide record\n");
5828 ret = NVFalse;
5829 }
5830
5831 if (rec->header.name[0] == '\0') {
5832 LOG_ERROR("libtcd error: null name in tide record\n");
5833 ret = NVFalse;
5834 }
5835
5836 if (rec->country < 0 || rec->country >= (NV_INT32)hd.pub.countries) {
5837 LOG_ERROR("libtcd error: bad country in tide record\n");
5838 ret = NVFalse;
5839 }
5840
5841 if (rec->restriction >= hd.pub.restriction_types) {
5842 LOG_ERROR("libtcd error: bad restriction in tide record\n");
5843 ret = NVFalse;
5844 }
5845
5846 if (rec->legalese >= hd.pub.legaleses) {
5847 LOG_ERROR("libtcd error: bad legalese in tide record\n");
5848 ret = NVFalse;
5849 }
5850
5851 if (!check_date(rec->date_imported)) {
5852 LOG_ERROR("libtcd error: bad date_imported in tide record\n");
5853 ret = NVFalse;
5854 }
5855
5856 if (rec->direction_units >= hd.pub.dir_unit_types) {
5857 LOG_ERROR("libtcd error: bad direction_units in tide record\n");
5858 ret = NVFalse;
5859 }
5860
5861 if (rec->min_direction < 0 || rec->min_direction > 361) {
5862 LOG_ERROR("libtcd error: min_direction out of range in tide record\n");
5863 ret = NVFalse;
5864 }
5865
5866 if (rec->max_direction < 0 || rec->max_direction > 361) {
5867 LOG_ERROR("libtcd error: max_direction out of range in tide record\n");
5868 ret = NVFalse;
5869 }
5870
5871 if (rec->level_units >= hd.pub.level_unit_types) {
5872 LOG_ERROR("libtcd error: bad units in tide record\n");
5873 ret = NVFalse;
5874 }
5875
5876 switch (rec->header.record_type) {
5877 case REFERENCE_STATION:
5878 if (rec->header.reference_station != -1) {
5879 LOG_ERROR("libtcd error: type 1 record, reference_station != -1\n");
5880 ret = NVFalse;
5881 }
5882
5883 if (rec->datum_offset < -13421.7728 || rec->datum_offset > 13421.7727) {
5884 LOG_ERROR("libtcd error: datum_offset out of range in tide record\n");
5885 ret = NVFalse;
5886 }
5887
5888 if (rec->datum < 0 || rec->datum >= (NV_INT32)hd.pub.datum_types) {
5889 LOG_ERROR("libtcd error: bad datum in tide record\n");
5890 ret = NVFalse;
5891 }
5892
5893 if (rec->zone_offset < -4096 || rec->zone_offset > 4095 ||
5894 rec->zone_offset % 100 >= 60) {
5895 LOG_ERROR("libtcd error: bad zone_offset in tide record\n");
5896 ret = NVFalse;
5897 }
5898
5899 if (!check_date(rec->expiration_date)) {
5900 LOG_ERROR("libtcd error: bad expiration_date in tide record\n");
5901 ret = NVFalse;
5902 }
5903
5904 if (rec->months_on_station > 1023) {
5905 LOG_ERROR(
5906 "libtcd error: months_on_station out of range in tide record\n");
5907 ret = NVFalse;
5908 }
5909
5910 if (!check_date(rec->last_date_on_station)) {
5911 LOG_ERROR("libtcd error: bad last_date_on_station in tide record\n");
5912 ret = NVFalse;
5913 }
5914
5915 if (rec->confidence > 15) {
5916 LOG_ERROR("libtcd error: confidence out of range in tide record\n");
5917 ret = NVFalse;
5918 }
5919
5920 /* Only issue each error once. */
5921 for (i = 0; i < hd.pub.constituents; ++i) {
5922 if (rec->amplitude[i] < 0.0 || rec->amplitude[i] > 52.4287) {
5923 LOG_ERROR(
5924 "libtcd error: constituent amplitude out of range in tide "
5925 "record\n");
5926 ret = NVFalse;
5927 break;
5928 }
5929 }
5930 for (i = 0; i < hd.pub.constituents; ++i) {
5931 if (rec->epoch[i] < 0.0 || rec->epoch[i] > 360.0) {
5932 LOG_ERROR(
5933 "libtcd error: constituent epoch out of range in tide record\n");
5934 ret = NVFalse;
5935 break;
5936 }
5937 }
5938
5939 break;
5940
5941 case SUBORDINATE_STATION:
5942 if (rec->header.reference_station < 0 ||
5943 rec->header.reference_station >= (NV_INT32)hd.pub.number_of_records) {
5944 LOG_ERROR("libtcd error: bad reference_station in tide record\n");
5945 ret = NVFalse;
5946 }
5947
5948 if (rec->min_time_add < -4096 || rec->min_time_add > 4095 ||
5949 rec->min_time_add % 100 >= 60) {
5950 LOG_ERROR("libtcd error: bad min_time_add in tide record\n");
5951 ret = NVFalse;
5952 }
5953
5954 if (rec->min_level_add < -65.536 || rec->min_level_add > 65.535) {
5955 LOG_ERROR("libtcd error: min_level_add out of range in tide record\n");
5956 ret = NVFalse;
5957 }
5958
5959 if (rec->min_level_multiply < 0.0 || rec->min_level_multiply > 65.535) {
5960 LOG_ERROR(
5961 "libtcd error: min_level_multiply out of range in tide record\n");
5962 ret = NVFalse;
5963 }
5964
5965 if (rec->max_time_add < -4096 || rec->max_time_add > 4095 ||
5966 rec->max_time_add % 100 >= 60) {
5967 LOG_ERROR("libtcd error: bad max_time_add in tide record\n");
5968 ret = NVFalse;
5969 }
5970
5971 if (rec->max_level_add < -65.536 || rec->max_level_add > 65.535) {
5972 LOG_ERROR("libtcd error: max_level_add out of range in tide record\n");
5973 ret = NVFalse;
5974 }
5975
5976 if (rec->max_level_multiply < 0.0 || rec->max_level_multiply > 65.535) {
5977 LOG_ERROR(
5978 "libtcd error: max_level_multiply out of range in tide record\n");
5979 ret = NVFalse;
5980 }
5981
5982 if (rec->flood_begins != NULLSLACKOFFSET &&
5983 (rec->flood_begins < -4096 || rec->flood_begins > 4095 ||
5984 rec->flood_begins % 100 >= 60)) {
5985 LOG_ERROR("libtcd error: bad flood_begins in tide record\n");
5986 ret = NVFalse;
5987 }
5988
5989 if (rec->ebb_begins != NULLSLACKOFFSET &&
5990 (rec->ebb_begins < -4096 || rec->ebb_begins > 4095 ||
5991 rec->ebb_begins % 100 >= 60)) {
5992 LOG_ERROR("libtcd error: bad ebb_begins in tide record\n");
5993 ret = NVFalse;
5994 }
5995
5996 break;
5997
5998 default:
5999 LOG_ERROR("libtcd error: invalid record_type in tide record\n");
6000 ret = NVFalse;
6001 }
6002
6003 if (ret == NVFalse) dump_tide_record(rec);
6004 return ret;
6005}
6006
6007/*****************************************************************************\
6008 DWF 2004-10-13
6009 Calculate size of a tide record as it would be encoded in the TCD file.
6010 Size is stored in record_size field. Return is number of constituents
6011 that will be encoded.
6012\*****************************************************************************/
6013static NV_U_INT32 figure_size(TIDE_RECORD *rec) {
6014 NV_U_INT32 i, count = 0, name_size, source_size, comments_size, notes_size,
6015 station_id_context_size, station_id_size, xfields_size;
6016
6017 assert(rec);
6018
6019 /* Figure out how many bits we'll need for this record. */
6020
6021 name_size = strlen(clip_string(rec->header.name)) + 1;
6022 source_size = strlen(clip_string(rec->source)) + 1;
6023 comments_size = strlen(clip_string(rec->comments)) + 1;
6024 notes_size = strlen(clip_string(rec->notes)) + 1;
6025 station_id_context_size = strlen(clip_string(rec->station_id_context)) + 1;
6026 station_id_size = strlen(clip_string(rec->station_id)) + 1;
6027 /* No clipping on xfields -- trailing \n required by syntax */
6028 xfields_size = strlen(rec->xfields) + 1;
6029
6030 rec->header.record_size =
6031 hd.record_size_bits + hd.record_type_bits + hd.latitude_bits +
6032 hd.longitude_bits + hd.station_bits + hd.tzfile_bits + (name_size * 8) +
6033
6034 hd.country_bits + (source_size * 8) + hd.restriction_bits +
6035 (comments_size * 8) + (notes_size * 8) + hd.legalese_bits +
6036 (station_id_context_size * 8) + (station_id_size * 8) + hd.date_bits +
6037 (xfields_size * 8) + hd.dir_unit_bits + hd.direction_bits +
6038 hd.direction_bits + hd.level_unit_bits;
6039
6040 switch (rec->header.record_type) {
6041 case REFERENCE_STATION:
6042 rec->header.record_size += hd.datum_offset_bits + hd.datum_bits +
6043 hd.time_bits + hd.date_bits +
6044 hd.months_on_station_bits + hd.date_bits +
6045 hd.confidence_value_bits + hd.constituent_bits;
6046
6047 for (i = 0; i < hd.pub.constituents; ++i) {
6048 assert(rec->amplitude[i] >= 0.0);
6049 if (rec->amplitude[i] >= AMPLITUDE_EPSILON) ++count;
6050 }
6051
6052 rec->header.record_size +=
6053 (count * hd.constituent_bits + count * hd.amplitude_bits +
6054 count * hd.epoch_bits);
6055
6056 break;
6057
6058 case SUBORDINATE_STATION:
6059 rec->header.record_size += hd.time_bits + hd.level_add_bits +
6060 hd.level_multiply_bits + hd.time_bits +
6061 hd.level_add_bits + hd.level_multiply_bits +
6062 hd.time_bits + hd.time_bits;
6063 break;
6064
6065 default:
6066 assert(0);
6067 }
6068
6069 rec->header.record_size = bits2bytes(rec->header.record_size);
6070 return count;
6071}
6072
6073/*****************************************************************************\
6074DWF 2004-10-14
6075\*****************************************************************************/
6076static void pack_string(NV_U_BYTE *buf, NV_U_INT32 *pos, NV_CHAR *s) {
6077 NV_U_INT32 i, temp_size;
6078 assert(buf);
6079 assert(pos);
6080 assert(s);
6081 temp_size = strlen(s) + 1;
6082 for (i = 0; i < temp_size; ++i) {
6083 bit_pack(buf, *pos, 8, s[i]);
6084 *pos += 8;
6085 }
6086}
6087
6088/*****************************************************************************\
6089
6090 Function pack_tide_record - convert TIDE_RECORD to packed form
6091
6092 Synopsis pack_tide_record (rec, bufptr, bufsize);
6093
6094 TIDE_RECORD *rec tide record (in)
6095 NV_U_BYTE **bufptr packed record (out)
6096 NV_U_INT32 *bufsize size of buf in bytes (out)
6097
6098 buf is allocated by pack_tide_record and should be
6099 freed by the caller.
6100
6101 Returns void
6102
6103 Author Extracted from write_tide_record by David Flater
6104 Date 2006-05-26
6105
6106\*****************************************************************************/
6107
6108static void pack_tide_record(TIDE_RECORD *rec, NV_U_BYTE **bufptr,
6109 NV_U_INT32 *bufsize) {
6110 NV_U_INT32 i, pos, constituent_count;
6111 NV_INT32 temp_int;
6112 NV_U_BYTE *buf;
6113
6114 /* Validate input */
6115 assert(rec);
6116 /* Cursory check for buffer overflows. Should not happen here --
6117 check_tide_record does a more thorough job when called by add_tide_record
6118 and update_tide_record. */
6119 boundscheck_oneliner(rec->header.name);
6120 boundscheck_oneliner(rec->source);
6121 boundscheck_monologue(rec->comments);
6122 boundscheck_monologue(rec->notes);
6123 boundscheck_oneliner(rec->station_id_context);
6124 boundscheck_oneliner(rec->station_id);
6125 boundscheck_monologue(rec->xfields);
6126
6127 constituent_count = figure_size(rec);
6128
6129 if (!(*bufptr =
6130 (NV_U_BYTE *)calloc(rec->header.record_size, sizeof(NV_U_BYTE)))) {
6131 perror("libtcd can't allocate memory in pack_tide_record");
6132 exit(-1);
6133 }
6134 buf = *bufptr; /* To conserve asterisks */
6135
6136 /* Bit pack the common section. "pos" is the bit position within the
6137 buffer "buf". */
6138
6139 pos = 0;
6140
6141 bit_pack(buf, pos, hd.record_size_bits, rec->header.record_size);
6142 pos += hd.record_size_bits;
6143
6144 bit_pack(buf, pos, hd.record_type_bits, rec->header.record_type);
6145 pos += hd.record_type_bits;
6146
6147 temp_int = NINT(rec->header.latitude * hd.latitude_scale);
6148 bit_pack(buf, pos, hd.latitude_bits, temp_int);
6149 pos += hd.latitude_bits;
6150
6151 temp_int = NINT(rec->header.longitude * hd.longitude_scale);
6152 bit_pack(buf, pos, hd.longitude_bits, temp_int);
6153 pos += hd.longitude_bits;
6154
6155 /* This ordering doesn't match everywhere else but there's no technical
6156 reason to change it from its V1 ordering. To do so would force
6157 another conditional in unpack_partial_tide_record. */
6158
6159 bit_pack(buf, pos, hd.tzfile_bits, rec->header.tzfile);
6160 pos += hd.tzfile_bits;
6161
6162 pack_string(buf, &pos, clip_string(rec->header.name));
6163
6164 bit_pack(buf, pos, hd.station_bits, rec->header.reference_station);
6165 pos += hd.station_bits;
6166
6167 bit_pack(buf, pos, hd.country_bits, rec->country);
6168 pos += hd.country_bits;
6169
6170 pack_string(buf, &pos, clip_string(rec->source));
6171
6172 bit_pack(buf, pos, hd.restriction_bits, rec->restriction);
6173 pos += hd.restriction_bits;
6174
6175 pack_string(buf, &pos, clip_string(rec->comments));
6176 pack_string(buf, &pos, clip_string(rec->notes));
6177
6178 bit_pack(buf, pos, hd.legalese_bits, rec->legalese);
6179 pos += hd.legalese_bits;
6180
6181 pack_string(buf, &pos, clip_string(rec->station_id_context));
6182 pack_string(buf, &pos, clip_string(rec->station_id));
6183
6184 bit_pack(buf, pos, hd.date_bits, rec->date_imported);
6185 pos += hd.date_bits;
6186
6187 /* No clipping on xfields -- trailing \n required by syntax */
6188 pack_string(buf, &pos, rec->xfields);
6189
6190 bit_pack(buf, pos, hd.dir_unit_bits, rec->direction_units);
6191 pos += hd.dir_unit_bits;
6192
6193 bit_pack(buf, pos, hd.direction_bits, rec->min_direction);
6194 pos += hd.direction_bits;
6195
6196 bit_pack(buf, pos, hd.direction_bits, rec->max_direction);
6197 pos += hd.direction_bits;
6198
6199 /* The units-to-level-units compatibility hack is in check_tide_record */
6200 bit_pack(buf, pos, hd.level_unit_bits, rec->level_units);
6201 pos += hd.level_unit_bits;
6202
6203 /* Bit pack record type 1 records. */
6204
6205 if (rec->header.record_type == REFERENCE_STATION) {
6206 temp_int = NINT(rec->datum_offset * hd.datum_offset_scale);
6207 bit_pack(buf, pos, hd.datum_offset_bits, temp_int);
6208 pos += hd.datum_offset_bits;
6209
6210 bit_pack(buf, pos, hd.datum_bits, rec->datum);
6211 pos += hd.datum_bits;
6212
6213 bit_pack(buf, pos, hd.time_bits, rec->zone_offset);
6214 pos += hd.time_bits;
6215
6216 bit_pack(buf, pos, hd.date_bits, rec->expiration_date);
6217 pos += hd.date_bits;
6218
6219 bit_pack(buf, pos, hd.months_on_station_bits, rec->months_on_station);
6220 pos += hd.months_on_station_bits;
6221
6222 bit_pack(buf, pos, hd.date_bits, rec->last_date_on_station);
6223 pos += hd.date_bits;
6224
6225 bit_pack(buf, pos, hd.confidence_value_bits, rec->confidence);
6226 pos += hd.confidence_value_bits;
6227
6228 bit_pack(buf, pos, hd.constituent_bits, constituent_count);
6229 pos += hd.constituent_bits;
6230
6231 for (i = 0; i < hd.pub.constituents; ++i) {
6232 if (rec->amplitude[i] >= AMPLITUDE_EPSILON) {
6233 bit_pack(buf, pos, hd.constituent_bits, i);
6234 pos += hd.constituent_bits;
6235
6236 temp_int = NINT(rec->amplitude[i] * hd.amplitude_scale);
6237 assert(temp_int);
6238 bit_pack(buf, pos, hd.amplitude_bits, temp_int);
6239 pos += hd.amplitude_bits;
6240
6241 temp_int = NINT(rec->epoch[i] * hd.epoch_scale);
6242 bit_pack(buf, pos, hd.epoch_bits, temp_int);
6243 pos += hd.epoch_bits;
6244 }
6245 }
6246 }
6247
6248 /* Bit pack record type 2 records. */
6249 else if (rec->header.record_type == SUBORDINATE_STATION) {
6250 bit_pack(buf, pos, hd.time_bits, rec->min_time_add);
6251 pos += hd.time_bits;
6252
6253 temp_int = NINT(rec->min_level_add * hd.level_add_scale);
6254 bit_pack(buf, pos, hd.level_add_bits, temp_int);
6255 pos += hd.level_add_bits;
6256
6257 temp_int = NINT(rec->min_level_multiply * hd.level_multiply_scale);
6258 bit_pack(buf, pos, hd.level_multiply_bits, temp_int);
6259 pos += hd.level_multiply_bits;
6260
6261 bit_pack(buf, pos, hd.time_bits, rec->max_time_add);
6262 pos += hd.time_bits;
6263
6264 temp_int = NINT(rec->max_level_add * hd.level_add_scale);
6265 bit_pack(buf, pos, hd.level_add_bits, temp_int);
6266 pos += hd.level_add_bits;
6267
6268 temp_int = NINT(rec->max_level_multiply * hd.level_multiply_scale);
6269 bit_pack(buf, pos, hd.level_multiply_bits, temp_int);
6270 pos += hd.level_multiply_bits;
6271
6272 bit_pack(buf, pos, hd.time_bits, rec->flood_begins);
6273 pos += hd.time_bits;
6274
6275 bit_pack(buf, pos, hd.time_bits, rec->ebb_begins);
6276 pos += hd.time_bits;
6277 }
6278
6279 else {
6280 LOG_ERROR("libtcd error: Record type %d is undefined\n",
6281 rec->header.record_type);
6282 exit(-1);
6283 }
6284
6285 *bufsize = rec->header.record_size;
6286 assert(*bufsize == bits2bytes(pos));
6287}
6288
6289/*****************************************************************************\
6290
6291 Function write_tide_record - writes a tide record to the database
6292
6293 Synopsis write_tide_record (num, rec);
6294
6295 NV_INT32 num record number:
6296 >= 0 overwrite record num
6297 -1 write at current file position
6298 TIDE_RECORD *rec tide record
6299
6300 Returns NV_BOOL NVTrue if successful
6301
6302 Author Jan C. Depner
6303 Date 08/01/02
6304
6305 See libtcd.html for changelog.
6306
6307 hd.end_of_file is not updated by this function in any event.
6308
6309\*****************************************************************************/
6310
6311static NV_BOOL write_tide_record(NV_INT32 num, TIDE_RECORD *rec) {
6312 NV_U_BYTE *buf = NULL;
6313 NV_U_INT32 bufsize = 0;
6314
6315 if (!fp) {
6316 LOG_ERROR(
6317 "libtcd error: attempt to access database when database not open\n");
6318 return NVFalse;
6319 }
6320 write_protect();
6321
6322 pack_tide_record(rec, &buf, &bufsize);
6323
6324 if (num == -1)
6325 ;
6326 else if (num >= 0)
6327 fseek(fp, tindex[num].address, SEEK_SET);
6328 else
6329 assert(0);
6330
6331 chk_fwrite(buf, bufsize, 1, fp);
6332 free(buf);
6333 modified = NVTrue;
6334 return NVTrue;
6335}
6336
6337/*****************************************************************************\
6338
6339 Function read_next_tide_record - reads the next tide record from
6340 the database
6341
6342 Synopsis read_next_tide_record (rec);
6343
6344 TIDE_RECORD *rec tide record
6345
6346 Returns NV_INT32 record number of the tide record
6347
6348 Author Jan C. Depner
6349 Date 08/01/02
6350
6351 See libtcd.html for changelog.
6352
6353\*****************************************************************************/
6354
6355NV_INT32 read_next_tide_record(TIDE_RECORD *rec) {
6356 return (read_tide_record(current_record + 1, rec));
6357}
6358
6359/*****************************************************************************\
6360
6361 Function unpack_tide_record - convert TIDE_RECORD from packed form
6362
6363 Synopsis unpack_tide_record (buf, bufsize, rec);
6364
6365 NV_U_BYTE *buf packed record (in)
6366 NV_U_INT32 bufsize size of buf in bytes (in)
6367 TIDE_RECORD *rec tide record (in-out)
6368
6369 rec must be allocated by the caller.
6370
6371 Returns void
6372
6373 Author Extracted from read_tide_record by David Flater
6374 Date 2006-05-26
6375
6376 rec->header.record_number is initialized from the global current_record.
6377
6378\*****************************************************************************/
6379
6380static void unpack_tide_record(NV_U_BYTE *buf, NV_U_INT32 bufsize,
6381 TIDE_RECORD *rec) {
6382 NV_INT32 temp_int;
6383 NV_U_INT32 i, j, pos, count;
6384
6385 assert(rec);
6386
6387 /* Initialize record */
6388 memset(rec, 0, sizeof(TIDE_RECORD));
6389 {
6390 int r = find_dir_units("degrees true");
6391 assert(r > 0);
6392 rec->direction_units = (NV_U_BYTE)r;
6393 }
6394 rec->min_direction = rec->max_direction = 361;
6395 rec->flood_begins = rec->ebb_begins = NULLSLACKOFFSET;
6396 rec->header.record_number = current_record;
6397
6398 unpack_partial_tide_record(buf, bufsize, rec, &pos);
6399
6400 switch (rec->header.record_type) {
6401 case REFERENCE_STATION:
6402 case SUBORDINATE_STATION:
6403 break;
6404 default:
6405 LOG_ERROR("libtcd fatal error: tried to read type %d tide record.\n",
6406 rec->header.record_type);
6407 LOG_ERROR(
6408 "This version of libtcd only supports types 1 and 2. Perhaps you "
6409 "should\nupgrade.\n");
6410 exit(-1);
6411 }
6412
6413 switch (hd.pub.major_rev) {
6414 /************************* TCD V1 *****************************/
6415 case 0:
6416 case 1:
6417
6418 /* "pos" is the bit position within the buffer "buf". */
6419
6420 rec->country = bit_unpack(buf, pos, hd.country_bits);
6421 pos += hd.country_bits;
6422
6423 /* pedigree */
6424 pos += hd.pedigree_bits;
6425
6426 unpack_string(buf, bufsize, &pos, rec->source, ONELINER_LENGTH,
6427 "source field");
6428
6429 rec->restriction = bit_unpack(buf, pos, hd.restriction_bits);
6430 pos += hd.restriction_bits;
6431
6432 unpack_string(buf, bufsize, &pos, rec->comments, MONOLOGUE_LENGTH,
6433 "comments field");
6434
6435 if (rec->header.record_type == REFERENCE_STATION) {
6436 rec->level_units = bit_unpack(buf, pos, hd.level_unit_bits);
6437#ifdef COMPAT114
6438 rec->units = rec->level_units;
6439#endif
6440 pos += hd.level_unit_bits;
6441
6442 temp_int = signed_bit_unpack(buf, pos, hd.datum_offset_bits);
6443 rec->datum_offset = (NV_FLOAT32)temp_int / hd.datum_offset_scale;
6444 pos += hd.datum_offset_bits;
6445
6446 rec->datum = bit_unpack(buf, pos, hd.datum_bits);
6447 pos += hd.datum_bits;
6448
6449 rec->zone_offset = signed_bit_unpack(buf, pos, hd.time_bits);
6450 pos += hd.time_bits;
6451
6452 rec->expiration_date = bit_unpack(buf, pos, hd.date_bits);
6453 pos += hd.date_bits;
6454
6455 rec->months_on_station =
6456 bit_unpack(buf, pos, hd.months_on_station_bits);
6457 pos += hd.months_on_station_bits;
6458
6459 rec->last_date_on_station = bit_unpack(buf, pos, hd.date_bits);
6460 pos += hd.date_bits;
6461
6462 rec->confidence = bit_unpack(buf, pos, hd.confidence_value_bits);
6463 pos += hd.confidence_value_bits;
6464
6465 for (i = 0; i < hd.pub.constituents; ++i) {
6466 rec->amplitude[i] = 0.0;
6467 rec->epoch[i] = 0.0;
6468 }
6469
6470 count = bit_unpack(buf, pos, hd.constituent_bits);
6471 pos += hd.constituent_bits;
6472
6473 for (i = 0; i < count; ++i) {
6474 j = bit_unpack(buf, pos, hd.constituent_bits);
6475 pos += hd.constituent_bits;
6476
6477 rec->amplitude[j] =
6478 (NV_FLOAT32)bit_unpack(buf, pos, hd.amplitude_bits) /
6479 hd.amplitude_scale;
6480 pos += hd.amplitude_bits;
6481
6482 rec->epoch[j] =
6483 (NV_FLOAT32)bit_unpack(buf, pos, hd.epoch_bits) / hd.epoch_scale;
6484 pos += hd.epoch_bits;
6485 }
6486 } else if (rec->header.record_type == SUBORDINATE_STATION) {
6487 rec->level_units = bit_unpack(buf, pos, hd.level_unit_bits);
6488 pos += hd.level_unit_bits;
6489
6490 rec->direction_units = bit_unpack(buf, pos, hd.dir_unit_bits);
6491 pos += hd.dir_unit_bits;
6492
6493 /* avg_level_units */
6494 pos += hd.level_unit_bits;
6495
6496 rec->min_time_add = signed_bit_unpack(buf, pos, hd.time_bits);
6497 pos += hd.time_bits;
6498
6499 temp_int = signed_bit_unpack(buf, pos, hd.level_add_bits);
6500 rec->min_level_add = (NV_FLOAT32)temp_int / hd.level_add_scale;
6501 pos += hd.level_add_bits;
6502
6503 /* Signed in V1 */
6504 temp_int = signed_bit_unpack(buf, pos, hd.level_multiply_bits);
6505 rec->min_level_multiply =
6506 (NV_FLOAT32)temp_int / hd.level_multiply_scale;
6507 pos += hd.level_multiply_bits;
6508
6509 /* min_avg_level */
6510 pos += hd.level_add_bits;
6511
6512 rec->min_direction = bit_unpack(buf, pos, hd.direction_bits);
6513 pos += hd.direction_bits;
6514
6515 rec->max_time_add = signed_bit_unpack(buf, pos, hd.time_bits);
6516 pos += hd.time_bits;
6517
6518 temp_int = signed_bit_unpack(buf, pos, hd.level_add_bits);
6519 rec->max_level_add = (NV_FLOAT32)temp_int / hd.level_add_scale;
6520 pos += hd.level_add_bits;
6521
6522 /* Signed in V1 */
6523 temp_int = signed_bit_unpack(buf, pos, hd.level_multiply_bits);
6524 rec->max_level_multiply =
6525 (NV_FLOAT32)temp_int / hd.level_multiply_scale;
6526 pos += hd.level_multiply_bits;
6527
6528 /* max_avg_level */
6529 pos += hd.level_add_bits;
6530
6531 rec->max_direction = bit_unpack(buf, pos, hd.direction_bits);
6532 pos += hd.direction_bits;
6533
6534 rec->flood_begins = signed_bit_unpack(buf, pos, hd.time_bits);
6535 pos += hd.time_bits;
6536
6537 rec->ebb_begins = signed_bit_unpack(buf, pos, hd.time_bits);
6538 pos += hd.time_bits;
6539 } else {
6540 assert(0);
6541 }
6542 break;
6543
6544 /************************* TCD V2 *****************************/
6545 case 2:
6546 rec->country = bit_unpack(buf, pos, hd.country_bits);
6547 pos += hd.country_bits;
6548
6549 unpack_string(buf, bufsize, &pos, rec->source, ONELINER_LENGTH,
6550 "source field");
6551
6552 rec->restriction = bit_unpack(buf, pos, hd.restriction_bits);
6553 pos += hd.restriction_bits;
6554
6555 unpack_string(buf, bufsize, &pos, rec->comments, MONOLOGUE_LENGTH,
6556 "comments field");
6557 unpack_string(buf, bufsize, &pos, rec->notes, MONOLOGUE_LENGTH,
6558 "notes field");
6559
6560 rec->legalese = bit_unpack(buf, pos, hd.legalese_bits);
6561 pos += hd.legalese_bits;
6562
6563 unpack_string(buf, bufsize, &pos, rec->station_id_context,
6564 ONELINER_LENGTH, "station_id_context field");
6565 unpack_string(buf, bufsize, &pos, rec->station_id, ONELINER_LENGTH,
6566 "station_id field");
6567
6568 rec->date_imported = bit_unpack(buf, pos, hd.date_bits);
6569 pos += hd.date_bits;
6570
6571 unpack_string(buf, bufsize, &pos, rec->xfields, MONOLOGUE_LENGTH,
6572 "xfields field");
6573
6574 rec->direction_units = bit_unpack(buf, pos, hd.dir_unit_bits);
6575 pos += hd.dir_unit_bits;
6576
6577 rec->min_direction = bit_unpack(buf, pos, hd.direction_bits);
6578 pos += hd.direction_bits;
6579
6580 rec->max_direction = bit_unpack(buf, pos, hd.direction_bits);
6581 pos += hd.direction_bits;
6582
6583 rec->level_units = bit_unpack(buf, pos, hd.level_unit_bits);
6584#ifdef COMPAT114
6585 rec->units = rec->level_units;
6586#endif
6587 pos += hd.level_unit_bits;
6588
6589 if (rec->header.record_type == REFERENCE_STATION) {
6590 temp_int = signed_bit_unpack(buf, pos, hd.datum_offset_bits);
6591 rec->datum_offset = (NV_FLOAT32)temp_int / hd.datum_offset_scale;
6592 pos += hd.datum_offset_bits;
6593
6594 rec->datum = bit_unpack(buf, pos, hd.datum_bits);
6595 pos += hd.datum_bits;
6596
6597 rec->zone_offset = signed_bit_unpack(buf, pos, hd.time_bits);
6598 pos += hd.time_bits;
6599
6600 rec->expiration_date = bit_unpack(buf, pos, hd.date_bits);
6601 pos += hd.date_bits;
6602
6603 rec->months_on_station =
6604 bit_unpack(buf, pos, hd.months_on_station_bits);
6605 pos += hd.months_on_station_bits;
6606
6607 rec->last_date_on_station = bit_unpack(buf, pos, hd.date_bits);
6608 pos += hd.date_bits;
6609
6610 rec->confidence = bit_unpack(buf, pos, hd.confidence_value_bits);
6611 pos += hd.confidence_value_bits;
6612
6613 for (i = 0; i < hd.pub.constituents; ++i) {
6614 rec->amplitude[i] = 0.0;
6615 rec->epoch[i] = 0.0;
6616 }
6617
6618 count = bit_unpack(buf, pos, hd.constituent_bits);
6619 pos += hd.constituent_bits;
6620
6621 for (i = 0; i < count; ++i) {
6622 j = bit_unpack(buf, pos, hd.constituent_bits);
6623 pos += hd.constituent_bits;
6624
6625 rec->amplitude[j] =
6626 (NV_FLOAT32)bit_unpack(buf, pos, hd.amplitude_bits) /
6627 hd.amplitude_scale;
6628 pos += hd.amplitude_bits;
6629
6630 rec->epoch[j] =
6631 (NV_FLOAT32)bit_unpack(buf, pos, hd.epoch_bits) / hd.epoch_scale;
6632 pos += hd.epoch_bits;
6633 }
6634 } else if (rec->header.record_type == SUBORDINATE_STATION) {
6635 rec->min_time_add = signed_bit_unpack(buf, pos, hd.time_bits);
6636 pos += hd.time_bits;
6637
6638 temp_int = signed_bit_unpack(buf, pos, hd.level_add_bits);
6639 rec->min_level_add = (NV_FLOAT32)temp_int / hd.level_add_scale;
6640 pos += hd.level_add_bits;
6641
6642 /* Made unsigned in V2 */
6643 temp_int = bit_unpack(buf, pos, hd.level_multiply_bits);
6644 rec->min_level_multiply =
6645 (NV_FLOAT32)temp_int / hd.level_multiply_scale;
6646 pos += hd.level_multiply_bits;
6647
6648 rec->max_time_add = signed_bit_unpack(buf, pos, hd.time_bits);
6649 pos += hd.time_bits;
6650
6651 temp_int = signed_bit_unpack(buf, pos, hd.level_add_bits);
6652 rec->max_level_add = (NV_FLOAT32)temp_int / hd.level_add_scale;
6653 pos += hd.level_add_bits;
6654
6655 /* Made unsigned in V2 */
6656 temp_int = bit_unpack(buf, pos, hd.level_multiply_bits);
6657 rec->max_level_multiply =
6658 (NV_FLOAT32)temp_int / hd.level_multiply_scale;
6659 pos += hd.level_multiply_bits;
6660
6661 rec->flood_begins = signed_bit_unpack(buf, pos, hd.time_bits);
6662 pos += hd.time_bits;
6663
6664 rec->ebb_begins = signed_bit_unpack(buf, pos, hd.time_bits);
6665 pos += hd.time_bits;
6666 } else {
6667 assert(0);
6668 }
6669 break;
6670
6671 default:
6672 assert(0);
6673 }
6674
6675 assert(pos <= bufsize * 8);
6676}
6677
6678/*****************************************************************************\
6679
6680 Function read_tide_record - reads tide record "num" from the
6681 database
6682
6683 Synopsis read_tide_record (num, rec);
6684
6685 NV_INT32 num record number (in)
6686 TIDE_RECORD *rec tide record (in-out)
6687
6688 rec must be allocated by the caller.
6689
6690 Returns NV_INT32 num if success, -1 if failure
6691
6692 Author Jan C. Depner
6693 Date 08/01/02
6694
6695 See libtcd.html for changelog.
6696
6697\*****************************************************************************/
6698
6699NV_INT32 read_tide_record(NV_INT32 num, TIDE_RECORD *rec) {
6700 NV_U_BYTE *buf;
6701 NV_U_INT32 bufsize;
6702
6703 if (!fp) {
6704 LOG_ERROR(
6705 "libtcd error: attempt to access database when database not open\n");
6706 return -1;
6707 }
6708
6709 if (num < 0 || num >= (NV_INT32)hd.pub.number_of_records) return -1;
6710 assert(rec);
6711
6712 bufsize = tindex[num].record_size;
6713 if ((buf = (NV_U_BYTE *)calloc(bufsize, sizeof(NV_U_BYTE))) == NULL) {
6714 perror("Allocating read_tide_record buffer");
6715 exit(-1);
6716 }
6717
6718 current_record = num;
6719 require(fseek(fp, tindex[num].address, SEEK_SET) == 0);
6720 chk_fread(buf, tindex[num].record_size, 1, fp);
6721 unpack_tide_record(buf, bufsize, rec);
6722 free(buf);
6723 return num;
6724}
6725
6726/*****************************************************************************\
6727
6728 Function add_tide_record - adds a tide record to the database
6729
6730 Synopsis add_tide_record (rec);
6731
6732 TIDE_RECORD *rec tide record
6733
6734 Returns NV_BOOL NVTrue if successful
6735
6736 Author Jan C. Depner
6737 Date 08/01/02
6738
6739 See libtcd.html for changelog.
6740
6741\*****************************************************************************/
6742
6743NV_BOOL add_tide_record(TIDE_RECORD *rec, DB_HEADER_PUBLIC *db) {
6744 NV_INT32 pos;
6745
6746 if (!fp) {
6747 LOG_ERROR(
6748 "libtcd error: attempt to access database when database not open\n");
6749 return NVFalse;
6750 }
6751 write_protect();
6752
6753 if (!check_tide_record(rec)) return NVFalse;
6754
6755 fseek(fp, hd.end_of_file, SEEK_SET);
6756 pos = ftell(fp);
6757 assert(pos > 0);
6758
6759 rec->header.record_number = hd.pub.number_of_records++;
6760
6761 if (write_tide_record(-1, rec)) {
6762 if ((tindex = (TIDE_INDEX *)realloc(
6763 tindex, hd.pub.number_of_records * sizeof(TIDE_INDEX))) == NULL) {
6764 perror("Allocating more index records");
6765 exit(-1);
6766 }
6767
6768 tindex[rec->header.record_number].address = pos;
6769 tindex[rec->header.record_number].record_size = rec->header.record_size;
6770 tindex[rec->header.record_number].record_type = rec->header.record_type;
6771 tindex[rec->header.record_number].reference_station =
6772 rec->header.reference_station;
6773 assert(rec->header.tzfile >= 0);
6774 tindex[rec->header.record_number].tzfile = rec->header.tzfile;
6775 tindex[rec->header.record_number].lat =
6776 NINT(rec->header.latitude * hd.latitude_scale);
6777 tindex[rec->header.record_number].lon =
6778 NINT(rec->header.longitude * hd.longitude_scale);
6779
6780 if ((tindex[rec->header.record_number].name = (NV_CHAR *)calloc(
6781 strlen(rec->header.name) + 1, sizeof(NV_CHAR))) == NULL) {
6782 perror("Allocating index name memory");
6783 exit(-1);
6784 }
6785
6786 strcpy(tindex[rec->header.record_number].name, rec->header.name);
6787 pos = ftell(fp);
6788 assert(pos > 0);
6789 hd.end_of_file = pos;
6790 modified = NVTrue;
6791
6792 /* Get the new number of records. */
6793 if (db) *db = hd.pub;
6794
6795 return NVTrue;
6796 }
6797
6798 return NVFalse;
6799}
6800
6801#if 0
6802/*****************************************************************************\
6803
6804 Function delete_tide_record - deletes a record and all subordinate
6805 records from the database
6806
6807 Synopsis delete_tide_record (num);
6808
6809 NV_INT32 num record number
6810
6811 Returns NV_BOOL NVTrue if successful
6812
6813 Author Jan C. Depner (redone by David Flater)
6814 Date 08/01/02 (2006-05-26)
6815
6816 See libtcd.html for changelog.
6817
6818\*****************************************************************************/
6819
6820NV_BOOL delete_tide_record (NV_INT32 num, DB_HEADER_PUBLIC *db)
6821{
6822 NV_INT32 i, newrecnum, *map;
6823 NV_U_BYTE **allrecs_packed;
6824
6825 if (!fp) {
6826 LOG_ERROR ("libtcd error: attempt to access database when database not open\n");
6827 return NVFalse;
6828 }
6829 write_protect();
6830
6831 if (num < 0 || num >= (NV_INT32)hd.pub.number_of_records) return NVFalse;
6832
6833 /* Allocate workspace */
6834
6835 if (!(map = (NV_INT32 *) malloc (hd.pub.number_of_records * sizeof(NV_INT32)))) {
6836 perror ("libtcd: delete_tide_record: can't malloc");
6837 return NVFalse;
6838 }
6839 if (!(allrecs_packed = (NV_U_BYTE **) malloc (hd.pub.number_of_records * sizeof(NV_U_BYTE*)))) {
6840 perror ("libtcd: delete_tide_record: can't malloc");
6841 free (map);
6842 return NVFalse;
6843 }
6844
6845 /* First pass: read in database, build record number map and mark records
6846 for deletion */
6847
6848 require (fseek (fp, tindex[0].address, SEEK_SET) == 0);
6849 for (newrecnum=0,i=0; i<(NV_INT32)hd.pub.number_of_records; ++i) {
6850 assert (ftell(fp) == tindex[i].address);
6851 if (i == num || (tindex[i].record_type == SUBORDINATE_STATION && tindex[i].reference_station == num)) {
6852 map[i] = -1;
6853 allrecs_packed[i] = NULL;
6854 require (fseek (fp, tindex[i].record_size, SEEK_CUR) == 0);
6855 } else {
6856 map[i] = newrecnum++;
6857 if (!(allrecs_packed[i] = (NV_U_BYTE *) malloc (tindex[i].record_size))) {
6858 perror ("libtcd: delete_tide_record: can't malloc");
6859 for (--i; i>=0; --i)
6860 free (allrecs_packed[i]);
6861 free (allrecs_packed);
6862 free (map);
6863 return NVFalse;
6864 }
6865 chk_fread (allrecs_packed[i], tindex[i].record_size, 1, fp);
6866 }
6867 }
6868
6869 /* Second pass: rewrite database and fix substation linkage */
6870
6871 require (fseek (fp, tindex[0].address, SEEK_SET) == 0);
6872 require (ftruncate (fileno(fp), tindex[0].address) == 0);
6873
6874 for (i=0; i<(NV_INT32)hd.pub.number_of_records; ++i)
6875 if (map[i] >= 0) {
6876 if (tindex[i].record_type == SUBORDINATE_STATION) {
6877 assert (tindex[i].reference_station >= 0);
6878 assert (tindex[i].reference_station <= (NV_INT32)hd.pub.number_of_records);
6879 if (map[tindex[i].reference_station] != tindex[i].reference_station) {
6880 /* Fix broken reference station linkage */
6881 TIDE_RECORD rec;
6882 unpack_tide_record (allrecs_packed[i], tindex[i].record_size, &rec);
6883 free (allrecs_packed[i]);
6884 rec.header.reference_station = map[tindex[i].reference_station];
6885 pack_tide_record (&rec, &(allrecs_packed[i]), &(tindex[i].record_size));
6886 }
6887 }
6888 chk_fwrite (allrecs_packed[i], tindex[i].record_size, 1, fp);
6889 free (allrecs_packed[i]);
6890 }
6891
6892 /* Free workspace (packed records were freed above) */
6893
6894 free (allrecs_packed);
6895 free (map);
6896
6897 /* Flush, reopen, renew. The index is now garbage; close and reopen
6898 to reindex. */
6899
6900 hd.end_of_file = ftell(fp);
6901 hd.pub.number_of_records = newrecnum;
6902 modified = NVTrue;
6903 close_tide_db ();
6904 open_tide_db (filename);
6905
6906 if (db)
6907 *db = hd.pub;
6908
6909 return NVTrue;
6910}
6911
6912#endif
6913
6914/*****************************************************************************\
6915
6916 Function update_tide_record - updates a tide record in the database
6917
6918 Synopsis update_tide_record (num, rec);
6919
6920 NV_INT32 num record number
6921 TIDE_RECORD *rec tide record
6922
6923 Returns NV_BOOL NVTrue if successful
6924
6925 Author Jan C. Depner
6926 Date 08/01/02
6927
6928 See libtcd.html for changelog.
6929
6930\*****************************************************************************/
6931
6932#ifdef COMPAT114
6933NV_BOOL update_tide_record(NV_INT32 num, TIDE_RECORD *rec)
6934#else
6935NV_BOOL update_tide_record(NV_INT32 num, TIDE_RECORD *rec, DB_HEADER_PUBLIC *db)
6936#endif
6937{
6938 NV_INT32 pos, size;
6939 TIDE_RECORD tmp_rec;
6940 NV_U_BYTE *block = NULL;
6941
6942 if (!fp) {
6943 LOG_ERROR(
6944 "libtcd error: attempt to access database when database not open\n");
6945 return NVFalse;
6946 }
6947 write_protect();
6948
6949 if (num < 0 || num >= (NV_INT32)hd.pub.number_of_records) return NVFalse;
6950
6951 if (!check_tide_record(rec)) return NVFalse;
6952
6953 figure_size(rec);
6954 read_tide_record(num, &tmp_rec);
6955 if (rec->header.record_size != tmp_rec.header.record_size) {
6956 /* Aaaaaaarrrrrgggggghhhh!!!! We have to move stuff! */
6957
6958 /* Save where we are - end of record being modified. */
6959 pos = ftell(fp);
6960 assert(pos > 0);
6961
6962 /* Figure out how big a block we need to move. */
6963 size = hd.end_of_file - pos;
6964 assert(size >= 0);
6965
6966 /* Allocate memory and read the block. */
6967 if (size) {
6968 if ((block = (NV_U_BYTE *)calloc(size, sizeof(NV_U_BYTE))) == NULL) {
6969 perror("Allocating block");
6970 return NVFalse;
6971 }
6972 chk_fread(block, size, 1, fp);
6973 }
6974
6975 /* Write out the modified record. */
6976 write_tide_record(num, rec);
6977
6978 /* If we weren't at the end of file, move the block. */
6979 if (size) {
6980 chk_fwrite(block, size, 1, fp);
6981 free(block);
6982 }
6983
6984 hd.end_of_file = ftell(fp);
6985
6986 /* Close the file and reopen it to index the records again. */
6987 close_tide_db();
6988 open_tide_db(filename);
6989 }
6990
6991 /* The easy way. No change to the record size. */
6992 else {
6993 write_tide_record(num, rec);
6994
6995 /* Save the header info in the index. */
6996 tindex[num].record_size = rec->header.record_size;
6997 tindex[num].record_type = rec->header.record_type;
6998 tindex[num].reference_station = rec->header.reference_station;
6999 tindex[num].tzfile = rec->header.tzfile;
7000 tindex[num].lat = NINT(rec->header.latitude * hd.latitude_scale);
7001 tindex[num].lon = NINT(rec->header.longitude * hd.longitude_scale);
7002
7003 /* AH maybe? */
7004 /* DWF: agree, same size record does not imply that name length
7005 is identical. */
7006 if (strcmp(tindex[num].name, rec->header.name) != 0) {
7007 free(tindex[num].name);
7008 tindex[num].name =
7009 (NV_CHAR *)calloc(strlen(rec->header.name) + 1, sizeof(NV_CHAR));
7010 strcpy(tindex[num].name, rec->header.name);
7011 }
7012 }
7013
7014#ifndef COMPAT114
7015 if (db) *db = hd.pub;
7016#endif
7017
7018 return (NVTrue);
7019}
7020
7021/*****************************************************************************\
7022
7023 Function infer_constituents - computes inferred constituents when
7024 M2, S2, K1, and O1 are given. This function fills the
7025 remaining unfilled constituents. The inferred constituents
7026 are developed or decided based on article 230 of
7027 "Manual of Harmonic Analysis and Prediction of Tides",
7028 Paul Schureman, C & GS special publication no. 98,
7029 October 1971. This function is really just for NAVO
7030 since we go to weird places and put in tide gages for
7031 ridiculously short periods of time so we only get a
7032 few major constituents developed. This function was
7033 modified from the NAVO FORTRAN program pred_tide_corr,
7034 subroutine infer.ftn, 08-oct-86.
7035
7036 Synopsis infer_constituents (rec);
7037
7038 TIDE_RECORD rec tide record
7039
7040 Returns NV_BOOL NVFalse if not enough constituents
7041 available to infer others
7042
7043 Author Jan C. Depner
7044 Date 08/01/02
7045
7046 See libtcd.html for changelog.
7047
7048\*****************************************************************************/
7049
7050NV_BOOL infer_constituents(TIDE_RECORD *rec) {
7051 NV_U_INT32 i, j;
7052 NV_INT32 m2, s2, k1, o1;
7053 NV_FLOAT32 epoch_m2, epoch_s2, epoch_k1, epoch_o1;
7054
7055 assert(rec);
7056 require((m2 = find_constituent("M2")) >= 0);
7057 require((s2 = find_constituent("S2")) >= 0);
7058 require((k1 = find_constituent("K1")) >= 0);
7059 require((o1 = find_constituent("O1")) >= 0);
7060
7061 if (rec->amplitude[m2] == 0.0 || rec->amplitude[s2] == 0.0 ||
7062 rec->amplitude[k1] == 0.0 || rec->amplitude[o1] == 0.0)
7063 return (NVFalse);
7064
7065 epoch_m2 = rec->epoch[m2];
7066 epoch_s2 = rec->epoch[s2];
7067 epoch_k1 = rec->epoch[k1];
7068 epoch_o1 = rec->epoch[o1];
7069
7070 for (i = 0; i < hd.pub.constituents; ++i) {
7071 if (rec->amplitude[i] == 0.0 && rec->epoch[i] == 0.0) {
7072 for (j = 0; j < INFERRED_SEMI_DIURNAL_COUNT; ++j) {
7073 if (!strcmp(inferred_semi_diurnal[j], get_constituent(i))) {
7074 /* Compute the inferred semi-diurnal constituent. */
7075
7076 rec->amplitude[i] =
7077 (semi_diurnal_coeff[j] / coeff[0]) * rec->amplitude[m2];
7078
7079 if (fabs((NV_FLOAT64)(epoch_s2 - epoch_m2)) > 180.0) {
7080 if (epoch_s2 < epoch_m2) {
7081 epoch_s2 += 360.0;
7082 } else {
7083 epoch_m2 += 360.0;
7084 }
7085 }
7086 rec->epoch[i] = epoch_m2 + ((hd.speed[i] - hd.speed[m2]) /
7087 (hd.speed[s2] - hd.speed[m2])) *
7088 (epoch_s2 - epoch_m2);
7089 }
7090 }
7091
7092 for (j = 0; j < INFERRED_DIURNAL_COUNT; ++j) {
7093 if (!strcmp(inferred_diurnal[j], get_constituent(i))) {
7094 /* Compute the inferred diurnal constituent. */
7095
7096 rec->amplitude[i] =
7097 (diurnal_coeff[j] / coeff[1]) * rec->amplitude[o1];
7098
7099 if (fabs((NV_FLOAT64)(epoch_k1 - epoch_o1)) > 180.0) {
7100 if (epoch_k1 < epoch_o1) {
7101 epoch_k1 += 360.0;
7102 } else {
7103 epoch_o1 += 360.0;
7104 }
7105 }
7106 rec->epoch[i] = epoch_o1 + ((hd.speed[i] - hd.speed[o1]) /
7107 (hd.speed[k1] - hd.speed[o1])) *
7108 (epoch_k1 - epoch_o1);
7109 }
7110 }
7111 }
7112 }
7113
7114 return (NVTrue);
7115}
7116
7117/* $Id: bit_pack.c 1805 2007-01-22 15:36:20Z flaterco $ */
7118
7119#include <math.h>
7120#include <stdio.h>
7121#include <assert.h>
7122
7123static NV_U_BYTE mask[8] = {0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe},
7124 notmask[8] = {0xff, 0x7f, 0x3f, 0x1f, 0x0f, 0x07, 0x03, 0x01};
7125
7126/*****************************************************************************\
7127
7128 DISTRIBUTION STATEMENT
7129
7130 This source file is unclassified, distribution unlimited, public
7131 domain. It is distributed in the hope that it will be useful, but
7132 WITHOUT ANY WARRANTY; without even the implied warranty of
7133 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7134
7135\*****************************************************************************/
7136
7137/***************************************************************************\
7138* *
7139* Function calculate_bits - Computes the number of bits needed *
7140* to store a specified value. *
7141* *
7142* Synopsis calculate_bits (value); *
7143* *
7144* NV_U_INT32 value the value to store *
7145* *
7146* Returns NV_U_INT32 number of bits needed *
7147* *
7148* If value = 0, return is 0. *
7149* No bits are needed to store a field whose only possible value is 0. *
7150* *
7151* Author Jan C. Depner *
7152* *
7153* Rewritten by DWF 2007-01-21 *
7154* - "Range" was ambiguous and off-by-one errors existed in tide_db.c *
7155* - Use of log10(x)/log10(2) was vulnerable to roundoff error *
7156* - Conversion to floating point was unnecessary *
7157* - Was giving the answer 0 for the input value 1 *
7158* - God only knows what it did for the input value 0 (the logarithm *
7159* is undefined) *
7160* *
7161\***************************************************************************/
7162
7163NV_U_INT32 calculate_bits(NV_U_INT32 value) {
7164 NV_U_INT32 bits = 32;
7165 NV_U_INT32 theBit = 0x80000000;
7166
7167 while (value < theBit) {
7168 theBit >>= 1;
7169 --bits;
7170 }
7171 assert(bits <= 32);
7172 return bits;
7173}
7174
7175/***************************************************************************\
7176* *
7177* Function bit_pack - Packs a long value into consecutive bits in *
7178* buffer. *
7179* *
7180* Synopsis bit_pack (buffer, start, numbits, value); *
7181* *
7182* NV_U_BYTE buffer[] address of buffer to use *
7183* NV_U_INT32 start start bit position in buffer *
7184* NV_U_INT32 numbits number of bits to store *
7185* NV_INT32 value value to store *
7186* *
7187* Description Packs the value 'value' into 'numbits' bits in 'buffer' *
7188* starting at bit position 'start'. The majority of *
7189* this code is based on Appendix C of Naval Ocean *
7190* Research and Development Activity Report #236, 'Data *
7191* Base Structure to Support the Production of the Digital *
7192* Bathymetric Data Base', Nov. 1989, James E. Braud, *
7193* John L. Breckenridge, James E. Current, Jerry L. *
7194* Landrum. *
7195* *
7196* Returns void *
7197* *
7198* Author Jan C. Depner *
7199* *
7200\***************************************************************************/
7201
7202void bit_pack(NV_U_BYTE buffer[], NV_U_INT32 start, NV_U_INT32 numbits,
7203 NV_INT32 value) {
7204 NV_INT32 start_byte, end_byte, start_bit, end_bit, i;
7205
7206 i = start + numbits;
7207
7208 /* Right shift the start and end by 3 bits, this is the same as */
7209 /* dividing by 8 but is faster. This is computing the start and end */
7210 /* bytes for the field. */
7211
7212 start_byte = start >> 3;
7213 end_byte = i >> 3;
7214
7215 /* AND the start and end bit positions with 7, this is the same as */
7216 /* doing a mod with 8 but is faster. Here we are computing the start */
7217 /* and end bits within the start and end bytes for the field. */
7218
7219 start_bit = start & 7;
7220 end_bit = i & 7;
7221
7222 /* Compute the number of bytes covered. */
7223
7224 i = end_byte - start_byte - 1;
7225
7226 /* If the value is to be stored in one byte, store it. */
7227
7228 if (start_byte == end_byte) {
7229 /* Rather tricky. We are masking out anything prior to the start */
7230 /* bit and after the end bit in order to not corrupt data that has */
7231 /* already been stored there. */
7232
7233 buffer[start_byte] &= mask[start_bit] | notmask[end_bit];
7234
7235 /* Now we mask out anything in the value that is prior to the */
7236 /* start bit and after the end bit. This is, of course, after we */
7237 /* have shifted the value left past the end bit. */
7238
7239 buffer[start_byte] |=
7240 (value << (8 - end_bit)) & (notmask[start_bit] & mask[end_bit]);
7241 }
7242
7243 /* If the value covers more than 1 byte, store it. */
7244
7245 else {
7246#pragma GCC diagnostic push
7247#pragma GCC diagnostic ignored "-Warray-bounds"
7248 // Compiler is confused about bit manipulated index, but it looks ok.
7249
7250 /* Here we mask out data prior to the start bit of the first byte. */
7251
7252 buffer[start_byte] &= mask[start_bit];
7253
7254 /* Get the upper bits of the value and mask out anything prior to */
7255 /* the start bit. As an example of what's happening here, if we */
7256 /* wanted to store a 14 bit field and the start bit for the first */
7257 /* byte is 3, we would be storing the upper 5 bits of the value in */
7258 /* the first byte. */
7259
7260 buffer[start_byte++] |=
7261 (value >> (numbits - (8 - start_bit))) & notmask[start_bit];
7262
7263 /* Loop while decrementing the byte counter. */
7264
7265 while (i--) {
7266 /* Clear the entire byte. */
7267
7268 buffer[start_byte] &= 0;
7269
7270 /* Get the next 8 bits from the value. */
7271
7272 buffer[start_byte++] |= (value >> ((i << 3) + end_bit)) & 255;
7273 }
7274
7275 /* For the last byte we mask out anything after the end bit. */
7276
7277 buffer[start_byte] &= notmask[end_bit];
7278
7279 /* Get the last part of the value and stuff it in the end byte. */
7280 /* The left shift effectively erases anything above 8 - end_bit */
7281 /* bits in the value so that it will fit in the last byte. */
7282
7283 buffer[start_byte] |= (value << (8 - end_bit));
7284#pragma GCC diagnostic pop
7285 }
7286}
7287
7288/***************************************************************************\
7289* *
7290* Function bit_unpack - Unpacks a long value from consecutive bits *
7291* in buffer. *
7292* *
7293* Synopsis bit_unpack (buffer, start, numbits); *
7294* *
7295* NV_U_BYTE buffer[] address of buffer to use *
7296* NV_U_INT32 start start bit position in buffer *
7297* NV_U_INT32 numbits number of bits to retrieve *
7298* *
7299* Description Unpacks the value from 'numbits' bits in 'buffer' *
7300* starting at bit position 'start'. The value is assumed *
7301* to be unsigned. The majority of this code is based on *
7302* Appendix C of Naval Ocean Research and Development *
7303* Activity Report #236, 'Data Base Structure to Support *
7304* the Production of the Digital Bathymetric Data Base', *
7305* Nov. 1989, James E. Braud, John L. Breckenridge, James *
7306* E. Current, Jerry L. Landrum. *
7307* *
7308* Returns NV_U_INT32 value retrieved from buffer *
7309* *
7310* Author Jan C. Depner *
7311* *
7312\***************************************************************************/
7313
7314NV_U_INT32 bit_unpack(NV_U_BYTE buffer[], NV_U_INT32 start,
7315 NV_U_INT32 numbits) {
7316 NV_INT32 start_byte, end_byte, start_bit, end_bit, i;
7317 NV_U_INT32 value;
7318
7319 i = start + numbits;
7320
7321 /* Right shift the start and end by 3 bits, this is the same as */
7322 /* dividing by 8 but is faster. This is computing the start and end */
7323 /* bytes for the field. */
7324
7325 start_byte = start >> 3;
7326 end_byte = i >> 3;
7327
7328 /* AND the start and end bit positions with 7, this is the same as */
7329 /* doing a mod with 8 but is faster. Here we are computing the start */
7330 /* and end bits within the start and end bytes for the field. */
7331
7332 start_bit = start & 7;
7333 end_bit = i & 7;
7334
7335 /* Compute the number of bytes covered. */
7336
7337 i = end_byte - start_byte - 1;
7338
7339 /* If the value is stored in one byte, retrieve it. */
7340
7341 if (start_byte == end_byte) {
7342 /* Mask out anything prior to the start bit and after the end bit. */
7343
7344 value =
7345 (NV_U_INT32)buffer[start_byte] & (notmask[start_bit] & mask[end_bit]);
7346
7347 /* Now we shift the value to the right. */
7348
7349 value >>= (8 - end_bit);
7350 }
7351
7352 /* If the value covers more than 1 byte, retrieve it. */
7353
7354 else {
7355 /* Here we mask out data prior to the start bit of the first byte */
7356 /* and shift to the left the necessary amount. */
7357
7358 value = (NV_U_INT32)(buffer[start_byte++] & notmask[start_bit])
7359 << (numbits - (8 - start_bit));
7360
7361 /* Loop while decrementing the byte counter. */
7362
7363 while (i--) {
7364 /* Get the next 8 bits from the buffer. */
7365
7366 value += (NV_U_INT32)buffer[start_byte++] << ((i << 3) + end_bit);
7367 }
7368
7369 /* For the last byte we mask out anything after the end bit and */
7370 /* then shift to the right (8 - end_bit) bits. */
7371 if (mask[end_bit]) {
7372 value +=
7373 (NV_U_INT32)(buffer[start_byte] & mask[end_bit]) >> (8 - end_bit);
7374 }
7375 }
7376
7377 return (value);
7378}
7379
7380/***************************************************************************\
7381* *
7382* Function signed_bit_unpack - Unpacks a signed long value from *
7383* consecutive bits in buffer. *
7384* *
7385* Synopsis signed_bit_unpack (buffer, start, numbits); *
7386* *
7387* NV_U_BYTE buffer[] address of buffer to use *
7388* NV_U_INT32 start start bit position in buffer *
7389* NV_U_INT32 numbits number of bits to retrieve *
7390* *
7391* Description Unpacks the value from 'numbits' bits in 'buffer' *
7392* starting at bit position 'start'. The value is assumed *
7393* to be signed. The majority of this code is based on *
7394* Appendix C of Naval Ocean Research and Development *
7395* Activity Report #236, 'Data Base Structure to Support *
7396* the Production of the Digital Bathymetric Data Base', *
7397* Nov. 1989, James E. Braud, John L. Breckenridge, James *
7398* E. Current, Jerry L. Landrum. *
7399* *
7400* Returns NV_INT32 value retrieved from buffer *
7401* *
7402* Author Jan C. Depner *
7403* *
7404\***************************************************************************/
7405
7406NV_INT32 signed_bit_unpack(NV_U_BYTE buffer[], NV_U_INT32 start,
7407 NV_U_INT32 numbits) {
7408 static NV_INT32 extend_mask = 0x7fffffff;
7409 NV_INT32 value;
7410
7411 /* This function is not used anywhere that this case could arise. */
7412 assert(numbits > 0);
7413
7414 value = bit_unpack(buffer, start, numbits);
7415
7416 if (value & (1 << (numbits - 1))) value |= (extend_mask << numbits);
7417
7418 return (value);
7419}
Represents an index entry for tidal and current data.
Definition idx_entry.h:48
int have_offsets
Flag indicating presence of time/height offsets.
Definition idx_entry.h:84
time_t epoch
Epoch time for the station.
Definition idx_entry.h:106
int IDX_time_zone
Station timezone offset from UTC (in minutes)
Definition idx_entry.h:94
char IDX_type
Entry type identifier "TCtcIUu".
Definition idx_entry.h:60
int num_nodes
Number of nodes in harmonic analysis.
Definition idx_entry.h:98
float IDX_lt_off
Low tide height offset.
Definition idx_entry.h:70
TCDataSource * pDataSource
Pointer to the associated data source.
Definition idx_entry.h:55
float IDX_lt_mpy
Low tide height multiplier.
Definition idx_entry.h:69
int Valid15
Validity flag for 15-minute interval data.
Definition idx_entry.h:75
time_t recent_high_time
Time of the most recent high tide.
Definition idx_entry.h:115
int epoch_year
Year of the epoch.
Definition idx_entry.h:107
int IDX_flood_dir
Flood current direction (in degrees)
Definition idx_entry.h:72
int IDX_Useable
Flag indicating if the entry is usable.
Definition idx_entry.h:74
char IDX_station_name[MAXNAMELEN]
Name of the tidal or current station.
Definition idx_entry.h:62
float recent_low_level
Most recently calculated low tide level.
Definition idx_entry.h:116
int station_tz_offset
Offset in seconds to convert from harmonic data (epochs) to the station time zone.
Definition idx_entry.h:93
double max_amplitude
Maximum tidal amplitude.
Definition idx_entry.h:83
int first_year
First year of valid data.
Definition idx_entry.h:105
double * m_work_buffer
Work buffer for calculations.
Definition idx_entry.h:104
int IDX_ht_time_off
High tide time offset (in minutes)
Definition idx_entry.h:65
float Dir15
Direction for 15-minute interval data.
Definition idx_entry.h:77
float recent_high_level
Most recently calculated high tide level.
Definition idx_entry.h:114
double ** m_cst_nodes
2D array of constituent nodes
Definition idx_entry.h:102
int IDX_ebb_dir
Ebb current direction (in degrees)
Definition idx_entry.h:73
double ** m_cst_epochs
2D array of constituent epochs
Definition idx_entry.h:103
float IDX_ht_mpy
High tide height multiplier.
Definition idx_entry.h:66
int current_depth
Depth for current stations.
Definition idx_entry.h:108
double IDX_lat
Latitude of the station (in degrees, +North)
Definition idx_entry.h:64
double IDX_lon
Longitude of the station (in degrees, +East)
Definition idx_entry.h:63
bool Ret15
Return flag for 15-minute interval data.
Definition idx_entry.h:78
bool b_skipTooDeep
Flag to skip processing if depth exceeds limit.
Definition idx_entry.h:109
int num_epochs
Number of epochs in harmonic data.
Definition idx_entry.h:100
double * m_cst_speeds
Array of constituent speeds.
Definition idx_entry.h:101
Station_Data * pref_sta_data
Pointer to the reference station data.
Definition idx_entry.h:96
int IDX_lt_time_off
Low tide time offset (in minutes)
Definition idx_entry.h:68
time_t recent_highlow_calc_time
Timestamp of the most recent high/low calculation.
Definition idx_entry.h:112
int num_csts
Number of harmonic constituents.
Definition idx_entry.h:99
time_t recent_low_time
Time of the most recent low tide.
Definition idx_entry.h:117
float IDX_ht_off
High tide height offset.
Definition idx_entry.h:67
int IDX_rec_num
Record number for multiple entries with same name.
Definition idx_entry.h:59
float Value15
Value for 15-minute interval data.
Definition idx_entry.h:76
Definition tcmgr.h:89
OpenCPN Georef utility.
General purpose GUI support.
Enhanced logging interface on top of wx/log.h.
std::string tolower(const std::string &input)
Return copy of s with all characters converted to lower case.
wxDateTime toUsrDateTime(const wxDateTime ts, const int format, const double lon)
Converts a timestamp from UTC to the user's preferred time format.
Definition navutil.cpp:2869
Utility functions.
Definition tcmgr.h:608
Runtime representation of a plugin block.
TCMgr * ptcmgr
Global instance.
Definition tcmgr.cpp:42
double BOGUS_amplitude(double mpy, IDX_entry *pIDX)
BOGUS amplitude stuff - Added mgh For knots^2 current stations, returns square root of (value * ampli...
Definition tcmgr.cpp:67
Tide and Current Manager @TODO Add original author copyright.