File: tide_db.c

package info (click to toggle)
libtcd 2.2.2-2
  • links: PTS
  • area: main
  • in suites: stretch
  • size: 1,672 kB
  • ctags: 268
  • sloc: sh: 8,820; ansic: 3,795; makefile: 56
file content (5495 lines) | stat: -rw-r--r-- 171,032 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
/* $Id: tide_db.c 1803 2007-01-22 15:29:56Z flaterco $ */

#include "tcd.h"
#include "tide_db_header.h"
#include "tide_db_default.h"

#ifndef require
#define require(expr) {       \
  int require_expr;           \
  require_expr = (int)(expr); \
  assert (require_expr);      \
}
#endif

#ifdef NDEBUG
#warning NDEBUG is defined.  This configuration is unsupported and discouraged.
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <math.h>
#include <ctype.h>
#include <unistd.h>
#include <assert.h>


/*****************************************************************************\

                            DISTRIBUTION STATEMENT

    This source file is unclassified, distribution unlimited, public
    domain.  It is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

\*****************************************************************************/



/* Some of the following commentary is out of date.  See the new
   documentation in libtcd.html. */

/*****************************************************************************\

    Tide Constituent Database API


    Author  : Jan C. Depner (depnerj@navo.navy.mil)

    Date    : 08/01/02
              (First day of Micro$oft's "Licensing 6" policy - P.T. Barnum was
              right!!!)

    Purpose : To replace the ASCII/XML formatted harmonic constituent data
              files, used in Dave Flater's (http://www.flaterco.com/xtide/)
              exceptionally fine open-source XTide program, with a fast,
              efficient binary format.  In addition, we wanted to replace the
              Naval Oceanographic Office's (http://www.navo.navy.mil)
              antiquated ASCII format harmonic constituent data file due to
              problems with configuration management of the file.  The
              resulting database will become a Navy OAML (Oceanographic and
              Atmospheric Master Library) standard harmonic tide constituent
              database.

    Design  : The following describes the database file and some of the
              rationale behind the design.

    First question - Why didn't I use PostgreSQL or MySQL?  Mostly
    portability.  What?  PostgreSQL runs on everything!  Yes, but it doesn't
    come installed on everything.  This would have meant that the poor,
    benighted Micro$oft borgs would have had to actually load a software
    package.  In addition, the present harmonics/offset files only contain
    a total of 6,409 stations.  It hardly seemed worth the effort (or overhead)
    of a fullblown RDBMS to handle this.  Second question - Why binary and not
    ASCII or XML?  This actually gets into philosophy.  At NAVO we have used an
    ASCII harmonic constituent file for years (we were founded in 1830 and I
    think that that's when they designed the file).  We have about fifty
    million copies floating around and each one is slightly different.  Why?
    Because they're ASCII and everyone thinks they know what they're doing so
    they tend to modify the file.  Same problem with XML, it's still ASCII.
    We wanted a file that people weren't going to mess with and that we could
    version control.  We also wanted a file that was small and fast.  This is
    very difficult to do with ASCII.  The big slowdown with the old format
    was I/O and parsing.  Third question - will it run on any OS?  Hopefully,
    yes.  After twenty-five years of working with low bidder systems I've
    worked on almost every OS known to man.  Once you've been bitten by big
    endian vs little endian or IEEE floating point format vs VAX floating
    point format or byte addressable memory vs word addressable memory or 32
    bit word vs 36 bit word vs 48 bit word vs 64 bit word sizes you get the
    message.  All of the data in the file is stored either as ASCII text or
    scaled integers (32 bits or smaller), bit-packed and stuffed into an
    unsigned character buffer for I/O.  No endian issues, no floating point
    issues, no word size issues, no memory mapping issues.  I will be testing
    this on x86 Linux, HP-UX, and Micro$oft Windoze.  By the time you read
    this it will be portable to those systems at least.

    Now, on to the file layout.  As much as I dislike ASCII it is occasionally
    handy to be able to see some information about a file without having to
    resort to a special purpose program.  With that in mind I made the first
    part of the header of the file ASCII.  The following is an example of the
    ASCII portion of the header:

        [VERSION] = PFM Software - tide_db V1.00 - 08/01/02
        [LAST MODIFIED] = Thu Aug  1 02:46:29 2002
        [HEADER SIZE] = 4096
        [NUMBER OF RECORDS] = 10652
        [START YEAR] = 1970
        [NUMBER OF YEARS] = 68
        [SPEED BITS] = 31
        [SPEED SCALE] = 10000000
        [SPEED OFFSET] = -410667
        [EQUILIBRIUM BITS] = 16
        [EQUILIBRIUM SCALE] = 100
        [EQUILIBRIUM OFFSET] = 0
        [NODE BITS] = 15
        [NODE SCALE] = 10000
        [NODE OFFSET] = -3949
        [AMPLITUDE BITS] = 19
        [AMPLITUDE SCALE] = 10000
        [EPOCH BITS] = 16
        [EPOCH SCALE] = 100
        [RECORD TYPE BITS] = 4
        [LATITUDE BITS] = 25
        [LATITUDE SCALE] = 100000
        [LONGITUDE BITS] = 26
        [LONGITUDE SCALE] = 100000
        [RECORD SIZE BITS] = 12
        [STATION BITS] = 18
        [DATUM OFFSET BITS] = 32
        [DATUM OFFSET SCALE] = 10000
        [DATE BITS] = 27
        [MONTHS ON STATION BITS] = 10
        [CONFIDENCE VALUE BITS] = 4
        [TIME BITS] = 13
        [LEVEL ADD BITS] = 16
        [LEVEL ADD SCALE] = 100
        [LEVEL MULTIPLY BITS] = 16
        [LEVEL MULTIPLY SCALE] = 1000
        [DIRECTION BITS] = 9
        [LEVEL UNIT BITS] = 3
        [LEVEL UNIT TYPES] = 6
        [LEVEL UNIT SIZE] = 15
        [DIRECTION UNIT BITS] = 2
        [DIRECTION UNIT TYPES] = 3
        [DIRECTION UNIT SIZE] = 15
        [RESTRICTION BITS] = 4
        [RESTRICTION TYPES] = 2
        [RESTRICTION SIZE] = 30
        [PEDIGREE BITS] = 6
        [PEDIGREE TYPES] = 13
        [PEDIGREE SIZE] = 60
        [DATUM BITS] = 7
        [DATUM TYPES] = 61
        [DATUM SIZE] = 70
        [CONSTITUENT BITS] = 8
        [CONSTITUENTS] = 173
        [CONSTITUENT SIZE] = 10
        [COUNTRY BITS] = 9
        [COUNTRIES] = 240
        [COUNTRY SIZE] = 50
        [TZFILE BITS] = 10
        [TZFILES] = 449
        [TZFILE SIZE] = 30
        [END OF FILE] = 2585170
        [END OF ASCII HEADER DATA]

    Most of these values will make sense in the context of the following
    description of the rest of the file.  Some caveats on the data storage -
    if no SCALE is listed for a field, the scale is 1.  If no BITS field is
    listed, this is a variable length character field and is stored as 8 bit
    ASCII characters.  If no OFFSET is listed, the offset is 0.  Offsets are
    scaled.  All SIZE fields refer to the maximum length, in characters, of a
    variable length character field.  Some of the BITS fields are calculated
    while others are hardwired (see code).  For instance, [DIRECTION BITS] is
    hardwired because it is an integer field whose value can only be from 0 to
    361 (361 = no direction flag).  [NODE BITS], on the other hand, is
    calculated on creation by checking the min, max, and range of all of the
    node factor values.  The number of bits needed is easily calculated by
    taking the log of the adjusted, scaled range, dividing by the log of 2 and
    adding 1.  Immediately following the ASCII portion of the header is a 32
    bit checksum of the ASCII portion of the header.  Why?  Because some
    genius always gets the idea that he/she can modify the header with a text
    or hex editor.  Go figure.

    The rest of the header is as follows :

        [LEVEL UNIT TYPES] fields of [LEVEL UNIT SIZE] characters, each field
            is internally 0 terminated (anything after the zero is garbage)

        [DIRECTION UNIT TYPES] fields of [DIRECTION UNIT SIZE] characters, 0
            terminated

        [RESTRICTION TYPES] fields of [RESTRICTION SIZE] characters, 0
            terminated

        [PEDIGREE TYPES] fields of [PEDIGREE SIZE] characters, 0 terminated

        [TZFILES] fields of [TZFILE SIZE] characters, 0 terminated

        [COUNTRIES] fields of [COUNTRY SIZE] characters, 0 terminated

        [DATUM TYPES] fields of [DATUM SIZE] characters, 0 terminated

        [CONSTITUENTS] fields of [CONSTITUENT SIZE] characters, 0 terminated
            Yes, I know, I wasted some space with these fields but I wasn't
            worried about a couple of hundred bytes.

        [CONSTITUENTS] fields of [SPEED BITS], speed values (scaled and offset)

        [CONSTITUENTS] groups of [NUMBER OF YEARS] fields of
            [EQUILIBRIUM BITS], equilibrium arguments (scaled and offset)

        [CONSTITUENTS] groups of [NUMBER OF YEARS] fields of [NODE BITS], node
            factors (scaled and offset)


    Finally, the data.  At present there are two types of records in the file.
    These are reference stations (record type 1) and subordinate stations
    (record type 2).  Reference stations contain a set of constituents while
    subordinate stations contain a number of offsets to be applied to the
    reference station that they are associated with.  Note that reference
    stations (record type 1) may, in actuality, be subordinate stations, albeit
    with a set of constituents.  All of the records have the following subset
    of information stored as the first part of the record:

        [RECORD SIZE BITS] - record size in bytes
        [RECORD TYPE BITS] - record type (1 or 2)
        [LATITUDE BITS] - latitude (degrees, south negative, scaled & offset)
        [LONGITUDE BITS] - longitude (degrees, west negative, scaled & offset)
        [TZFILE BITS] - index into timezone array (retrieved from header)
        variable size - station name, 0 terminated
        [STATION BITS] - record number of reference station or -1
        [COUNTRY_BITS] index into country array (retrieved from header)
        [PEDIGREE BITS] - index into pedigree array (retrieved from header)
        variable size - source, 0 terminated
        [RESTRICTION BITS] - index into restriction array
        variable size - comments, may contain LFs to indicate newline (no CRs)


    These are the rest of the fields for record type 1:

        [LEVEL UNIT BITS] - index into level units array
        [DATUM OFFSET BITS] - datum offset (scaled)
        [DATUM BITS] - index into datum name array
        [TIME BITS] - time zone offset from GMT0 (meridian, integer +/-HHMM)
        [DATE BITS] - expiration date, (integer YYYYMMDD, default is 0)
        [MONTHS ON STATION BITS] - months on station
        [DATE BITS] - last date on station, default is 0
        [CONFIDENCE BITS] - confidence value (TBD)
        [CONSTITUENT BITS] - "N", number of constituents for this station

        N groups of:
            [CONSTITUENT BITS] - constituent number
            [AMPLITUDE BITS] - amplitude (scaled & offset)
            [EPOCH BITS] - epoch (scaled & offset)


    These are the rest of the fields for record type 2:

        [LEVEL UNIT BITS] - leveladd units, index into level_units array
        [DIRECTION UNIT BITS] - direction units, index into dir_units array
        [LEVEL UNIT BITS] - avglevel units, index into level_units array
        [TIME BITS] - min timeadd (integer +/-HHMM) or 0
        [LEVEL ADD BITS] - min leveladd (scaled) or 0
        [LEVEL MULTIPLY BITS] - min levelmultiply (scaled) or 0
        [LEVEL ADD BITS] - min avglevel (scaled) or 0
        [DIRECTION BITS] - min direction (0-360 or 361 for no direction)
        [TIME BITS] - max timeadd (integer +/-HHMM) or 0
        [LEVEL ADD BITS] - max leveladd (scaled) or 0
        [LEVEL MULTIPLY BITS] - max levelmultiply (scaled) or 0
        [LEVEL ADD BITS] - max avglevel (scaled) or 0
        [DIRECTION BITS] - max direction (0-360 or 361 for no direction)
        [TIME BITS] - floodbegins (integer +/-HHMM) or NULLSLACKOFFSET
        [TIME BITS] - ebbbegins (integer +/-HHMM) or NULLSLACKOFFSET


    Back to philosophy!  When you design a database of any kind the first
    thing you should ask yourself is "Self, how am I going to access this
    data most of the time?".  If you answer yourself out loud you should
    consider seeing a shrink.  99 and 44/100ths percent of the time this
    database is going to be read to get station data.  The other 66/100ths
    percent of the time it will be created/modified.  Variable length records
    are no problem on retrieval.  They are no problem to create.  They can be
    a major pain in the backside if you have to modify/delete them.  Since we
    shouldn't be doing too much editing of the data (usually just adding
    records) this is a pretty fair design.  At some point though we are going
    to want to modify or delete a record.  There are two possibilities here.
    We can dump the database to an ASCII file or files using restore_tide_db,
    use a text editor to modify them, and then rebuild the database.  The
    other possibility is to modify the record in place.  This is OK if you
    don't change a variable length field but what if you want to change the
    station name or add a couple of constituents?  With the design as is we
    have to read the remainder of the file from the end of the record to be
    modified, write the modified record, rewrite the remainder of the file,
    and then change the end_of_file pointer in the header.  So, which fields
    are going to be a problem?  Changes to station name, source, comments, or
    the number of constituents for a station will require a resizing of the
    database.  Changes to any of the other fields can be done in place.  The
    worst thing that you can do though is to delete a record.  Not just
    because the file has to be resized but because it might be a reference
    record with subordinate stations.  These would have to be deleted as well.
    The delete_tide_record function will do just that so make sure you check
    before you call it.  You might not want to do that.

    Another point to note is that when you open the database the records are
    indexed at that point.  This takes about half a second on a dual 450.
    Most applications use the header part of the record very often and
    the rest of the record only if they are going to actually produce
    predicted tides.  For instance, XTide plots all of the stations on a
    world map or globe and lists all of the station names.  It also needs the
    timezone up front.  To save re-indexing to get these values I save them
    in memory.  The only time an application needs to actually read an entire
    record is when you want to do the prediction.  Otherwise just use
    get_partial_tide_record or get_next_partial_tide_record to yank the good
    stuff out of memory.

    'Nuff said?


    See libtcd.html for changelog.

\*****************************************************************************/

/* Maintenance by DWF */


/*  Function prototypes.  */

NV_U_INT32 calculate_bits (NV_U_INT32 value);
void bit_pack (NV_U_BYTE *, NV_U_INT32, NV_U_INT32, NV_INT32);
NV_U_INT32 bit_unpack (NV_U_BYTE *, NV_U_INT32, NV_U_INT32);
NV_INT32 signed_bit_unpack (NV_U_BYTE buffer[], NV_U_INT32 start,
                            NV_U_INT32 numbits);



/*  Global variables.  */

typedef struct
{
    NV_INT32                address;
    NV_U_INT32              record_size;
    NV_U_INT16              tzfile;
    NV_INT32                reference_station;
    NV_INT32                lat;
    NV_INT32                lon;
    NV_U_BYTE               record_type;
    NV_CHAR                 *name;
} TIDE_INDEX;


static FILE                 *fp = NULL;
static TIDE_INDEX           *tindex = NULL;
static NV_BOOL              modified = NVFalse;
static NV_INT32             current_record, current_index;
static NV_CHAR              filename[MONOLOGUE_LENGTH];


/*****************************************************************************\

    Function        dump_tide_record - prints out all of the fields in the
                    input tide record

    Synopsis        dump_tide_record (rec);

                    TIDE_RECORD *rec        pointer to the tide record

    Returns         void

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

void dump_tide_record (TIDE_RECORD *rec)
{
    NV_U_INT32              i;

    assert (rec);

    fprintf (stderr, "\n\nRecord number = %d\n", rec->header.record_number);
    fprintf (stderr, "Record size = %u\n", rec->header.record_size);
    fprintf (stderr, "Record type = %u\n", rec->header.record_type);
    fprintf (stderr, "Latitude = %f\n", rec->header.latitude);
    fprintf (stderr, "Longitude = %f\n", rec->header.longitude);
    fprintf (stderr, "Reference station = %d\n",
        rec->header.reference_station);
    fprintf (stderr, "Tzfile = %s\n", get_tzfile (rec->header.tzfile));
    fprintf (stderr, "Name = %s\n", rec->header.name);

    fprintf (stderr, "Country = %s\n", get_country (rec->country));
    fprintf (stderr, "Source = %s\n", rec->source);
    fprintf (stderr, "Restriction = %s\n", get_restriction (rec->restriction));
    fprintf (stderr, "Comments = %s\n", rec->comments);
    fprintf (stderr, "Notes = %s\n", rec->notes);
    fprintf (stderr, "Legalese = %s\n",
        get_legalese (rec->legalese));
    fprintf (stderr, "Station ID context = %s\n", rec->station_id_context);
    fprintf (stderr, "Station ID = %s\n", rec->station_id);
    fprintf (stderr, "Date imported = %d\n", rec->date_imported);
    fprintf (stderr, "Xfields = %s\n", rec->xfields);

    fprintf (stderr, "Direction units = %s\n",
        get_dir_units (rec->direction_units));
    fprintf (stderr, "Min direction = %d\n", rec->min_direction);
    fprintf (stderr, "Max direction = %d\n", rec->max_direction);
    fprintf (stderr, "Level units = %s\n", get_level_units (rec->level_units));

    if (rec->header.record_type == REFERENCE_STATION)
    {
        fprintf (stderr, "Datum offset = %f\n", rec->datum_offset);
        fprintf (stderr, "Datum = %s\n", get_datum (rec->datum));
        fprintf (stderr, "Zone offset = %d\n", rec->zone_offset);
        fprintf (stderr, "Expiration date = %d\n", rec->expiration_date);
        fprintf (stderr, "Months on station = %d\n", rec->months_on_station);
        fprintf (stderr, "Last date on station = %d\n",
            rec->last_date_on_station);
        fprintf (stderr, "Confidence = %d\n", rec->confidence);
        for (i = 0 ; i < hd.pub.constituents ; ++i)
        {
            if (rec->amplitude[i] != 0.0 || rec->epoch[i] != 0.0)
            {
                fprintf (stderr, "Amplitude[%d] = %f\n", i, rec->amplitude[i]);
                fprintf (stderr, "Epoch[%d] = %f\n", i, rec->epoch[i]);
            }
        }
    }

    else if (rec->header.record_type == SUBORDINATE_STATION)
    {
        fprintf (stderr, "Min time add = %d\n", rec->min_time_add);
        fprintf (stderr, "Min level add = %f\n", rec->min_level_add);
        fprintf (stderr, "Min level multiply = %f\n", rec->min_level_multiply);
        fprintf (stderr, "Max time add = %d\n", rec->max_time_add);
        fprintf (stderr, "Max level add = %f\n", rec->max_level_add);
        fprintf (stderr, "Max level multiply = %f\n", rec->max_level_multiply);
        fprintf (stderr, "Flood begins = %d\n", rec->flood_begins);
        fprintf (stderr, "Ebb begins = %d\n", rec->ebb_begins);
    }
}


/*****************************************************************************\

    Function        write_protect - prevent trying to modify TCD files of
                    an earlier version.  Nothing to do with file locking.

    David Flater, 2004-10-14.

\*****************************************************************************/

static void write_protect () {
  if (hd.pub.major_rev < LIBTCD_MAJOR_REV) {
    fprintf (stderr, "libtcd error: can't modify TCD files created by earlier version.  Use\nrewrite_tide_db to upgrade the TCD file.\n");
    exit (-1);
  }
}


/*****************************************************************************\

    Function        get_country - gets the country field for record "num"

    Synopsis        get_country (num);

                    NV_INT32 num            tide record number

    Returns         NV_CHAR *               country name (associated with
                                            ISO 3166-1:1999 2-character
                                            country code

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_CHAR *get_country (NV_INT32 num)
{
  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit(-1);
  }
  if (num >= 0 && num < (NV_INT32)hd.pub.countries) return (hd.country[num]);
  return ("Unknown");
}


/*****************************************************************************\

    Function        get_tzfile - gets the time zone name for record "num"

    Synopsis        get_tzfile (num);

                    NV_INT32 num            tide record number

    Returns         NV_CHAR *               time zone name used in TZ variable

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_CHAR *get_tzfile (NV_INT32 num)
{
  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit(-1);
  }
  if (num >= 0 && num < (NV_INT32)hd.pub.tzfiles) return (hd.tzfile[num]);
  return ("Unknown");
}


/*****************************************************************************\

    Function        get_station - get the name of the station for record "num"

    Synopsis        get_station (num);

                    NV_INT32 num            tide record number

    Returns         NV_CHAR *               station name

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_CHAR *get_station (NV_INT32 num)
{
  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit(-1);
  }
  if (num >= 0 && num < (NV_INT32)hd.pub.number_of_records) return (tindex[num].name);
  return ("Unknown");
}


/*****************************************************************************\

    Function        get_constituent - get the constituent name for constituent
                    number "num"

    Synopsis        get_constituent (num);

                    NV_INT32 num            constituent number

    Returns         NV_CHAR *               constituent name

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_CHAR *get_constituent (NV_INT32 num)
{
  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit(-1);
  }
  if (num >= 0 && num < (NV_INT32)hd.pub.constituents) return (hd.constituent[num]);
  return ("Unknown");
}


/*****************************************************************************\

    Function        get_level_units - get the level units for level units
                    number "num"

    Synopsis        get_level_units (num);

                    NV_INT32 num            level units number

    Returns         NV_CHAR *               units (ex. "meters");

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_CHAR *get_level_units (NV_INT32 num)
{
  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit(-1);
  }
  if (num >= 0 && num < (NV_INT32)hd.pub.level_unit_types) return (hd.level_unit[num]);
  return ("Unknown");
}


/*****************************************************************************\

    Function        get_dir_units - get the direction units for direction
                    units number "num"

    Synopsis        get_dir_units (num);

                    NV_INT32 num            direction units number

    Returns         NV_CHAR *               units (ex. "degrees true");

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_CHAR *get_dir_units (NV_INT32 num)
{
  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit(-1);
  }
  if (num >= 0 && num < (NV_INT32)hd.pub.dir_unit_types) return (hd.dir_unit[num]);
  return ("Unknown");
}


/*****************************************************************************\

    Function        get_restriction - gets the restriction description for
                    restriction number "num"

    Synopsis        get_restriction (num);

                    NV_INT32 num            restriction number

    Returns         NV_CHAR *               restriction (ex. "PUBLIC DOMAIN");

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_CHAR *get_restriction (NV_INT32 num)
{
  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit(-1);
  }
  if (num >= 0 && num < (NV_INT32)hd.pub.restriction_types)
      return (hd.restriction[num]);
  return ("Unknown");
}


/*****************************************************************************\

    Function        get_pedigree - gets the pedigree description for pedigree
                    number "num"

    Synopsis        get_pedigree (num);

                    NV_INT32 num            pedigree number

    Returns         NV_CHAR *               pedigree description

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

#ifdef COMPAT114
NV_CHAR *get_pedigree (NV_INT32 num) {
  return "Unknown";
}
#endif


/*****************************************************************************\

    Function        get_datum - gets the datum name for datum number "num"

    Synopsis        get_datum (num);

                    NV_INT32 num            datum number

    Returns         NV_CHAR *               datum name

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_CHAR *get_datum (NV_INT32 num)
{
  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit(-1);
  }
  if (num >= 0 && num < (NV_INT32)hd.pub.datum_types) return (hd.datum[num]);
  return ("Unknown");
}


/*****************************************************************************\
DWF 2004-10-14
\*****************************************************************************/
NV_CHAR *get_legalese (NV_INT32 num)
{
  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit(-1);
  }
  if (num >= 0 && num < (NV_INT32)hd.pub.legaleses) return (hd.legalese[num]);
  return ("Unknown");
}


/*****************************************************************************\

    Function        get_speed - gets the speed value for constituent number
                    "num"

    Synopsis        get_speed (num);

                    NV_INT32 num            constituent number

    Returns         NV_FLOAT64              speed

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_FLOAT64 get_speed (NV_INT32 num)
{
  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit(-1);
  }
  assert (num >= 0 && num < (NV_INT32)hd.pub.constituents);
  return hd.speed[num];
}


/*****************************************************************************\

    Function        get_equilibrium - gets the equilibrium value for
                    constituent number "num" and year "year"

    Synopsis        get_equilibrium (num, year);

                    NV_INT32 num            constituent number
                    NV_INT32 year           year

    Returns         NV_FLOAT32              equilibrium argument

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_FLOAT32 get_equilibrium (NV_INT32 num, NV_INT32 year)
{
  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit(-1);
  }
  assert (num >= 0 && num < (NV_INT32)hd.pub.constituents && year >= 0 && year < (NV_INT32)hd.pub.number_of_years);
  return hd.equilibrium[num][year];
}


/*****************************************************************************\
  DWF 2004-10-04
\*****************************************************************************/
NV_FLOAT32 *get_equilibriums (NV_INT32 num) {
  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit(-1);
  }
  assert (num >= 0 && num < (NV_INT32)hd.pub.constituents);
  return hd.equilibrium[num];
}


/*****************************************************************************\

    Function        get_node_factor - gets the node factor value for
                    constituent number "num" and year "year"

    Synopsis        get_node_factor (num, year);

                    NV_INT32 num            constituent number
                    NV_INT32 year           year

    Returns         NV_FLOAT32              node factor

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_FLOAT32 get_node_factor (NV_INT32 num, NV_INT32 year)
{
  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit(-1);
  }
  assert (num >= 0 && num < (NV_INT32)hd.pub.constituents && year >= 0 && year < (NV_INT32)hd.pub.number_of_years);
  return hd.node_factor[num][year];
}


/*****************************************************************************\
  DWF 2004-10-04
\*****************************************************************************/
NV_FLOAT32 *get_node_factors (NV_INT32 num) {
  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit(-1);
  }
  assert (num >= 0 && num < (NV_INT32)hd.pub.constituents);
  return hd.node_factor[num];
}


/*****************************************************************************\

    Function        get_partial_tide_record - gets "header" portion of record
                    "num" from the index that is stored in memory.  This is
                    way faster than reading it again and we have to read it
                    to set up the index.  This costs a bit in terms of
                    memory but most applications use this data far more than
                    the rest of the record.

    Synopsis        get_partial_tide_record (num, rec);

                    NV_INT32 num              record number
                    TIDE_STATION_HEADER *rec  header portion of the record

    Returns         NV_BOOL                   NVTrue if successful

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_BOOL get_partial_tide_record (NV_INT32 num, TIDE_STATION_HEADER *rec)
{
  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    return NVFalse;
  }

    if (num < 0 || num >= (NV_INT32)hd.pub.number_of_records) return (NVFalse);

    assert (rec);

    rec->record_number = num;
    rec->record_size = tindex[num].record_size;
    rec->record_type = tindex[num].record_type;
    rec->latitude = (NV_FLOAT64) tindex[num].lat / hd.latitude_scale;
    rec->longitude = (NV_FLOAT64) tindex[num].lon / hd.longitude_scale;
    rec->reference_station = tindex[num].reference_station;
    rec->tzfile = tindex[num].tzfile;
    strcpy (rec->name, tindex[num].name);

    current_index = num;

    return (NVTrue);
}


/*****************************************************************************\

    Function        get_next_partial_tide_record - gets "header" portion of
                    the next record from the index that is stored in memory.

    Synopsis        get_next_partial_tide_record (rec);

                    TIDE_STATION_HEADER *rec  header portion of the record

    Returns         NV_INT32                  record number or -1 on failure

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_INT32 get_next_partial_tide_record (TIDE_STATION_HEADER *rec)
{
    if (!get_partial_tide_record (current_index + 1, rec)) return (-1);

    return (current_index);
}


/*****************************************************************************\

    Function        get_nearest_partial_tide_record - gets "header" portion of
                    the record closest geographically to the input position.

    Synopsis        get_nearest_partial_tide_record (lat, lon, rec);

                    NV_FLOAT64 lat            latitude
                    NV_FLOAT64 lon            longitude
                    TIDE_STATION_HEADER *rec  header portion of the record

    Returns         NV_INT32                  record number or -1 on failure

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_INT32 get_nearest_partial_tide_record (NV_FLOAT64 lat, NV_FLOAT64 lon,
TIDE_STATION_HEADER *rec)
{
    NV_FLOAT64           diff, min_diff, lt, ln;
    NV_U_INT32             i, shortest = 0;

    min_diff = 999999999.9;
    for (i = 0 ; i < hd.pub.number_of_records ; ++i)
    {
        lt = (NV_FLOAT64) tindex[i].lat / hd.latitude_scale;
        ln = (NV_FLOAT64) tindex[i].lon / hd.longitude_scale;

        diff = sqrt ((lat - lt) * (lat - lt) + (lon - ln) * (lon - ln));

        if (diff < min_diff)
        {
            min_diff = diff;
            shortest = i;
        }
    }

    if (!get_partial_tide_record (shortest, rec)) return (-1);
    return (shortest);
}


/*****************************************************************************\

    Function        get_time - converts a time string in +/-HH:MM form to an
                    integer in +/-HHMM form

    Synopsis        get_time (string);

                    NV_CHAR *string         time string

    Returns         NV_INT32                time

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_INT32 get_time (NV_CHAR *string)
{
    NV_INT32        hour, minute, hhmm;

    assert (string);
    sscanf (string, "%d:%d", &hour, &minute);


    /*  Trying to deal with negative 0 (-00:45).  */

    if (string[0] == '-')
    {
        if (hour < 0) hour = -hour;

        hhmm = -(hour * 100 + minute);
    }
    else
    {
        hhmm = hour * 100 + minute;
    }

    return (hhmm);
}


/*****************************************************************************\

    Function        ret_time - converts a time value in +/-HHMM form to a
                    time string in +/-HH:MM form

    Synopsis        ret_time (time);

                    NV_INT32                time

    Returns         NV_CHAR *               time string

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_CHAR *ret_time (NV_INT32 time)
{
    NV_INT32          hour, minute;
    static NV_CHAR    tname[10];

    hour = abs (time) / 100;
    assert (hour < 100000); /* 9 chars: +99999:99 */
    minute = abs (time) % 100;

    if (time < 0)
    {
        sprintf (tname, "-%02d:%02d", hour, minute);
    }
    else
    {
        sprintf (tname, "+%02d:%02d", hour, minute);
    }

    return tname;
}


/*****************************************************************************\
  DWF 2004-10-04
\*****************************************************************************/
NV_CHAR *ret_time_neat (NV_INT32 time)
{
    NV_INT32          hour, minute;
    static NV_CHAR    tname[10];

    hour = abs (time) / 100;
    assert (hour < 100000); /* 9 chars: +99999:99 */
    minute = abs (time) % 100;

    if (time < 0)
      sprintf (tname, "-%d:%02d", hour, minute);
    else if (time > 0)
      sprintf (tname, "+%d:%02d", hour, minute);
    else
      strcpy (tname, "0:00");

    return tname;
}


/*****************************************************************************\
  DWF 2004-10-04
\*****************************************************************************/
NV_CHAR *ret_date (NV_U_INT32 date) {
  static NV_CHAR tname[30];
  if (!date)
    strcpy (tname, "NULL");
  else {
    unsigned y, m, d;
    y = date / 10000;
    date %= 10000;
    m = date / 100;
    d = date % 100;
    sprintf (tname, "%4u-%02u-%02u", y, m, d);
  }
  return tname;
}


/*****************************************************************************\

    Function        get_tide_db_header - gets the public portion of the tide
                    database header

    Synopsis        get_tide_db_header ();

    Returns         DB_HEADER_PUBLIC        public tide header

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

DB_HEADER_PUBLIC get_tide_db_header ()
{
  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit(-1);
  }
    return (hd.pub);
}


/*****************************************************************************\
   DWF 2004-09-30
   Prevent buffer overflows for MONOLOGUE_LENGTH strings.
\*****************************************************************************/
static void boundscheck_monologue (NV_CHAR *string) {
  assert (string);
  if (strlen(string) >= MONOLOGUE_LENGTH) {
    fprintf (stderr, "libtcd fatal error:  static buffer size exceeded\n");
    fprintf (stderr, "Buffer is size MONOLOGUE_LENGTH (%u)\n",
             MONOLOGUE_LENGTH);
    fprintf (stderr, "String is length %u\n", strlen(string));
    fprintf (stderr, "The offending string is:\n%s\n", string);
    exit (-1);
  }
}


/*****************************************************************************\
   DWF 2004-09-30
   Prevent buffer overflows for ONELINER_LENGTH strings.
\*****************************************************************************/
static void boundscheck_oneliner (NV_CHAR *string) {
  assert (string);
  if (strlen(string) >= ONELINER_LENGTH) {
    fprintf (stderr, "libtcd fatal error:  static buffer size exceeded\n");
    fprintf (stderr, "Buffer is size ONELINER_LENGTH (%u)\n",
             ONELINER_LENGTH);
    fprintf (stderr, "String is length %u\n", strlen(string));
    fprintf (stderr, "The offending string is:\n%s\n", string);
    exit (-1);
  }
}


/*****************************************************************************\

    Function        clip_string - removes leading and trailing spaces from
                    search strings.

    Synopsis        clip_string (string);

                    NV_CHAR *string         search string

    Returns         NV_CHAR *               clipped string

    Author          Jan C. Depner
    Date            09/16/02

    See libtcd.html for changelog.

\*****************************************************************************/

static NV_CHAR *clip_string (NV_CHAR *string)
{
  static NV_CHAR        new_string[MONOLOGUE_LENGTH];
  NV_INT32              i, l, start = -1, end = -1;

  boundscheck_monologue (string);
  new_string[0] = '\0';

  l = (int)strlen(string);
  if (l) {
    for (i=0; i<l; ++i) {
      if (string[i] != ' ') {
        start = i;
        break;
      }
    }
    for (i=l-1; i >= start; --i) {
      if (string[i] != ' ' && string[i] != 10 && string[i] != 13) {
        end = i;
        break;
      }
    }
    if (start > -1 && end > -1 && end >= start) {
      strncpy (new_string, string+start, end-start+1);
      new_string[end-start+1] = '\0';
    }
  }
  return new_string;
}


/*****************************************************************************\

    Function        search_station - returns record numbers of all stations
                    that have the string "string" anywhere in the station
                    name.  This search is case insensitive.  When no more
                    records are found it returns -1;

    Synopsis        search_station (string);

                    NV_CHAR *string         search string

    Returns         NV_INT32                record number or -1 when no more
                                            matches

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_INT32 search_station (NV_CHAR *string)
{
    static NV_CHAR        last_search[ONELINER_LENGTH];
    static NV_U_INT32     j=0;
    NV_U_INT32            i;
    NV_CHAR               name[ONELINER_LENGTH], search[ONELINER_LENGTH];

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    return -1;
  }

    boundscheck_oneliner (string);

    for (i = 0 ; i < strlen(string) + 1 ; ++i)
        search[i] = tolower (string[i]);

    if (strcmp (search, last_search)) j = 0;

    strcpy (last_search, search);

    while (j < hd.pub.number_of_records)
    {
        for (i = 0 ; i < strlen(tindex[j].name) + 1 ; ++i)
            name[i] = tolower (tindex[j].name[i]);

        ++j;
        if (strstr (name, search))
          return (j - 1);
    }

    j = 0;
    return -1;
}


/*****************************************************************************\

    Function        find_station - finds the record number of the station
                    that has name "name"

    Synopsis        find_station (name);

                    NV_CHAR *name           station name

    Returns         NV_INT32                record number

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_INT32 find_station (NV_CHAR *name)
{
    NV_U_INT32              i;

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    return -1;
  }

    assert (name);
    for (i = 0 ; i < hd.pub.number_of_records ; ++i)
    {
        if (!strcmp (name, tindex[i].name)) return (i);
    }

    return (-1);
}


/*****************************************************************************\

    Function        find_tzfile - gets the timezone number (index into
                    tzfile array) given the tzfile name

    Synopsis        find_tzfile (name);

                    NV_CHAR *name          tzfile name

    Returns         NV_INT32                tzfile number

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_INT32 find_tzfile (NV_CHAR *name)
{
    NV_INT32   j;
    NV_U_INT32 i;
    NV_CHAR     *temp;

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    return -1;
  }

    temp = clip_string(name);

    j = -1;
    for (i = 0 ; i < hd.pub.tzfiles ; ++i)
    {
        if (!strcmp (temp, get_tzfile (i)))
        {
            j = i;
            break;
        }
    }

    return (j);
}


/*****************************************************************************\

    Function        find_country - gets the timezone number (index into
                    country array) given the country name

    Synopsis        find_country (name);

                    NV_CHAR *name          country name

    Returns         NV_INT32                country number

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_INT32 find_country (NV_CHAR *name)
{
    NV_INT32    j;
    NV_U_INT32  i;
    NV_CHAR     *temp;

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    return -1;
  }

    temp = clip_string(name);

    j = -1;
    for (i = 0 ; i < hd.pub.countries ; ++i)
    {
        if (!strcmp (temp, get_country (i)))
        {
            j = i;
            break;
        }
    }

    return (j);
}


/*****************************************************************************\

    Function        find_level_units - gets the index into the level_units
                    array given the level units name

    Synopsis        find_level_units (name);

                    NV_CHAR *name          units name (ex. "meters")

    Returns         NV_INT32                units number

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_INT32 find_level_units (NV_CHAR *name)
{
    NV_INT32    j;
    NV_U_INT32  i;
    NV_CHAR     *temp;

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    return -1;
  }

    temp = clip_string(name);

    j = -1;
    for (i = 0 ; i < hd.pub.level_unit_types ; ++i)
    {
        if (!strcmp (get_level_units (i), temp))
        {
            j = i;
            break;
        }
    }

    return (j);
}


/*****************************************************************************\

    Function        find_dir_units - gets the index into the dir_units
                    array given the direction units name

    Synopsis        find_dir_units (name);

                    NV_CHAR *name          units name (ex. "degrees true")

    Returns         NV_INT32                units number

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_INT32 find_dir_units (NV_CHAR *name)
{
    NV_INT32    j;
    NV_U_INT32  i;
    NV_CHAR     *temp;

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    return -1;
  }

    temp = clip_string(name);

    j = -1;
    for (i = 0 ; i < hd.pub.dir_unit_types ; ++i)
    {
        if (!strcmp (get_dir_units (i), temp))
        {
            j = i;
            break;
        }
    }

    return (j);
}


/*****************************************************************************\

    Function        find_pedigree - gets the index into the pedigree array
                    given the pedigree name

    Synopsis        find_pedigree (name);

                    NV_CHAR *name          pedigree name

    Returns         NV_INT32                pedigree number

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

#ifdef COMPAT114
NV_INT32 find_pedigree (NV_CHAR *name) {
  return 0;
}
#endif


/*****************************************************************************\

    Function        find_datum - gets the index into the datum array given the
                    datum name

    Synopsis        find_datum (name);

                    NV_CHAR *name          datum name

    Returns         NV_INT32                datum number

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_INT32 find_datum (NV_CHAR *name)
{
    NV_INT32    j;
    NV_U_INT32  i;
    NV_CHAR     *temp;

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    return -1;
  }

    temp = clip_string(name);

    j = -1;
    for (i = 0 ; i < hd.pub.datum_types ; ++i)
    {
        if (!strcmp (get_datum (i), temp))
        {
            j = i;
            break;
        }
    }

    return (j);
}


/*****************************************************************************\
  DWF 2004-10-14
\*****************************************************************************/
NV_INT32 find_legalese (NV_CHAR *name)
{
  NV_INT32    j;
  NV_U_INT32  i;
  NV_CHAR     *temp;

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    return -1;
  }

  temp = clip_string(name);

  j = -1;
  for (i = 0 ; i < hd.pub.legaleses ; ++i)
  {
    if (!strcmp (get_legalese (i), temp))
    {
      j = i;
      break;
    }
  }

  return (j);
}


/*****************************************************************************\

    Function        find_constituent - gets the index into the constituent
                    arrays for the named constituent.

    Synopsis        find_constituent (name);

                    NV_CHAR *name           constituent name (ex. M2)

    Returns         NV_INT32                index into constituent arrays or -1
                                            on failure

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_INT32 find_constituent (NV_CHAR *name)
{
    NV_U_INT32               i;
    NV_CHAR     *temp;

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    return -1;
  }

    temp = clip_string(name);

    for (i = 0 ; i < hd.pub.constituents ; ++i)
    {
      if (!strcmp (get_constituent (i), temp)) return (i);
    }

    return (-1);
}


/*****************************************************************************\

    Function        find_restriction - gets the index into the restriction
                    array given the restriction name

    Synopsis        find_restriction (name);

                    NV_CHAR *name          restriction name

    Returns         NV_INT32                restriction number

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_INT32 find_restriction (NV_CHAR *name)
{
    NV_INT32    j;
    NV_U_INT32  i;
    NV_CHAR     *temp;

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    return -1;
  }

    temp = clip_string(name);

    j = -1;
    for (i = 0 ; i < hd.pub.restriction_types ; ++i)
    {
        if (!strcmp (get_restriction (i), temp))
        {
            j = i;
            break;
        }
    }
    return (j);
}


/*****************************************************************************\

    Function        set_speed - sets the speed value for constituent "num"

    Synopsis        set_speed (num, value);

                    NV_INT32 num            constituent number
                    NV_FLOAT64 value        speed value

    Returns         void

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

void set_speed (NV_INT32 num, NV_FLOAT64 value)
{
  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit (-1);
  }
  write_protect();
  assert (num >= 0 && num < (NV_INT32)hd.pub.constituents);
  if (value < 0.0) {
    fprintf (stderr, "libtcd set_speed: somebody tried to set a negative speed (%f)\n", value);
    exit (-1);
  }
  hd.speed[num] = value;
  modified = NVTrue;
}


/*****************************************************************************\

    Function        set_equilibrium - sets the equilibrium argument for
                    constituent "num" and year "year"

    Synopsis        set_equilibrium (num, year, value);

                    NV_INT32 num            constituent number
                    NV_INT32 year           year
                    NV_FLOAT64 value        equilibrium argument

    Returns         void

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

void set_equilibrium (NV_INT32 num, NV_INT32 year, NV_FLOAT32 value)
{
  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit (-1);
  }
  write_protect();
  assert (num >= 0 && num < (NV_INT32)hd.pub.constituents && year >= 0 && year < (NV_INT32)hd.pub.number_of_years);
  hd.equilibrium[num][year] = value;
  modified = NVTrue;
}


/*****************************************************************************\

    Function        set_node_factor - sets the node factor for constituent
                    "num" and year "year"

    Synopsis        set_node_factor (num, year, value);

                    NV_INT32 num            constituent number
                    NV_INT32 year           year
                    NV_FLOAT64 value        node factor

    Returns         void

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

void set_node_factor (NV_INT32 num, NV_INT32 year, NV_FLOAT32 value)
{
  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit (-1);
  }
  write_protect();
  assert (num >= 0 && num < (NV_INT32)hd.pub.constituents && year >= 0 && year < (NV_INT32)hd.pub.number_of_years);
  if (value <= 0.0) {
    fprintf (stderr, "libtcd set_node_factor: somebody tried to set a negative or zero node factor (%f)\n", value);
    exit (-1);
  }
  hd.node_factor[num][year] = value;
  modified = NVTrue;
}


/*****************************************************************************\

    Function        add_pedigree - adds a new pedigree to the database

    Synopsis        add_pedigree (name, db);

                    NV_CHAR *name          new pedigree string
                    DB_HEADER_PUBLIC *db    modified header

    Returns         NV_INT32                new pedigree index

    Author          Jan C. Depner
    Date            09/20/02

    See libtcd.html for changelog.

\*****************************************************************************/

#ifdef COMPAT114
NV_INT32 add_pedigree (NV_CHAR *name, DB_HEADER_PUBLIC *db) {
  return 0;
}
#endif


/*****************************************************************************\

    Function        add_tzfile - adds a new tzfile to the database

    Synopsis        add_tzfile (name, db);

                    NV_CHAR *name          new tzfile string
                    DB_HEADER_PUBLIC *db    modified header

    Returns         NV_INT32                new tzfile index

    Author          Jan C. Depner
    Date            09/20/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_INT32 add_tzfile (NV_CHAR *name, DB_HEADER_PUBLIC *db)
{
    NV_CHAR *c_name;

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit (-1);
  }
  write_protect();

  assert (name);
  if (strlen(name) + 1 > hd.tzfile_size) {
    fprintf (stderr, "libtcd error: tzfile exceeds size limit (%u).\n",
             hd.tzfile_size);
    fprintf (stderr, "The offending input is: %s\n", name);
    exit (-1);
  }

    if (hd.pub.tzfiles == hd.max_tzfiles)
    {
        fprintf (stderr,
            "You have exceeded the maximum number of tzfile types!\n");
        fprintf (stderr,
            "You cannot add any new tzfile types.\n");
        fprintf (stderr,
            "Modify the DEFAULT_TZFILE_BITS and rebuild the database.\n");
        exit (-1);
    }

    c_name = clip_string (name);

    hd.tzfile[hd.pub.tzfiles] = (NV_CHAR *) calloc (strlen (c_name) + 1,
        sizeof (NV_CHAR));

    if (hd.tzfile[hd.pub.tzfiles] == NULL)
    {
        perror ("Allocating new tzfile string");
        exit (-1);
    }

    strcpy (hd.tzfile[hd.pub.tzfiles++], c_name);
    if (db)
      *db = hd.pub;
    modified = NVTrue;
    return (hd.pub.tzfiles - 1);
}


/*****************************************************************************\

    Function        add_country - adds a new country to the database

    Synopsis        add_country (name, db);

                    NV_CHAR *name          new country string
                    DB_HEADER_PUBLIC *db    modified header

    Returns         NV_INT32                new country index

    Author          Jan C. Depner
    Date            09/20/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_INT32 add_country (NV_CHAR *name, DB_HEADER_PUBLIC *db)
{
    NV_CHAR *c_name;

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit (-1);
  }
  write_protect();

  assert (name);
  if (strlen(name) + 1 > hd.country_size) {
    fprintf (stderr, "libtcd error: country exceeds size limit (%u).\n",
             hd.country_size);
    fprintf (stderr, "The offending input is: %s\n", name);
    exit (-1);
  }

    if (hd.pub.countries == hd.max_countries)
    {
        fprintf (stderr,
            "You have exceeded the maximum number of country names!\n");
        fprintf (stderr,
            "You cannot add any new country names.\n");
        fprintf (stderr,
            "Modify the DEFAULT_COUNTRY_BITS and rebuild the database.\n");
        exit (-1);
    }

    c_name = clip_string (name);

    hd.country[hd.pub.countries] = (NV_CHAR *) calloc (strlen (c_name) + 1,
        sizeof (NV_CHAR));

    if (hd.country[hd.pub.countries] == NULL)
    {
        perror ("Allocating new country string");
        exit (-1);
    }

    strcpy (hd.country[hd.pub.countries++], c_name);
    if (db)
      *db = hd.pub;
    modified = NVTrue;
    return (hd.pub.countries - 1);
}


/*****************************************************************************\

    Function        add_datum - adds a new datum to the database

    Synopsis        add_datum (name, db);

                    NV_CHAR *name          new datum string
                    DB_HEADER_PUBLIC *db    modified header

    Returns         NV_INT32                new datum index

    Author          Jan C. Depner
    Date            09/20/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_INT32 add_datum (NV_CHAR *name, DB_HEADER_PUBLIC *db)
{
    NV_CHAR *c_name;

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit (-1);
  }
  write_protect();

  assert (name);
  if (strlen(name) + 1 > hd.datum_size) {
    fprintf (stderr, "libtcd error: datum exceeds size limit (%u).\n",
             hd.datum_size);
    fprintf (stderr, "The offending input is: %s\n", name);
    exit (-1);
  }

    if (hd.pub.datum_types == hd.max_datum_types)
    {
        fprintf (stderr,
            "You have exceeded the maximum number of datum types!\n");
        fprintf (stderr,
            "You cannot add any new datum types.\n");
        fprintf (stderr,
            "Modify the DEFAULT_DATUM_BITS and rebuild the database.\n");
        exit (-1);
    }

    c_name = clip_string (name);

    hd.datum[hd.pub.datum_types] = (NV_CHAR *) calloc (strlen (c_name) + 1,
        sizeof (NV_CHAR));

    if (hd.datum[hd.pub.datum_types] == NULL)
    {
        perror ("Allocating new datum string");
        exit (-1);
    }

    strcpy (hd.datum[hd.pub.datum_types++], c_name);
    if (db)
      *db = hd.pub;
    modified = NVTrue;
    return (hd.pub.datum_types - 1);
}


/*****************************************************************************\
  DWF 2004-10-14
\*****************************************************************************/
NV_INT32 add_legalese (NV_CHAR *name, DB_HEADER_PUBLIC *db)
{
    NV_CHAR *c_name;

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit (-1);
  }
  write_protect();

  assert (name);
  if (strlen(name) + 1 > hd.legalese_size) {
    fprintf (stderr, "libtcd error: legalese exceeds size limit (%u).\n",
             hd.legalese_size);
    fprintf (stderr, "The offending input is: %s\n", name);
    exit (-1);
  }

    if (hd.pub.legaleses == hd.max_legaleses)
    {
        fprintf (stderr,
            "You have exceeded the maximum number of legaleses!\n");
        fprintf (stderr,
            "You cannot add any new legaleses.\n");
        fprintf (stderr,
            "Modify the DEFAULT_LEGALESE_BITS and rebuild the database.\n");
        exit (-1);
    }

    c_name = clip_string (name);

    hd.legalese[hd.pub.legaleses] = (NV_CHAR *) calloc (strlen (c_name) + 1,
        sizeof (NV_CHAR));

    if (hd.legalese[hd.pub.legaleses] == NULL)
    {
        perror ("Allocating new legalese string");
        exit (-1);
    }

    strcpy (hd.legalese[hd.pub.legaleses++], c_name);
    if (db)
      *db = hd.pub;
    modified = NVTrue;
    return (hd.pub.legaleses - 1);
}


/*****************************************************************************\

    Function        add_restriction - adds a new restriction to the database

    Synopsis        add_restriction (name, db);

                    NV_CHAR *name          new restriction string
                    DB_HEADER_PUBLIC *db    modified header

    Returns         NV_INT32                new restriction index

    Author          Jan C. Depner
    Date            09/20/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_INT32 add_restriction (NV_CHAR *name, DB_HEADER_PUBLIC *db)
{
    NV_CHAR *c_name;

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit (-1);
  }
  write_protect();

  assert (name);
  if (strlen(name) + 1 > hd.restriction_size) {
    fprintf (stderr, "libtcd error: restriction exceeds size limit (%u).\n",
             hd.restriction_size);
    fprintf (stderr, "The offending input is: %s\n", name);
    exit (-1);
  }

    if (hd.pub.restriction_types == hd.max_restriction_types)
    {
        fprintf (stderr,
            "You have exceeded the maximum number of restriction types!\n");
        fprintf (stderr,
            "You cannot add any new restriction types.\n");
        fprintf (stderr,
            "Modify the DEFAULT_RESTRICTION_BITS and rebuild the database.\n");
        exit (-1);
    }

    c_name = clip_string (name);

    hd.restriction[hd.pub.restriction_types] =
        (NV_CHAR *) calloc (strlen (c_name) + 1, sizeof (NV_CHAR));

    if (hd.restriction[hd.pub.restriction_types] == NULL)
    {
        perror ("Allocating new restriction string");
        exit (-1);
    }

    strcpy (hd.restriction[hd.pub.restriction_types++], c_name);
    if (db)
      *db = hd.pub;
    modified = NVTrue;
    return (hd.pub.restriction_types - 1);
}


/*****************************************************************************\
  DWF 2004-10-04
\*****************************************************************************/
NV_INT32 find_or_add_restriction (NV_CHAR *name, DB_HEADER_PUBLIC *db) {
  NV_INT32 ret;
  ret = find_restriction (name);
  if (ret < 0)
    ret = add_restriction (name, db);
  assert (ret >= 0);
  return ret;
}


/*****************************************************************************\
  DWF 2004-10-04
\*****************************************************************************/
NV_INT32 find_or_add_tzfile (NV_CHAR *name, DB_HEADER_PUBLIC *db) {
  NV_INT32 ret;
  ret = find_tzfile (name);
  if (ret < 0)
    ret = add_tzfile (name, db);
  assert (ret >= 0);
  return ret;
}


/*****************************************************************************\
  DWF 2004-10-04
\*****************************************************************************/
NV_INT32 find_or_add_country (NV_CHAR *name, DB_HEADER_PUBLIC *db) {
  NV_INT32 ret;
  ret = find_country (name);
  if (ret < 0)
    ret = add_country (name, db);
  assert (ret >= 0);
  return ret;
}


/*****************************************************************************\
  DWF 2004-10-04
\*****************************************************************************/
NV_INT32 find_or_add_datum (NV_CHAR *name, DB_HEADER_PUBLIC *db) {
  NV_INT32 ret;
  ret = find_datum (name);
  if (ret < 0)
    ret = add_datum (name, db);
  assert (ret >= 0);
  return ret;
}


/*****************************************************************************\
  DWF 2004-10-14
\*****************************************************************************/
NV_INT32 find_or_add_legalese (NV_CHAR *name, DB_HEADER_PUBLIC *db) {
  NV_INT32 ret;
  ret = find_legalese (name);
  if (ret < 0)
    ret = add_legalese (name, db);
  assert (ret >= 0);
  return ret;
}


/*****************************************************************************\

    Function        check_simple - checks tide record to see if it is a
                    "simple" subordinate station.

    Synopsis        check_simple (rec);

                    TIDE_RECORD rec         tide record

    Returns         NV_BOOL                 NVTrue if "simple"

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

    "Simplified" type 2 records were done away with 2003-03-27 per the
    discussion in http://www.flaterco.com/xtide/tcd_notes.html.  This
    function is now of interest only in restore_tide_db, which uses it
    to determine which XML format to output.  Deprecated here, moved
    to restore_tide_db.

\*****************************************************************************/

#ifdef COMPAT114
NV_BOOL check_simple (TIDE_RECORD rec)
{
  if (rec.max_time_add       == rec.min_time_add        &&
      rec.max_level_add      == rec.min_level_add       &&
      rec.max_level_multiply == rec.min_level_multiply  &&
      rec.max_avg_level == 0   &&
      rec.min_avg_level == 0   &&
      rec.max_direction == 361 &&
      rec.min_direction == 361 &&
      rec.flood_begins  == NULLSLACKOFFSET &&
      rec.ebb_begins    == NULLSLACKOFFSET)
    return (NVTrue);

    return (NVFalse);
}
#endif


/*****************************************************************************\

    Function        header_checksum - compute the checksum for the ASCII
                    portion of the database header

    Synopsis        header_checksum ();

    Returns         NV_U_INT32              checksum value

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

static NV_U_INT32 header_checksum ()
{
    NV_U_INT32          checksum, i, save_pos;
    NV_U_BYTE           *buf;
    NV_U_INT32          crc_table[256] =
      {0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,
       0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,
       0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,0x1DB71064,0x6AB020F2,
       0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,
       0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,
       0xFA0F3D63,0x8D080DF5,0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,
       0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,
       0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
       0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,
       0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,
       0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,0x76DC4190,0x01DB7106,
       0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,
       0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,
       0x91646C97,0xE6635C01,0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,
       0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,
       0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
       0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,
       0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,
       0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,0x5005713C,0x270241AA,
       0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,
       0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,
       0xB7BD5C3B,0xC0BA6CAD,0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,
       0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,
       0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
       0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,
       0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,
       0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,0xD6D6A3E8,0xA1D1937E,
       0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,
       0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,
       0x316E8EEF,0x4669BE79,0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,
       0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,
       0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
       0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,
       0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,
       0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,0x86D3D2D4,0xF1D4E242,
       0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,
       0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,
       0x616BFFD3,0x166CCF45,0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,
       0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,
       0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
       0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,
       0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,
       0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D};

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit (-1);
  }

    save_pos = ftell (fp);

    fseek (fp, 0, SEEK_SET);

    if ((buf = (NV_U_BYTE *) calloc (hd.header_size, sizeof (NV_U_BYTE))) ==
        NULL)
    {
        perror ("Allocating checksum buffer");
        exit (-1);
    }

    checksum = ~0;

    assert (hd.header_size > 0);
    fread (buf, hd.header_size, 1, fp);
    for (i = 0 ; i < (NV_U_INT32)hd.header_size ; ++i)
    {
        checksum = crc_table[(checksum ^ buf[i]) & 0xff] ^ (checksum >> 8);
    }
    checksum ^= ~0;

    free (buf);

    fseek (fp, save_pos, SEEK_SET);

    return (checksum);
}


/*****************************************************************************\

    Function        old_header_checksum - compute the old-style checksum for 
                    the ASCII portion of the database header just in case this
                    is a pre 1.02 file.

    Synopsis        old_header_checksum ();

    Returns         NV_U_INT32              checksum value

    Author          Jan C. Depner
    Date            11/15/02

\*****************************************************************************/

#ifdef COMPAT114
static NV_U_INT32 old_header_checksum ()
{
    NV_U_INT32          checksum, i, save_pos;
    NV_U_BYTE           *buf;

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit (-1);
  }

    save_pos = ftell (fp);

    checksum = 0;

    fseek (fp, 0, SEEK_SET);

    if ((buf = (NV_U_BYTE *) calloc (hd.header_size, sizeof (NV_U_BYTE))) == 
        NULL)
    {
        perror ("Allocating checksum buffer");
        exit (-1);
    }

    fread (buf, hd.header_size, 1, fp);

    for (i = 0 ; i < hd.header_size ; ++i) checksum += buf[i];

    free (buf);

    fseek (fp, save_pos, SEEK_SET);

    return (checksum);
}
#endif


/*****************************************************************************\
   DWF 2004-10-01
   Get current time in preferred format.
\*****************************************************************************/
static NV_CHAR *curtime () {
  static NV_CHAR buf[ONELINER_LENGTH];
  time_t t = time(NULL);
  require (strftime (buf, ONELINER_LENGTH, "%Y-%m-%d %H:%M %Z", localtime(&t)) > 0);
  return buf;
}


/*****************************************************************************\
   DWF 2004-10-15
   Calculate bytes for number of bits.
\*****************************************************************************/
static NV_U_INT32 bits2bytes (NV_U_INT32 nbits) {
  if (nbits % 8)
    return nbits / 8 + 1;
  return nbits / 8;
}


/*****************************************************************************\

    Function        write_tide_db_header - writes the database header to the
                    file

    Synopsis        write_tide_db_header ();

    Returns         void

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

static void write_tide_db_header ()
{
    NV_U_INT32          i, size, pos;
    NV_INT32            start, temp_int;
    static NV_CHAR      zero = 0;
    NV_U_BYTE           *buf, checksum_c[4];

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit (-1);
  }
  write_protect();

    fseek (fp, 0, SEEK_SET);

    fprintf (fp, "[VERSION] = %s\n", LIBTCD_VERSION);
    fprintf (fp, "[MAJOR REV] = %u\n", LIBTCD_MAJOR_REV);
    fprintf (fp, "[MINOR REV] = %u\n", LIBTCD_MINOR_REV);

    fprintf (fp, "[LAST MODIFIED] = %s\n", curtime());

    fprintf (fp, "[HEADER SIZE] = %u\n", hd.header_size);
    fprintf (fp, "[NUMBER OF RECORDS] = %u\n", hd.pub.number_of_records);

    fprintf (fp, "[START YEAR] = %d\n", hd.pub.start_year);
    fprintf (fp, "[NUMBER OF YEARS] = %u\n", hd.pub.number_of_years);

    fprintf (fp, "[SPEED BITS] = %u\n", hd.speed_bits);
    fprintf (fp, "[SPEED SCALE] = %u\n", hd.speed_scale);
    fprintf (fp, "[SPEED OFFSET] = %d\n", hd.speed_offset);
    fprintf (fp, "[EQUILIBRIUM BITS] = %u\n", hd.equilibrium_bits);
    fprintf (fp, "[EQUILIBRIUM SCALE] = %u\n", hd.equilibrium_scale);
    fprintf (fp, "[EQUILIBRIUM OFFSET] = %d\n", hd.equilibrium_offset);
    fprintf (fp, "[NODE BITS] = %u\n", hd.node_bits);
    fprintf (fp, "[NODE SCALE] = %u\n", hd.node_scale);
    fprintf (fp, "[NODE OFFSET] = %d\n", hd.node_offset);
    fprintf (fp, "[AMPLITUDE BITS] = %u\n", hd.amplitude_bits);
    fprintf (fp, "[AMPLITUDE SCALE] = %u\n", hd.amplitude_scale);
    fprintf (fp, "[EPOCH BITS] = %u\n", hd.epoch_bits);
    fprintf (fp, "[EPOCH SCALE] = %u\n", hd.epoch_scale);

    fprintf (fp, "[RECORD TYPE BITS] = %u\n", hd.record_type_bits);
    fprintf (fp, "[LATITUDE BITS] = %u\n", hd.latitude_bits);
    fprintf (fp, "[LATITUDE SCALE] = %u\n", hd.latitude_scale);
    fprintf (fp, "[LONGITUDE BITS] = %u\n", hd.longitude_bits);
    fprintf (fp, "[LONGITUDE SCALE] = %u\n", hd.longitude_scale);
    fprintf (fp, "[RECORD SIZE BITS] = %u\n", hd.record_size_bits);

    fprintf (fp, "[STATION BITS] = %u\n", hd.station_bits);

    fprintf (fp, "[DATUM OFFSET BITS] = %u\n", hd.datum_offset_bits);
    fprintf (fp, "[DATUM OFFSET SCALE] = %u\n", hd.datum_offset_scale);
    fprintf (fp, "[DATE BITS] = %u\n", hd.date_bits);
    fprintf (fp, "[MONTHS ON STATION BITS] = %u\n",
             hd.months_on_station_bits);
    fprintf (fp, "[CONFIDENCE VALUE BITS] = %u\n", hd.confidence_value_bits);

    fprintf (fp, "[TIME BITS] = %u\n", hd.time_bits);
    fprintf (fp, "[LEVEL ADD BITS] = %u\n", hd.level_add_bits);
    fprintf (fp, "[LEVEL ADD SCALE] = %u\n", hd.level_add_scale);
    fprintf (fp, "[LEVEL MULTIPLY BITS] = %u\n", hd.level_multiply_bits);
    fprintf (fp, "[LEVEL MULTIPLY SCALE] = %u\n", hd.level_multiply_scale);
    fprintf (fp, "[DIRECTION BITS] = %u\n", hd.direction_bits);

    fprintf (fp, "[LEVEL UNIT BITS] = %u\n", hd.level_unit_bits);
    fprintf (fp, "[LEVEL UNIT TYPES] = %u\n", hd.pub.level_unit_types);
    fprintf (fp, "[LEVEL UNIT SIZE] = %u\n", hd.level_unit_size);

    fprintf (fp, "[DIRECTION UNIT BITS] = %u\n", hd.dir_unit_bits);
    fprintf (fp, "[DIRECTION UNIT TYPES] = %u\n", hd.pub.dir_unit_types);
    fprintf (fp, "[DIRECTION UNIT SIZE] = %u\n", hd.dir_unit_size);

    fprintf (fp, "[RESTRICTION BITS] = %u\n", hd.restriction_bits);
    fprintf (fp, "[RESTRICTION TYPES] = %u\n", hd.pub.restriction_types);
    fprintf (fp, "[RESTRICTION SIZE] = %u\n", hd.restriction_size);

    fprintf (fp, "[DATUM BITS] = %u\n", hd.datum_bits);
    fprintf (fp, "[DATUM TYPES] = %u\n", hd.pub.datum_types);
    fprintf (fp, "[DATUM SIZE] = %u\n", hd.datum_size);

    fprintf (fp, "[LEGALESE BITS] = %u\n", hd.legalese_bits);
    fprintf (fp, "[LEGALESE TYPES] = %u\n", hd.pub.legaleses);
    fprintf (fp, "[LEGALESE SIZE] = %u\n", hd.legalese_size);

    fprintf (fp, "[CONSTITUENT BITS] = %u\n", hd.constituent_bits);
    fprintf (fp, "[CONSTITUENTS] = %u\n", hd.pub.constituents);
    fprintf (fp, "[CONSTITUENT SIZE] = %u\n", hd.constituent_size);

    fprintf (fp, "[TZFILE BITS] = %u\n", hd.tzfile_bits);
    fprintf (fp, "[TZFILES] = %u\n", hd.pub.tzfiles);
    fprintf (fp, "[TZFILE SIZE] = %u\n", hd.tzfile_size);

    fprintf (fp, "[COUNTRY BITS] = %u\n", hd.country_bits);
    fprintf (fp, "[COUNTRIES] = %u\n", hd.pub.countries);
    fprintf (fp, "[COUNTRY SIZE] = %u\n", hd.country_size);

    fprintf (fp, "[END OF FILE] = %u\n", hd.end_of_file);
    fprintf (fp, "[END OF ASCII HEADER DATA]\n");


    /*  Fill the remainder of the [HEADER SIZE] ASCII header with zeroes.  */

    start = ftell (fp);
    assert (start >= 0);
    for (i = start ; i < hd.header_size ; ++i) fwrite (&zero, 1, 1, fp);
    fflush (fp);


    /*  Compute and save the checksum. */

    bit_pack (checksum_c, 0, 32, header_checksum ());
    fwrite (checksum_c, 4, 1, fp);


    /*  NOTE : Using strcpy for character strings (no endian issue).  */

    /*  Write level units.  */

    pos = 0;
    size = hd.pub.level_unit_types * hd.level_unit_size;

    if ((buf = (NV_U_BYTE *) calloc (size, sizeof (NV_U_BYTE))) == NULL)
    {
        perror ("Allocating unit write buffer");
        exit (-1);
    }
    memset (buf, 0, size);

    for (i = 0 ; i < hd.pub.level_unit_types ; ++i)
    {
        assert (strlen(hd.level_unit[i]) + 1 <= hd.level_unit_size);
        strcpy ((NV_CHAR *) &buf[pos], hd.level_unit[i]);
        pos += hd.level_unit_size;
    }

    fwrite (buf, pos, 1, fp);
    free (buf);


    /*  Write direction units.  */

    pos = 0;
    size = hd.pub.dir_unit_types * hd.dir_unit_size;

    if ((buf = (NV_U_BYTE *) calloc (size, sizeof (NV_U_BYTE))) == NULL)
    {
        perror ("Allocating unit write buffer");
        exit (-1);
    }
    memset (buf, 0, size);

    for (i = 0 ; i < hd.pub.dir_unit_types ; ++i)
    {
        assert (strlen(hd.dir_unit[i]) + 1 <= hd.dir_unit_size);
        strcpy ((NV_CHAR *) &buf[pos], hd.dir_unit[i]);
        pos += hd.dir_unit_size;
    }

    fwrite (buf, pos, 1, fp);
    free (buf);


    /*  Write restrictions.  */

    pos = 0;
    size = hd.max_restriction_types * hd.restriction_size;

    if ((buf = (NV_U_BYTE *) calloc (size, sizeof (NV_U_BYTE))) == NULL)
    {
        perror ("Allocating restriction write buffer");
        exit (-1);
    }
    memset (buf, 0, size);

    for (i = 0 ; i < hd.max_restriction_types ; ++i)
    {
        if (i == hd.pub.restriction_types) break;
        assert (strlen(hd.restriction[i]) + 1 <= hd.restriction_size);
        strcpy ((NV_CHAR *) &buf[pos], hd.restriction[i]);
        pos += hd.restriction_size;
    }
    memcpy (&buf[pos], "__END__", 7);

    fwrite (buf, size, 1, fp);
    free (buf);


    /*  Write tzfiles.  */

    pos = 0;
    size = hd.max_tzfiles * hd.tzfile_size;

    if ((buf = (NV_U_BYTE *) calloc (size, sizeof (NV_U_BYTE))) == NULL)
    {
        perror ("Allocating tzfile write buffer");
        exit (-1);
    }
    memset (buf, 0, size);

    for (i = 0 ; i < hd.max_tzfiles ; ++i)
    {
        if (i == hd.pub.tzfiles) break;
        assert (strlen(hd.tzfile[i]) + 1 <= hd.tzfile_size);
        strcpy ((NV_CHAR *) &buf[pos], hd.tzfile[i]);
        pos += hd.tzfile_size;
    }
    memcpy (&buf[pos], "__END__", 7);

    fwrite (buf, size, 1, fp);
    free (buf);


    /*  Write countries.  */

    pos = 0;
    size = hd.max_countries * hd.country_size;

    if ((buf = (NV_U_BYTE *) calloc (size, sizeof (NV_U_BYTE))) == NULL)
    {
        perror ("Allocating country write buffer");
        exit (-1);
    }
    memset (buf, 0, size);

    for (i = 0 ; i < hd.max_countries ; ++i)
    {
        if (i == hd.pub.countries) break;
        assert (strlen(hd.country[i]) + 1 <= hd.country_size);
        strcpy ((NV_CHAR *) &buf[pos], hd.country[i]);
        pos += hd.country_size;
    }
    memcpy (&buf[pos], "__END__", 7);

    fwrite (buf, size, 1, fp);
    free (buf);


    /*  Write datums.  */

    pos = 0;
    size = hd.max_datum_types * hd.datum_size;

    if ((buf = (NV_U_BYTE *) calloc (size, sizeof (NV_U_BYTE))) == NULL)
    {
        perror ("Allocating datum write buffer");
        exit (-1);
    }
    memset (buf, 0, size);

    for (i = 0 ; i < hd.max_datum_types ; ++i)
    {
        if (i == hd.pub.datum_types) break;
        assert (strlen(hd.datum[i]) + 1 <= hd.datum_size);
        strcpy ((NV_CHAR *) &buf[pos], hd.datum[i]);
        pos += hd.datum_size;
    }
    memcpy (&buf[pos], "__END__", 7);

    fwrite (buf, size, 1, fp);
    free (buf);


    /*  Write legaleses.  */

    pos = 0;
    size = hd.max_legaleses * hd.legalese_size;

    if ((buf = (NV_U_BYTE *) calloc (size, sizeof (NV_U_BYTE))) == NULL)
    {
        perror ("Allocating legalese write buffer");
        exit (-1);
    }
    memset (buf, 0, size);

    for (i = 0 ; i < hd.max_legaleses ; ++i)
    {
        if (i == hd.pub.legaleses) break;
        assert (strlen(hd.legalese[i]) + 1 <= hd.legalese_size);
        strcpy ((NV_CHAR *) &buf[pos], hd.legalese[i]);
        pos += hd.legalese_size;
    }
    memcpy (&buf[pos], "__END__", 7);

    fwrite (buf, size, 1, fp);
    free (buf);


    /*  Write constituent names.  */

    pos = 0;
    size = hd.pub.constituents * hd.constituent_size;

    if ((buf = (NV_U_BYTE *) calloc (size, sizeof (NV_U_BYTE))) == NULL)
    {
        perror ("Allocating constituent write buffer");
        exit (-1);
    }
    memset (buf, 0, size);

    for (i = 0 ; i < hd.pub.constituents ; ++i)
    {
        assert (strlen(hd.constituent[i]) + 1 <= hd.constituent_size);
        strcpy ((NV_CHAR *) &buf[pos], hd.constituent[i]);
        pos += hd.constituent_size;
    }

    fwrite (buf, pos, 1, fp);
    free (buf);


    /*  NOTE : Using bit_pack for integers.  */

    /*  Write speeds.  */

    pos = 0;
    size = bits2bytes (hd.pub.constituents * hd.speed_bits);

    if ((buf = (NV_U_BYTE *) calloc (size, sizeof (NV_U_BYTE))) == NULL)
    {
        perror ("Allocating speed write buffer");
        exit (-1);
    }
    memset (buf, 0, size);

    for (i = 0 ; i < hd.pub.constituents ; ++i)
    {
        temp_int = NINT (hd.speed[i] * hd.speed_scale) - hd.speed_offset;
        assert (temp_int >= 0);
        bit_pack (buf, pos, hd.speed_bits, temp_int);
        pos += hd.speed_bits;
    }

    fwrite (buf, size, 1, fp);
    free (buf);


    /*  Write equilibrium arguments.  */

    pos = 0;
    size = bits2bytes (hd.pub.constituents *  hd.pub.number_of_years *
		       hd.equilibrium_bits);

    if ((buf = (NV_U_BYTE *) calloc (size, sizeof (NV_U_BYTE))) == NULL)
    {
        perror ("Allocating equilibrium write buffer");
        exit (-1);
    }
    memset (buf, 0, size);

    for (i = 0 ; i < hd.pub.constituents ; ++i)
    {
        NV_U_INT32 j;
        for (j = 0 ; j < hd.pub.number_of_years ; ++j)
        {
            temp_int = NINT (hd.equilibrium[i][j] * hd.equilibrium_scale) -
                hd.equilibrium_offset;
            assert (temp_int >= 0);
            bit_pack (buf, pos, hd.equilibrium_bits, temp_int);
            pos += hd.equilibrium_bits;
        }
    }

    fwrite (buf, size, 1, fp);
    free (buf);


    /*  Write node factors.  */

    pos = 0;
    size = bits2bytes (hd.pub.constituents * hd.pub.number_of_years *
		       hd.node_bits);

    if ((buf = (NV_U_BYTE *) calloc (size, sizeof (NV_U_BYTE))) == NULL)
    {
        perror ("Allocating node write buffer");
        exit (-1);
    }
    memset (buf, 0, size);

    for (i = 0 ; i < hd.pub.constituents ; ++i)
    {
        NV_U_INT32 j;
        for (j = 0 ; j < hd.pub.number_of_years ; ++j)
        {
            temp_int = NINT (hd.node_factor[i][j] * hd.node_scale) -
                hd.node_offset;
            assert (temp_int >= 0);
            bit_pack (buf, pos, hd.node_bits, temp_int);
            pos += hd.node_bits;
        }
    }

    fwrite (buf, size, 1, fp);
    free (buf);
}


/*****************************************************************************\

    Function        unpack_string - Safely unpack a string into a
                    fixed-length buffer.

    Synopsis        unpack_string (buf, bufsize, pos, outbuf, outbuflen, desc);

                    NV_U_BYTE *buf          input buffer
                    NV_U_INT32 bufsize      size of input buffer in bytes
                    NV_U_INT32 *pos         current bit-position in buf
                                            (in-out parameter)
                    NV_CHAR *outbuf         fixed-length string-buffer
                    NV_U_INT32 outbuflen    size of outbuf in bytes
                    NV_CHAR *desc           description of the field being
                                            unpacked for use in warning
                                            messages when truncation occurs

    Returns         void

    Author          David Flater
    Date            2004-09-30

    pos will be left at the start of the next field even if the string
    gets truncated.

\*****************************************************************************/

static void unpack_string (NV_U_BYTE *buf, NV_U_INT32 bufsize, NV_U_INT32 *pos,
NV_CHAR *outbuf, NV_U_INT32 outbuflen, NV_CHAR *desc) {
  NV_U_INT32 i;
  NV_CHAR c = 'x';
  assert (buf);
  assert (pos);
  assert (outbuf);
  assert (desc);
  assert (outbuflen);
  --outbuflen;
  bufsize <<= 3;
  for (i = 0 ; c ; ++i) {
    assert (*pos < bufsize); /* Catch unterminated strings */
    c = bit_unpack (buf, *pos, 8);
    (*pos) += 8;
    if (i < outbuflen) {
      outbuf[i] = c;
    } else if (i == outbuflen) {
      outbuf[i] = '\0';
      if (c) {
        fprintf (stderr, "libtcd warning: truncating overlong %s\n", desc);
        fprintf (stderr, "The offending string starts with:\n%s\n", outbuf);
      }
    }
  }
}


/*****************************************************************************\

    Function        unpack_partial_tide_record - unpacks the "header" portion
                    of a tide record from the supplied buffer

    Synopsis        unpack_partial_tide_record (buf, rec, pos);

                    NV_U_BYTE *buf          input buffer
                    NV_U_INT32 bufsize      size of input buffer in bytes
                    TIDE_RECORD *rec        tide record
                    NV_U_INT32 *pos         final position in buffer after
                                            unpacking the header

    Returns         void

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

static void unpack_partial_tide_record (NV_U_BYTE *buf, NV_U_INT32 bufsize,
TIDE_RECORD *rec, NV_U_INT32 *pos)
{
    NV_INT32 temp_int;

    assert (buf);
    assert (rec);
    assert (pos);

    *pos = 0;

    rec->header.record_size = bit_unpack (buf, *pos, hd.record_size_bits);
    *pos += hd.record_size_bits;

    rec->header.record_type = bit_unpack (buf, *pos, hd.record_type_bits);
    *pos += hd.record_type_bits;

    temp_int = signed_bit_unpack (buf, *pos, hd.latitude_bits);
    rec->header.latitude = (NV_FLOAT64) temp_int / hd.latitude_scale;
    *pos += hd.latitude_bits;

    temp_int = signed_bit_unpack (buf, *pos, hd.longitude_bits);
    rec->header.longitude = (NV_FLOAT64) temp_int / hd.longitude_scale;
    *pos += hd.longitude_bits;

    /* This ordering doesn't match everywhere else but there's no technical
       reason to change it from its V1 ordering. */

    rec->header.tzfile = bit_unpack (buf, *pos, hd.tzfile_bits);
    *pos += hd.tzfile_bits;

    unpack_string (buf, bufsize, pos, rec->header.name, ONELINER_LENGTH, "station name");

    rec->header.reference_station =
	signed_bit_unpack (buf, *pos, hd.station_bits);
    *pos += hd.station_bits;

    assert (*pos <= bufsize*8);
}


/*****************************************************************************\

    Function        read_partial_tide_record - reads the "header" portion
                    of a tide record from the database.  This is used to index
                    the database on opening.

    Synopsis        read_partial_tide_record (num, rec);

                    NV_INT32 num            record number
                    TIDE_RECORD *rec        tide record

    Returns         NV_INT32                record number read

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

static NV_INT32 read_partial_tide_record (NV_INT32 num, TIDE_RECORD *rec)
{
    NV_U_BYTE               *buf;
    NV_U_INT32              size, pos;

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit (-1);
  }

    assert (rec);

    /*  Read just the record size, record type, position, time zone, and
        name.  */

    size = hd.record_size_bits + hd.record_type_bits + hd.latitude_bits +
        hd.longitude_bits + hd.tzfile_bits + (ONELINER_LENGTH * 8) +
        hd.station_bits;
    size = bits2bytes (size);

    if ((buf = (NV_U_BYTE *) calloc (size, sizeof (NV_U_BYTE))) == NULL)
    {
        perror ("Allocating partial tide record buffer");
        exit (-1);
    }

    current_record = num;
    fseek (fp, tindex[num].address, SEEK_SET);
    fread (buf, size, 1, fp);
    unpack_partial_tide_record (buf, size, rec, &pos);
    free (buf);
    return (num);
}


/*****************************************************************************\

    Function        read_tide_db_header - reads the tide database header

    Synopsis        read_tide_db_header ();

    Returns         NV_BOOL                 NVTrue if header is correct

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

static NV_BOOL read_tide_db_header ()
{
    NV_INT32            temp_int;
    NV_CHAR             varin[ONELINER_LENGTH], *info;
    NV_U_INT32          utemp, i, j, pos, size, key_count;
    NV_U_BYTE           *buf, checksum_c[4];
    TIDE_RECORD         rec;

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    exit (-1);
  }

    strcpy (hd.pub.version, "NO VERSION");

    /*  Compute the number of key phrases there are to match.  */
    key_count = sizeof (keys) / sizeof (KEY);

    /*  Zero out the header structure.  */
    memset (&hd, 0, sizeof (hd));

    /*  Handle the ASCII header data.  */
    while (fgets (varin, sizeof(varin), fp) != NULL)
    {
        if (strlen (varin) == ONELINER_LENGTH-1) {
          if (varin[ONELINER_LENGTH-2] != '\n') {
            fprintf (stderr, "libtcd error:  header line too long, begins with:\n");
            fprintf (stderr, "%s\n", varin);
            fprintf (stderr, "in file %s\n", filename);
            fprintf (stderr, "Configured limit is %u\n", ONELINER_LENGTH-1);
            fclose (fp);
            return NVFalse;
          }
        }

        if (strstr (varin, "[END OF ASCII HEADER DATA]")) break;

        /* All other lines must be field = value */
        info = strchr (varin, '=');
        if (!info) {
          fprintf (stderr, "libtcd error:  invalid tide db header line:\n");
          fprintf (stderr, "%s", varin);
          fprintf (stderr, "in file %s\n", filename);
          fclose (fp);
          return NVFalse;
        }
        ++info;

        /* Scan the fields per "keys" defined in tide_db_header.h. */
        for (i=0; i<key_count; ++i) {
          if (strstr (varin, keys[i].keyphrase)) {
            if (!strcmp (keys[i].datatype, "cstr"))
              strcpy (keys[i].address.cstr, clip_string(info));
            else if (!strcmp (keys[i].datatype, "i32")) {
              if (sscanf (info, "%d", keys[i].address.i32) != 1) {
          fprintf (stderr, "libtcd error:  invalid tide db header line:\n");
          fprintf (stderr, "%s", varin);
          fprintf (stderr, "in file %s\n", filename);
          fclose (fp);
          return NVFalse;
              }
            } else if (!strcmp (keys[i].datatype, "ui32")) {
              if (sscanf (info, "%u", keys[i].address.ui32) != 1) {
          fprintf (stderr, "libtcd error:  invalid tide db header line:\n");
          fprintf (stderr, "%s", varin);
          fprintf (stderr, "in file %s\n", filename);
          fclose (fp);
          return NVFalse;
              }
            } else
              assert (0);
          }
        }
    }

    /*  We didn't get a valid version string.  */

    if (!strcmp (hd.pub.version, "NO VERSION"))
    {
        fprintf (stderr, "libtcd error:  no version found in tide db header\n");
        fprintf (stderr, "in file %s\n", filename);
        fclose (fp);
        return NVFalse;
    }

    /* If no major or minor rev, they're 0 (pre-1.99) */
    if (hd.pub.major_rev > LIBTCD_MAJOR_REV) {
      fprintf (stderr, "libtcd error:  major revision in TCD file (%u) exceeds major revision of\n", hd.pub.major_rev);
      fprintf (stderr, "libtcd (%u).  You must upgrade libtcd to read this file.\n", LIBTCD_MAJOR_REV);
      fclose (fp);
      return NVFalse;
    }

    /*  Move to end of ASCII header.  */
    fseek (fp, hd.header_size, SEEK_SET);


    /*  Read and check the checksum. */

    fread (checksum_c, 4, 1, fp);
    utemp = bit_unpack (checksum_c, 0, 32);

    if (utemp != header_checksum ()) {
#ifdef COMPAT114
      if (utemp != old_header_checksum ()) {
        fprintf (stderr,
            "libtcd error:  header checksum error in file %s\n", filename);
        fprintf (stderr, "Someone may have modified the ASCII portion of the header (don't do that),\n\
or it may just be corrupt.\n");
        fclose (fp);
        return NVFalse;
      }
#else
      fprintf (stderr,
          "libtcd error:  header checksum error in file %s\n", filename);
      fprintf (stderr, "Someone may have modified the ASCII portion of the header (don't do that),\n\
or it may be an ancient pre-version-1.02 TCD file, or it may just be corrupt.\n\
Pre-version-1.02 TCD files can be read by building libtcd with COMPAT114\n\
defined.\n");
      fclose (fp);
      return NVFalse;
#endif
    }
    fseek (fp, hd.header_size + 4, SEEK_SET);


    /*  Set the max possible restriction types based on the number of bits
        used.  */

    hd.max_restriction_types = NINT (pow (2.0,
        (NV_FLOAT64) hd.restriction_bits));


    /*  Set the max possible tzfiles based on the number of bits used.  */

    hd.max_tzfiles = NINT (pow (2.0, (NV_FLOAT64) hd.tzfile_bits));


    /*  Set the max possible countries based on the number of bits used.  */

    hd.max_countries = NINT (pow (2.0, (NV_FLOAT64) hd.country_bits));


    /*  Set the max possible datum types based on the number of bits
        used.  */

    hd.max_datum_types = NINT (pow (2.0, (NV_FLOAT64) hd.datum_bits));


    /*  Set the max possible legaleses based on the number of bits
        used.  */

    if (hd.pub.major_rev < 2)
      hd.max_legaleses = 1;
    else
      hd.max_legaleses = NINT (pow (2.0, (NV_FLOAT64) hd.legalese_bits));


    /*  NOTE : Using strcpy for character strings (no endian issue).  */

    /*  Read level units.  */

    hd.level_unit = (NV_CHAR **) calloc (hd.pub.level_unit_types,
        sizeof (NV_CHAR *));

    if ((buf = (NV_U_BYTE *) calloc (hd.level_unit_size,
        sizeof (NV_U_BYTE))) == NULL)
    {
        perror ("Allocating level unit read buffer");
        exit (-1);
    }

    for (i = 0 ; i < hd.pub.level_unit_types ; ++i)
    {
        fread (buf, hd.level_unit_size, 1, fp);
        hd.level_unit[i] = (NV_CHAR *) calloc (strlen((char*)buf) + 1,
            sizeof (NV_CHAR));
        strcpy (hd.level_unit[i], (NV_CHAR *) buf);
    }
    free (buf);



    /*  Read direction units.  */

    hd.dir_unit = (NV_CHAR **) calloc (hd.pub.dir_unit_types,
        sizeof (NV_CHAR *));

    if ((buf = (NV_U_BYTE *) calloc (hd.dir_unit_size, sizeof (NV_U_BYTE))) ==
        NULL)
    {
        perror ("Allocating dir unit read buffer");
        exit (-1);
    }

    for (i = 0 ; i < hd.pub.dir_unit_types ; ++i)
    {
        fread (buf, hd.dir_unit_size, 1, fp);
        hd.dir_unit[i] = (NV_CHAR *) calloc (strlen((char*)buf) + 1,
            sizeof (NV_CHAR));
        strcpy (hd.dir_unit[i], (NV_CHAR *) buf);
    }
    free (buf);



    /*  Read restrictions.  */

    utemp = ftell (fp);
    hd.restriction = (NV_CHAR **) calloc (hd.max_restriction_types,
        sizeof (NV_CHAR *));

    if ((buf = (NV_U_BYTE *) calloc (hd.restriction_size,
        sizeof (NV_U_BYTE))) == NULL)
    {
        perror ("Allocating restriction read buffer");
        exit (-1);
    }

    hd.pub.restriction_types = 0;
    for (i = 0 ; i < hd.max_restriction_types ; ++i)
    {
        fread (buf, hd.restriction_size, 1, fp);
        if (!strcmp ((char*)buf, "__END__"))
        {
            hd.pub.restriction_types = i;
            break;
        }
        hd.restriction[i] = (NV_CHAR *) calloc (strlen((char*)buf) + 1,
            sizeof (NV_CHAR));
        strcpy (hd.restriction[i], (NV_CHAR *) buf);
    }
    free (buf);
    fseek (fp, utemp + hd.max_restriction_types * hd.restriction_size,
        SEEK_SET);



    /*  Skip pedigrees. */
    if (hd.pub.major_rev < 2)
      fseek (fp, hd.pedigree_size * NINT (pow (2.0, (NV_FLOAT64) hd.pedigree_bits)), SEEK_CUR);
    hd.pub.pedigree_types = 1;



    /*  Read tzfiles.  */

    utemp = ftell (fp);
    hd.tzfile = (NV_CHAR **) calloc (hd.max_tzfiles, sizeof (NV_CHAR *));

    if ((buf = (NV_U_BYTE *) calloc (hd.tzfile_size, sizeof (NV_U_BYTE))) ==
        NULL)
    {
        perror ("Allocating tzfile read buffer");
        exit (-1);
    }

    hd.pub.tzfiles = 0;
    for (i = 0 ; i < hd.max_tzfiles ; ++i)
    {
        fread (buf, hd.tzfile_size, 1, fp);
        if (!strcmp ((char*)buf, "__END__"))
        {
            hd.pub.tzfiles = i;
            break;
        }
        hd.tzfile[i] = (NV_CHAR *) calloc (strlen((char*)buf) + 1, sizeof (NV_CHAR));
        strcpy (hd.tzfile[i], (NV_CHAR *) buf);
    }
    free (buf);
    fseek (fp, utemp + hd.max_tzfiles * hd.tzfile_size, SEEK_SET);


    /*  Read countries.  */

    utemp = ftell (fp);
    hd.country = (NV_CHAR **) calloc (hd.max_countries, sizeof (NV_CHAR *));

    if ((buf = (NV_U_BYTE *) calloc (hd.country_size, sizeof (NV_U_BYTE))) ==
        NULL)
    {
        perror ("Allocating country read buffer");
        exit (-1);
    }

    hd.pub.countries = 0;
    for (i = 0 ; i < hd.max_countries ; ++i)
    {
        fread (buf, hd.country_size, 1, fp);
        if (!strcmp ((char*)buf, "__END__"))
        {
            hd.pub.countries = i;
            break;
        }
        hd.country[i] = (NV_CHAR *) calloc (strlen((char*)buf) + 1,
            sizeof (NV_CHAR));
        strcpy (hd.country[i], (NV_CHAR *) buf);
    }
    free (buf);
    fseek (fp, utemp + hd.max_countries * hd.country_size, SEEK_SET);


    /*  Read datums.  */

    utemp = ftell (fp);
    hd.datum = (NV_CHAR **) calloc (hd.max_datum_types, sizeof (NV_CHAR *));

    if ((buf = (NV_U_BYTE *) calloc (hd.datum_size, sizeof (NV_U_BYTE))) ==
        NULL)
    {
        perror ("Allocating datum read buffer");
        exit (-1);
    }

    hd.pub.datum_types = 0;
    for (i = 0 ; i < hd.max_datum_types ; ++i)
    {
        fread (buf, hd.datum_size, 1, fp);
        if (!strcmp ((char*)buf, "__END__"))
        {
            hd.pub.datum_types = i;
            break;
        }
        hd.datum[i] = (NV_CHAR *) calloc (strlen((char*)buf) + 1, sizeof (NV_CHAR));
        strcpy (hd.datum[i], (NV_CHAR *) buf);
    }
    free (buf);
    fseek (fp, utemp + hd.max_datum_types * hd.datum_size, SEEK_SET);



    /*  Read legaleses.  */

    if (hd.pub.major_rev < 2) {
      require (hd.legalese = (NV_CHAR **) malloc (sizeof (NV_CHAR *)));
      require (hd.legalese[0] = (NV_CHAR *) malloc (5 * sizeof (NV_CHAR)));
      strcpy (hd.legalese[0], "NULL");
      hd.pub.legaleses = 1;
    } else {
      utemp = ftell (fp);
      hd.legalese = (NV_CHAR **) calloc (hd.max_legaleses, sizeof (NV_CHAR *));

      if ((buf = (NV_U_BYTE *) calloc (hd.legalese_size, sizeof (NV_U_BYTE))) ==
	  NULL)
      {
	  perror ("Allocating legalese read buffer");
	  exit (-1);
      }

      hd.pub.legaleses = 0;
      for (i = 0 ; i < hd.max_legaleses ; ++i)
      {
	  fread (buf, hd.legalese_size, 1, fp);
	  if (!strcmp ((char*)buf, "__END__"))
	  {
	      hd.pub.legaleses = i;
	      break;
	  }
	  hd.legalese[i] = (NV_CHAR *) calloc (strlen((char*)buf) + 1, sizeof (NV_CHAR));
	  strcpy (hd.legalese[i], (NV_CHAR *) buf);
      }
      free (buf);
      fseek (fp, utemp + hd.max_legaleses * hd.legalese_size, SEEK_SET);
    }



    /*  Read constituent names.  */

    hd.constituent =
        (NV_CHAR **) calloc (hd.pub.constituents, sizeof (NV_CHAR *));

    if ((buf = (NV_U_BYTE *) calloc (hd.constituent_size,
        sizeof (NV_U_BYTE))) == NULL)
    {
        perror ("Allocating constituent read buffer");
        exit (-1);
    }

    for (i = 0 ; i < hd.pub.constituents ; ++i)
    {
        fread (buf, hd.constituent_size, 1, fp);
        hd.constituent[i] = (NV_CHAR *) calloc (strlen((char*)buf) + 1,
            sizeof (NV_CHAR));
        strcpy (hd.constituent[i], (NV_CHAR *) buf);
    }
    free (buf);


    if (hd.speed_offset < 0 || hd.equilibrium_offset < 0 ||
        hd.node_offset < 0) {
      fprintf (stderr, "libtcd WARNING:  File: %s\n", filename);
      fprintf (stderr, "WARNING:  This TCD file was created by a pre-version-1.11 libtcd.\n\
Versions of libtcd prior to 1.11 contained a serious bug that can result\n\
in overflows in the speeds, equilibrium arguments, or node factors.  This\n\
database should be rebuilt from the original data if possible.\n");
    }


    /*  NOTE: Using bit_unpack to get integers.  */

    /*  Read speeds.  */

    hd.speed = (NV_FLOAT64 *) calloc (hd.pub.constituents,
        sizeof (NV_FLOAT64));

    pos = 0;
    /* wasted byte bug in V1 */
    if (hd.pub.major_rev < 2)
      size = ((hd.pub.constituents * hd.speed_bits) / 8) + 1;
    else
      size = bits2bytes (hd.pub.constituents * hd.speed_bits);

    if ((buf = (NV_U_BYTE *) calloc (size, sizeof (NV_U_BYTE))) == NULL)
    {
        perror ("Allocating speed read buffer");
        exit (-1);
    }

    fread (buf, size, 1, fp);

    for (i = 0 ; i < hd.pub.constituents ; ++i)
    {
        temp_int = bit_unpack (buf, pos, hd.speed_bits);
        hd.speed[i] = (NV_FLOAT64) (temp_int + hd.speed_offset) /
            hd.speed_scale;
        pos += hd.speed_bits;
        assert (hd.speed[i] >= 0.0);
    }
    free (buf);



    /*  Read equilibrium arguments.  */

    hd.equilibrium = (NV_FLOAT32 **) calloc (hd.pub.constituents,
        sizeof (NV_FLOAT32 *));

    for (i = 0 ; i < hd.pub.constituents ; ++i)
    {
        hd.equilibrium[i] = (NV_FLOAT32 *) calloc (hd.pub.number_of_years,
            sizeof (NV_FLOAT32));
    }



    pos = 0;
    /* wasted byte bug in V1 */
    if (hd.pub.major_rev < 2)
      size = ((hd.pub.constituents * hd.pub.number_of_years *
        hd.equilibrium_bits) / 8) + 1;
    else
      size = bits2bytes (hd.pub.constituents * hd.pub.number_of_years *
        hd.equilibrium_bits);


    if ((buf = (NV_U_BYTE *) calloc (size, sizeof (NV_U_BYTE))) == NULL)
    {
        perror ("Allocating equilibrium read buffer");
        exit (-1);
    }

    fread (buf, size, 1, fp);

    for (i = 0 ; i < hd.pub.constituents ; ++i)
    {
        for (j = 0 ; j < hd.pub.number_of_years ; ++j)
        {
            temp_int = bit_unpack (buf, pos, hd.equilibrium_bits);
            hd.equilibrium[i][j] = (NV_FLOAT32) (temp_int +
                hd.equilibrium_offset) / hd.equilibrium_scale;
            pos += hd.equilibrium_bits;
        }
    }
    free (buf);



    /*  Read node factors.  */

    hd.node_factor = (NV_FLOAT32 **) calloc (hd.pub.constituents,
        sizeof (NV_FLOAT32 *));

    for (i = 0 ; i < hd.pub.constituents ; ++i)
    {
        hd.node_factor[i] =
            (NV_FLOAT32 *) calloc (hd.pub.number_of_years,
            sizeof (NV_FLOAT32));
    }


    pos = 0;
    /* wasted byte bug in V1 */
    if (hd.pub.major_rev < 2)
      size = ((hd.pub.constituents * hd.pub.number_of_years *
        hd.node_bits) / 8) + 1;
    else
      size = bits2bytes (hd.pub.constituents * hd.pub.number_of_years *
        hd.node_bits);


    if ((buf = (NV_U_BYTE *) calloc (size, sizeof (NV_U_BYTE))) == NULL)
    {
        perror ("Allocating node read buffer");
        exit (-1);
    }

    fread (buf, size, 1, fp);

    for (i = 0 ; i < hd.pub.constituents ; ++i)
    {
        for (j = 0 ; j < hd.pub.number_of_years ; ++j)
        {
            temp_int = bit_unpack (buf, pos, hd.node_bits);
            hd.node_factor[i][j] = (NV_FLOAT32) (temp_int +
                hd.node_offset) / hd.node_scale;
            pos += hd.node_bits;
            assert (hd.node_factor[i][j] > 0.0);
        }
    }
    free (buf);


    /*  Read the header portion of all of the records in the file and save
        the record size, address, and name.  */

    /* DWF added test for zero 2003-11-16 -- happens on create new db */
    if (hd.pub.number_of_records) {
      if ((tindex = (TIDE_INDEX *) calloc (hd.pub.number_of_records,
          sizeof (TIDE_INDEX))) == NULL) {
          perror ("Allocating tide index");
          exit (-1);
      }
      /*  Set the first address to be immediately after the header  */
      tindex[0].address = ftell (fp);
    } else tindex = NULL; /* May as well be explicit... */

    for (i = 0 ; i < hd.pub.number_of_records ; ++i)
    {
        /*  Set the address for the next record so that
            read_partial_tide_record will know where to go.  */

        if (i) tindex[i].address = tindex[i - 1].address +
            rec.header.record_size;

        read_partial_tide_record (i, &rec);


        /*  Save the header info in the index.  */

        tindex[i].record_size = rec.header.record_size;
        tindex[i].record_type = rec.header.record_type;
        tindex[i].reference_station = rec.header.reference_station;
        assert (rec.header.tzfile >= 0);
        tindex[i].tzfile = rec.header.tzfile;
        tindex[i].lat = NINT (rec.header.latitude * hd.latitude_scale);
        tindex[i].lon = NINT (rec.header.longitude * hd.longitude_scale);

        if ((tindex[i].name =
            (NV_CHAR *) calloc (strlen (rec.header.name) + 1,
            sizeof (NV_CHAR))) == NULL)
        {
            perror ("Allocating index name memory");
            exit (-1);
        }

        strcpy (tindex[i].name, rec.header.name);
    }


    current_record = -1;
    current_index = -1;

    return (NVTrue);
}


/*****************************************************************************\

    Function        open_tide_db - opens the tide database

    Synopsis        open_tide_db (file);

                    NV_CHAR *file           database file name

    Returns         NV_BOOL                 NVTrue if file opened

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_BOOL open_tide_db (NV_CHAR *file)
{
    assert (file);
    current_record = -1;
    current_index = -1;
    if (fp) {
        if (!strcmp(file,filename) && !modified) return NVTrue;
        else close_tide_db();
    }
    if ((fp = fopen (file, "rb+")) == NULL) {
        if ((fp = fopen (file, "rb")) == NULL) return (NVFalse);
    }
    boundscheck_monologue (file);
    strcpy (filename, file);
    return (read_tide_db_header());
}


/*****************************************************************************\

    Function        close_tide_db - closes the tide database

    Synopsis        close_tide_db ();

    Returns         void

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

    If the global modified flag is true, the database header is rewritten
    before the database is closed.  The modified flag is then cleared.

\*****************************************************************************/

void close_tide_db ()
{
    NV_U_INT32 i;

    if (!fp) {
      fprintf (stderr, "libtcd warning: close_tide_db called when no database open\n");
      return;
    }

    /*  If we've changed something in the file, write the header to reset
        the last modified time.  */

    if (modified) write_tide_db_header ();


    /*  Free all of the temporary memory.  */

    assert (hd.constituent);
    for (i = 0 ; i < hd.pub.constituents ; ++i)
    {
        if (hd.constituent[i] != NULL) free (hd.constituent[i]);
    }
    free (hd.constituent);
    hd.constituent = NULL;

    if (hd.speed != NULL) free (hd.speed);

    assert (hd.equilibrium);
    for (i = 0 ; i < hd.pub.constituents ; ++i)
    {
        if (hd.equilibrium[i] != NULL) free (hd.equilibrium[i]);
    }
    free (hd.equilibrium);
    hd.equilibrium = NULL;

    assert (hd.node_factor);
    for (i = 0 ; i < hd.pub.constituents ; ++i)
    {
        if (hd.node_factor[i] != NULL) free (hd.node_factor[i]);
    }
    free (hd.node_factor);
    hd.node_factor = NULL;

    assert (hd.level_unit);
    for (i = 0 ; i < hd.pub.level_unit_types ; ++i)
    {
        if (hd.level_unit[i] != NULL) free (hd.level_unit[i]);
    }
    free (hd.level_unit);
    hd.level_unit = NULL;

    assert (hd.dir_unit);
    for (i = 0 ; i < hd.pub.dir_unit_types ; ++i)
    {
        if (hd.dir_unit[i] != NULL) free (hd.dir_unit[i]);
    }
    free (hd.dir_unit);
    hd.dir_unit = NULL;

    assert (hd.restriction);
    for (i = 0 ; i < hd.max_restriction_types ; ++i)
    {
        if (hd.restriction[i] != NULL) free (hd.restriction[i]);
    }
    free (hd.restriction);
    hd.restriction = NULL;

    assert (hd.legalese);
    for (i = 0 ; i < hd.max_legaleses ; ++i)
    {
        if (hd.legalese[i] != NULL) free (hd.legalese[i]);
    }
    free (hd.legalese);
    hd.legalese = NULL;

    assert (hd.tzfile);
    for (i = 0 ; i < hd.max_tzfiles ; ++i)
    {
        if (hd.tzfile[i] != NULL) free (hd.tzfile[i]);
    }
    free (hd.tzfile);
    hd.tzfile = NULL;

    assert (hd.country);
    for (i = 0 ; i < hd.max_countries ; ++i)
    {
        if (hd.country[i] != NULL) free (hd.country[i]);
    }
    free (hd.country);
    hd.country = NULL;

    assert (hd.datum);
    for (i = 0 ; i < hd.max_datum_types ; ++i)
    {
        if (hd.datum[i] != NULL) free (hd.datum[i]);
    }
    free (hd.datum);
    hd.datum = NULL;

    /* tindex will still be null on create_tide_db */
    if (tindex) {
      for (i = 0 ; i < hd.pub.number_of_records ; ++i)
      {
          if (tindex[i].name) free (tindex[i].name);
      }
      free (tindex);
      tindex = NULL;
    }

    fclose (fp);
    fp = NULL;
    modified = NVFalse;

    /* Don't nullify the filename; there are places in the code where
       open_tide_db (filename) is invoked after close_tide_db().  This
       does not break the cache logic in open_tide_db because tindex
       is still nullified. */
}


/*****************************************************************************\

    Function        create_tide_db - creates the tide database

    Synopsis        create_tide_db (file, constituents, constituent, speed,
                        start_year, num_years, equilibrium, node_factor);

                    NV_CHAR *file              database file name
                    NV_U_INT32 constituents    number of constituents
                    NV_CHAR *constituent[]     constituent names
                    NV_FLOAT64 *speed          speed values
                    NV_INT32 start_year        start year
                    NV_U_INT32 num_years       number of years
                    NV_FLOAT32 *equilibrium[]  equilibrium arguments
                    NV_FLOAT32 *node_factor[]  node factors

    Returns         NV_BOOL                 NVTrue if file created

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_BOOL create_tide_db (NV_CHAR *file, NV_U_INT32 constituents,
NV_CHAR *constituent[], NV_FLOAT64 *speed, NV_INT32 start_year,
NV_U_INT32 num_years, NV_FLOAT32 *equilibrium[], NV_FLOAT32 *node_factor[])
{
    NV_U_INT32            i, j;
    NV_FLOAT64            min_value, max_value;
    NV_INT32              temp_int;

    /* Validate input */
    assert (file);
    assert (constituent);
    assert (speed);
    assert (equilibrium);
    assert (node_factor);
    for (i = 0 ; i < constituents ; ++i) {
      if (speed[i] < 0.0) {
        fprintf (stderr, "libtcd create_tide_db: somebody tried to set a negative speed (%f)\n", speed[i]);
        return NVFalse;
      }
      for (j = 0 ; j < num_years ; ++j) {
        if (node_factor[i][j] <= 0.0) {
          fprintf (stderr, "libtcd create_tide_db: somebody tried to set a negative or zero node factor (%f)\n", node_factor[i][j]);
          return NVFalse;
        }
      }
    }

    if (fp)
      close_tide_db();

    if ((fp = fopen (file, "wb+")) == NULL) return (NVFalse);

    /*  Zero out the header structure.  */

    memset (&hd, 0, sizeof (hd));

    hd.pub.major_rev = LIBTCD_MAJOR_REV;
    hd.pub.minor_rev = LIBTCD_MINOR_REV;

    hd.header_size = DEFAULT_HEADER_SIZE;
    hd.pub.number_of_records = DEFAULT_NUMBER_OF_RECORDS;

    hd.pub.start_year = start_year;
    hd.pub.number_of_years = num_years;

    hd.pub.constituents = constituents;


    /*  Constituent names.  */

    hd.constituent =
        (NV_CHAR **) calloc (hd.pub.constituents, sizeof (NV_CHAR *));
    for (i = 0 ; i < hd.pub.constituents ; ++i)
    {
        hd.constituent[i] = (NV_CHAR *) calloc (strlen (constituent[i]) + 1,
            sizeof (NV_CHAR));
        strcpy (hd.constituent[i], constituent[i]);
    }


    /* A constituent count is stored with each reference station record,
       and it uses constituent_bits, so we need to be able to store
       the count itself (not just the values 0..count-1). */
    hd.constituent_bits = calculate_bits (hd.pub.constituents);


    /*  Set all of the speed attributes.  */

    hd.speed =  (NV_FLOAT64 *) calloc (hd.pub.constituents,
        sizeof (NV_FLOAT64));

    hd.speed_scale = DEFAULT_SPEED_SCALE;
    min_value = 99999999.0;
    max_value = -99999999.0;
    for (i = 0 ; i < hd.pub.constituents ; ++i)
    {
        if (speed[i] < min_value) min_value = speed[i];
        if (speed[i] > max_value) max_value = speed[i];

        hd.speed[i] = speed[i];
    }

    /* DWF fixed sign reversal 2003-11-16 */
    /* DWF harmonized rounding with the way it is done in write_tide_db_header
       2007-01-22 */
    hd.speed_offset = (NINT (min_value * hd.speed_scale));
    temp_int = NINT (max_value * hd.speed_scale) - hd.speed_offset;
    assert (temp_int >= 0);
    hd.speed_bits = calculate_bits ((NV_U_INT32)temp_int);
    /* Generally 31.  With signed ints we don't have any bits to spare. */
    assert (hd.speed_bits < 32);

    /*  Set all of the equilibrium attributes.  */

    hd.equilibrium = (NV_FLOAT32 **) calloc (hd.pub.constituents,
        sizeof (NV_FLOAT32 *));

    hd.equilibrium_scale = DEFAULT_EQUILIBRIUM_SCALE;
    min_value = 99999999.0;
    max_value = -99999999.0;
    for (i = 0 ; i < hd.pub.constituents ; ++i)
    {
        hd.equilibrium[i] = (NV_FLOAT32 *) calloc (hd.pub.number_of_years,
            sizeof (NV_FLOAT32));
        for (j = 0 ; j < hd.pub.number_of_years ; ++j)
        {
            if (equilibrium[i][j] < min_value) min_value = equilibrium[i][j];
            if (equilibrium[i][j] > max_value) max_value = equilibrium[i][j];

            hd.equilibrium[i][j] = equilibrium[i][j];
        }
    }

    /* DWF fixed sign reversal 2003-11-16 */
    /* DWF harmonized rounding with the way it is done in write_tide_db_header
       2007-01-22 */
    hd.equilibrium_offset = (NINT (min_value * hd.equilibrium_scale));
    temp_int = NINT (max_value * hd.equilibrium_scale) - hd.equilibrium_offset;
    assert (temp_int >= 0);
    hd.equilibrium_bits = calculate_bits ((NV_U_INT32)temp_int);


    /*  Set all of the node factor attributes.  */

    hd.node_factor = (NV_FLOAT32 **) calloc (hd.pub.constituents,
        sizeof (NV_FLOAT32 *));

    hd.node_scale = DEFAULT_NODE_SCALE;
    min_value = 99999999.0;
    max_value = -99999999.0;
    for (i = 0 ; i < hd.pub.constituents ; ++i)
    {
        hd.node_factor[i] = (NV_FLOAT32 *) calloc (hd.pub.number_of_years,
            sizeof (NV_FLOAT32));
        for (j = 0 ; j < hd.pub.number_of_years ; ++j)
        {
            if (node_factor[i][j] < min_value) min_value =
                node_factor[i][j];
            if (node_factor[i][j] > max_value) max_value =
                node_factor[i][j];

            hd.node_factor[i][j] = node_factor[i][j];
        }
    }

    /* DWF fixed sign reversal 2003-11-16 */
    /* DWF harmonized rounding with the way it is done in write_tide_db_header
       2007-01-22 */
    hd.node_offset = (NINT (min_value * hd.node_scale));
    temp_int = NINT (max_value * hd.node_scale) - hd.node_offset;
    assert (temp_int >= 0);
    hd.node_bits = calculate_bits ((NV_U_INT32)temp_int);


    /*  Default city.  */

    hd.amplitude_bits = DEFAULT_AMPLITUDE_BITS;
    hd.amplitude_scale = DEFAULT_AMPLITUDE_SCALE;
    hd.epoch_bits = DEFAULT_EPOCH_BITS;
    hd.epoch_scale = DEFAULT_EPOCH_SCALE;

    hd.record_type_bits = DEFAULT_RECORD_TYPE_BITS;
    hd.latitude_bits = DEFAULT_LATITUDE_BITS;
    hd.latitude_scale = DEFAULT_LATITUDE_SCALE;
    hd.longitude_bits = DEFAULT_LONGITUDE_BITS;
    hd.longitude_scale = DEFAULT_LONGITUDE_SCALE;
    hd.record_size_bits = DEFAULT_RECORD_SIZE_BITS;

    hd.station_bits = DEFAULT_STATION_BITS;

    hd.datum_offset_bits = DEFAULT_DATUM_OFFSET_BITS;
    hd.datum_offset_scale = DEFAULT_DATUM_OFFSET_SCALE;
    hd.date_bits = DEFAULT_DATE_BITS;
    hd.months_on_station_bits = DEFAULT_MONTHS_ON_STATION_BITS;
    hd.confidence_value_bits = DEFAULT_CONFIDENCE_VALUE_BITS;

    hd.time_bits = DEFAULT_TIME_BITS;
    hd.level_add_bits = DEFAULT_LEVEL_ADD_BITS;
    hd.level_add_scale = DEFAULT_LEVEL_ADD_SCALE;
    hd.level_multiply_bits = DEFAULT_LEVEL_MULTIPLY_BITS;
    hd.level_multiply_scale = DEFAULT_LEVEL_MULTIPLY_SCALE;
    hd.direction_bits = DEFAULT_DIRECTION_BITS;

    hd.constituent_size = DEFAULT_CONSTITUENT_SIZE;
    hd.level_unit_size = DEFAULT_LEVEL_UNIT_SIZE;
    hd.dir_unit_size = DEFAULT_DIR_UNIT_SIZE;
    hd.restriction_size = DEFAULT_RESTRICTION_SIZE;
    hd.tzfile_size = DEFAULT_TZFILE_SIZE;
    hd.country_size = DEFAULT_COUNTRY_SIZE;
    hd.datum_size = DEFAULT_DATUM_SIZE;
    hd.legalese_size = DEFAULT_LEGALESE_SIZE;



    /*  Level units.  */

    hd.pub.level_unit_types = DEFAULT_LEVEL_UNIT_TYPES;
    hd.level_unit_bits = calculate_bits (hd.pub.level_unit_types - 1);

    hd.level_unit = (NV_CHAR **) calloc (hd.pub.level_unit_types,
        sizeof (NV_CHAR *));
    for (i = 0 ; i < hd.pub.level_unit_types ; ++i)
    {
        hd.level_unit[i] = (NV_CHAR *) calloc (strlen (level_unit[i]) + 1,
            sizeof (NV_CHAR));
        strcpy (hd.level_unit[i], level_unit[i]);
    }


    /*  Direction units.  */

    hd.pub.dir_unit_types = DEFAULT_DIR_UNIT_TYPES;
    hd.dir_unit_bits = calculate_bits (hd.pub.dir_unit_types - 1);

    hd.dir_unit = (NV_CHAR **) calloc (hd.pub.dir_unit_types,
        sizeof (NV_CHAR *));
    for (i = 0 ; i < hd.pub.dir_unit_types ; ++i)
    {
        hd.dir_unit[i] = (NV_CHAR *) calloc (strlen (dir_unit[i]) + 1,
            sizeof (NV_CHAR));
        strcpy (hd.dir_unit[i], dir_unit[i]);
    }


    /*  Restrictions.  */

    hd.restriction_bits = DEFAULT_RESTRICTION_BITS;
    hd.max_restriction_types = NINT (pow (2.0,
        (NV_FLOAT64) hd.restriction_bits));
    hd.pub.restriction_types = DEFAULT_RESTRICTION_TYPES;

    hd.restriction = (NV_CHAR **) calloc (hd.max_restriction_types,
        sizeof (NV_CHAR *));
    for (i = 0 ; i < hd.max_restriction_types ; ++i)
    {
        if (i == hd.pub.restriction_types) break;

        hd.restriction[i] = (NV_CHAR *) calloc (strlen (restriction[i]) + 1,
            sizeof (NV_CHAR));
        strcpy (hd.restriction[i], restriction[i]);
    }


    /*  Legaleses.  */

    hd.legalese_bits = DEFAULT_LEGALESE_BITS;
    hd.max_legaleses = NINT (pow (2.0, (NV_FLOAT64) hd.legalese_bits));
    hd.pub.legaleses = DEFAULT_LEGALESES;

    hd.legalese = (NV_CHAR **) calloc (hd.max_legaleses,
        sizeof (NV_CHAR *));
    for (i = 0 ; i < hd.max_legaleses ; ++i)
    {
        if (i == hd.pub.legaleses) break;

        hd.legalese[i] = (NV_CHAR *) calloc (strlen (legalese[i]) + 1,
            sizeof (NV_CHAR));
        strcpy (hd.legalese[i], legalese[i]);
    }


    /*  Tzfiles.  */

    hd.tzfile_bits = DEFAULT_TZFILE_BITS;
    hd.max_tzfiles = NINT (pow (2.0, (NV_FLOAT64) hd.tzfile_bits));
    hd.pub.tzfiles = DEFAULT_TZFILES;

    hd.tzfile = (NV_CHAR **) calloc (hd.max_tzfiles, sizeof (NV_CHAR *));
    for (i = 0 ; i < hd.max_tzfiles ; ++i)
    {
        if (i == hd.pub.tzfiles) break;

        hd.tzfile[i] = (NV_CHAR *) calloc (strlen (tzfile[i]) + 1,
            sizeof (NV_CHAR));
        strcpy (hd.tzfile[i], tzfile[i]);
    }


    /*  Countries.  */

    hd.country_bits = DEFAULT_COUNTRY_BITS;
    hd.max_countries = NINT (pow (2.0, (NV_FLOAT64) hd.country_bits));
    hd.pub.countries = DEFAULT_COUNTRIES;

    hd.country = (NV_CHAR **) calloc (hd.max_countries, sizeof (NV_CHAR *));
    for (i = 0 ; i < hd.max_countries ; ++i)
    {
        if (i == hd.pub.countries) break;

        hd.country[i] = (NV_CHAR *) calloc (strlen (country[i]) + 1,
            sizeof (NV_CHAR));
        strcpy (hd.country[i], country[i]);
    }


    /*  Datums.  */

    hd.datum_bits = DEFAULT_DATUM_BITS;
    hd.max_datum_types = NINT (pow (2.0, (NV_FLOAT64) hd.datum_bits));
    hd.pub.datum_types = DEFAULT_DATUM_TYPES;

    hd.datum = (NV_CHAR **) calloc (hd.max_datum_types, sizeof (NV_CHAR *));
    for (i = 0 ; i < hd.max_datum_types ; ++i)
    {
        if (i == hd.pub.datum_types) break;

        hd.datum[i] = (NV_CHAR *) calloc (strlen (datum[i]) + 1,
            sizeof (NV_CHAR));
        strcpy (hd.datum[i], datum[i]);
    }


    /*  Write the header to the file and close. */

    modified = NVTrue;
    close_tide_db ();


    /*  Re-open it and read the header from the file.  */

    i = (open_tide_db (file));


    /*  Set the correct end of file position since the one in the header is
        set to 0.  */
    hd.end_of_file = ftell(fp);
    /* DWF 2004-08-15: if the original program exits without adding any
       records, that doesn't help!  Rewrite the header with correct
       end_of_file. */
    write_tide_db_header ();

    return (i);
}


/*****************************************************************************\
  DWF 2004-10-13
  Used in check_tide_record.
\*****************************************************************************/
static NV_BOOL check_date (NV_U_INT32 date) {
  if (date) {
    unsigned m, d;
    date %= 10000;
    m = date / 100;
    d = date % 100;
    if (m < 1 || m > 12 || d < 1 || d > 31)
      return NVFalse;
  }
  return NVTrue;
}


/*****************************************************************************\
  DWF 2004-10-13
  Returns true iff a record is valid enough to write.  Reports all problems
  to stderr.  The checks are not designed to be airtight (e.g., if you
  use 360 degrees instead of 0 we'll let it slide).

  Mild side effects may occur:
  Note that the units-to-level-units COMPAT114 trick is wedged in here.
\*****************************************************************************/
static NV_BOOL check_tide_record (TIDE_RECORD *rec) {
  NV_U_INT32 i;
  NV_BOOL ret = NVTrue;

  if (!rec) {
    fprintf (stderr, "libtcd error: null pointer passed to check_tide_record\n");
    return NVFalse;
  }

  /* These are all static fields--if a buffer overflow has occurred on one
     of these, other fields might be invalid, but the problem started here. */
  boundscheck_oneliner (rec->header.name);
  boundscheck_oneliner (rec->source);
  boundscheck_monologue (rec->comments);
  boundscheck_monologue (rec->notes);
  boundscheck_oneliner (rec->station_id_context);
  boundscheck_oneliner (rec->station_id);
  boundscheck_monologue (rec->xfields);

#ifdef COMPAT114
  if (rec->header.record_type == REFERENCE_STATION && rec->units > 0)
    rec->level_units = rec->units;
#endif

  if (rec->header.latitude < -90.0 || rec->header.latitude > 90.0 ||
      rec->header.longitude < -180.0 || rec->header.longitude > 180.0) {
    fprintf (stderr, "libtcd error: bad coordinates in tide record\n");
    ret = NVFalse;
  }

  if (rec->header.tzfile < 0 || rec->header.tzfile >= (NV_INT32)hd.pub.tzfiles) {
    fprintf (stderr, "libtcd error: bad tzfile in tide record\n");
    ret = NVFalse;
  }

  if (rec->header.name[0] == '\0') {
    fprintf (stderr, "libtcd error: null name in tide record\n");
    ret = NVFalse;
  }

  if (rec->country < 0 || rec->country >= (NV_INT32)hd.pub.countries) {
    fprintf (stderr, "libtcd error: bad country in tide record\n");
    ret = NVFalse;
  }

  if (rec->restriction >= hd.pub.restriction_types) {
    fprintf (stderr, "libtcd error: bad restriction in tide record\n");
    ret = NVFalse;
  }

  if (rec->legalese >= hd.pub.legaleses) {
    fprintf (stderr, "libtcd error: bad legalese in tide record\n");
    ret = NVFalse;
  }

  if (!check_date (rec->date_imported)) {
    fprintf (stderr, "libtcd error: bad date_imported in tide record\n");
    ret = NVFalse;
  }

  if (rec->direction_units >= hd.pub.dir_unit_types) {
    fprintf (stderr, "libtcd error: bad direction_units in tide record\n");
    ret = NVFalse;
  }

  if (rec->min_direction < 0 || rec->min_direction > 361) {
    fprintf (stderr, "libtcd error: min_direction out of range in tide record\n");
    ret = NVFalse;
  }

  if (rec->max_direction < 0 || rec->max_direction > 361) {
    fprintf (stderr, "libtcd error: max_direction out of range in tide record\n");
    ret = NVFalse;
  }

  if (rec->level_units >= hd.pub.level_unit_types) {
    fprintf (stderr, "libtcd error: bad units in tide record\n");
    ret = NVFalse;
  }

  switch (rec->header.record_type) {
  case REFERENCE_STATION:
    if (rec->header.reference_station != -1) {
      fprintf (stderr, "libtcd error: type 1 record, reference_station != -1\n");
      ret = NVFalse;
    }

    if (rec->datum_offset < -13421.7728 || rec->datum_offset > 13421.7727) {
      fprintf (stderr, "libtcd error: datum_offset out of range in tide record\n");
      ret = NVFalse;
    }

    if (rec->datum < 0 || rec->datum >= (NV_INT32)hd.pub.datum_types) {
      fprintf (stderr, "libtcd error: bad datum in tide record\n");
      ret = NVFalse;
    }

    if (rec->zone_offset < -4096 || rec->zone_offset > 4095 ||
        rec->zone_offset % 100 >= 60) {
      fprintf (stderr, "libtcd error: bad zone_offset in tide record\n");
      ret = NVFalse;
    }

    if (!check_date (rec->expiration_date)) {
      fprintf (stderr, "libtcd error: bad expiration_date in tide record\n");
      ret = NVFalse;
    }

    if (rec->months_on_station > 1023) {
      fprintf (stderr, "libtcd error: months_on_station out of range in tide record\n");
      ret = NVFalse;
    }

    if (!check_date (rec->last_date_on_station)) {
      fprintf (stderr, "libtcd error: bad last_date_on_station in tide record\n");
      ret = NVFalse;
    }

    if (rec->confidence > 15) {
      fprintf (stderr, "libtcd error: confidence out of range in tide record\n");
      ret = NVFalse;
    }

    /* Only issue each error once. */
    for (i=0; i < hd.pub.constituents; ++i) {
      if (rec->amplitude[i] < 0.0 || rec->amplitude[i] > 52.4287) {
        fprintf (stderr, "libtcd error: constituent amplitude out of range in tide record\n");
        ret = NVFalse;
        break;
      }
    }
    for (i=0; i < hd.pub.constituents; ++i) {
      if (rec->epoch[i] < 0.0 || rec->epoch[i] > 360.0) {
        fprintf (stderr, "libtcd error: constituent epoch out of range in tide record\n");
        ret = NVFalse;
        break;
      }
    }

    break;

  case SUBORDINATE_STATION:
    if (rec->header.reference_station < 0 || rec->header.reference_station
    >= (NV_INT32)hd.pub.number_of_records) {
      fprintf (stderr, "libtcd error: bad reference_station in tide record\n");
      ret = NVFalse;
    }

    if (rec->min_time_add < -4096 || rec->min_time_add > 4095 ||
        rec->min_time_add % 100 >= 60) {
      fprintf (stderr, "libtcd error: bad min_time_add in tide record\n");
      ret = NVFalse;
    }

    if (rec->min_level_add < -65.536 || rec->min_level_add > 65.535) {
      fprintf (stderr, "libtcd error: min_level_add out of range in tide record\n");
      ret = NVFalse;
    }

    if (rec->min_level_multiply < 0.0 || rec->min_level_multiply > 65.535) {
      fprintf (stderr, "libtcd error: min_level_multiply out of range in tide record\n");
      ret = NVFalse;
    }

    if (rec->max_time_add < -4096 || rec->max_time_add > 4095 ||
        rec->max_time_add % 100 >= 60) {
      fprintf (stderr, "libtcd error: bad max_time_add in tide record\n");
      ret = NVFalse;
    }

    if (rec->max_level_add < -65.536 || rec->max_level_add > 65.535) {
      fprintf (stderr, "libtcd error: max_level_add out of range in tide record\n");
      ret = NVFalse;
    }

    if (rec->max_level_multiply < 0.0 || rec->max_level_multiply > 65.535) {
      fprintf (stderr, "libtcd error: max_level_multiply out of range in tide record\n");
      ret = NVFalse;
    }

    if (rec->flood_begins != NULLSLACKOFFSET && (rec->flood_begins < -4096 ||
    rec->flood_begins > 4095 || rec->flood_begins % 100 >= 60)) {
      fprintf (stderr, "libtcd error: bad flood_begins in tide record\n");
      ret = NVFalse;
    }

    if (rec->ebb_begins != NULLSLACKOFFSET && (rec->ebb_begins < -4096 ||
    rec->ebb_begins > 4095 || rec->ebb_begins % 100 >= 60)) {
      fprintf (stderr, "libtcd error: bad ebb_begins in tide record\n");
      ret = NVFalse;
    }

    break;

  default:
    fprintf (stderr, "libtcd error: invalid record_type in tide record\n");
    ret = NVFalse;
  }

  if (ret == NVFalse)
    dump_tide_record (rec);
  return ret;
}


/*****************************************************************************\
  DWF 2004-10-13
  Calculate size of a tide record as it would be encoded in the TCD file.
  Size is stored in record_size field.  Return is number of constituents
  that will be encoded.
\*****************************************************************************/
static NV_U_INT32 figure_size (TIDE_RECORD *rec) {
  NV_U_INT32 i, count=0, name_size, source_size, comments_size,
    notes_size, station_id_context_size, station_id_size, xfields_size;

  assert (rec);

  /*  Figure out how many bits we'll need for this record. */

  name_size = strlen(clip_string(rec->header.name))+1;
  source_size = strlen(clip_string(rec->source))+1;
  comments_size = strlen(clip_string(rec->comments))+1;
  notes_size = strlen(clip_string(rec->notes))+1;
  station_id_context_size = strlen(clip_string(rec->station_id_context))+1;
  station_id_size = strlen(clip_string(rec->station_id))+1;
  /* No clipping on xfields -- trailing \n required by syntax */
  xfields_size = strlen(rec->xfields)+1;

  rec->header.record_size =
      hd.record_size_bits +
      hd.record_type_bits +
      hd.latitude_bits +
      hd.longitude_bits +
      hd.station_bits +
      hd.tzfile_bits +
      (name_size * 8) +

      hd.country_bits +
      (source_size  * 8) +
      hd.restriction_bits +
      (comments_size * 8) +
      (notes_size * 8) +
      hd.legalese_bits +
      (station_id_context_size * 8) +
      (station_id_size * 8) +
      hd.date_bits + 
      (xfields_size * 8) +
      hd.dir_unit_bits +
      hd.direction_bits +
      hd.direction_bits +
      hd.level_unit_bits;

  switch (rec->header.record_type) {
  case REFERENCE_STATION:
    rec->header.record_size +=
        hd.datum_offset_bits +
        hd.datum_bits +
        hd.time_bits +
        hd.date_bits +
        hd.months_on_station_bits +
        hd.date_bits +
        hd.confidence_value_bits +
        hd.constituent_bits;

    for (i = 0 ; i < hd.pub.constituents ; ++i)
    {
        assert (rec->amplitude[i] >= 0.0);
        if (rec->amplitude[i] >= AMPLITUDE_EPSILON) ++count;
    }

    rec->header.record_size +=
        (count * hd.constituent_bits +
        count * hd.amplitude_bits +
        count * hd.epoch_bits);

    break;

  case SUBORDINATE_STATION:
    rec->header.record_size +=
        hd.time_bits +
        hd.level_add_bits +
        hd.level_multiply_bits +
        hd.time_bits +
        hd.level_add_bits +
        hd.level_multiply_bits +
        hd.time_bits +
        hd.time_bits;
    break;

  default:
    assert (0);
  }

  rec->header.record_size = bits2bytes (rec->header.record_size);
  return count;
}


/*****************************************************************************\
DWF 2004-10-14
\*****************************************************************************/
static void pack_string (NV_U_BYTE *buf, NV_U_INT32 *pos, NV_CHAR *s) {
  NV_U_INT32 i, temp_size;
  assert (buf);
  assert (pos);
  assert (s);
  temp_size = strlen(s)+1;
  for (i=0; i<temp_size; ++i) {
    bit_pack (buf, *pos, 8, s[i]);
    *pos += 8;
  }
}


/*****************************************************************************\

    Function        pack_tide_record - convert TIDE_RECORD to packed form

    Synopsis        pack_tide_record (rec, bufptr, bufsize);

                    TIDE_RECORD *rec        tide record (in)
                    NV_U_BYTE **bufptr      packed record (out)
                    NV_U_INT32 *bufsize     size of buf in bytes (out)

                    buf is allocated by pack_tide_record and should be
                    freed by the caller.

    Returns         void

    Author          Extracted from write_tide_record by David Flater
    Date            2006-05-26

\*****************************************************************************/

static void pack_tide_record (TIDE_RECORD *rec, NV_U_BYTE **bufptr,
NV_U_INT32 *bufsize) {
  NV_U_INT32              i, pos, constituent_count;
  NV_INT32                temp_int;
  NV_U_BYTE               *buf;

  /* Validate input */
  assert (rec);
  /* Cursory check for buffer overflows.  Should not happen here --
     check_tide_record does a more thorough job when called by add_tide_record
     and update_tide_record. */
  boundscheck_oneliner (rec->header.name);
  boundscheck_oneliner (rec->source);
  boundscheck_monologue (rec->comments);
  boundscheck_monologue (rec->notes);
  boundscheck_oneliner (rec->station_id_context);
  boundscheck_oneliner (rec->station_id);
  boundscheck_monologue (rec->xfields);

  constituent_count = figure_size (rec);

  if (!(*bufptr = (NV_U_BYTE *) calloc (rec->header.record_size,
				    sizeof (NV_U_BYTE)))) {
    perror ("libtcd can't allocate memory in pack_tide_record");
    exit (-1);
  }
  buf = *bufptr; /* To conserve asterisks */

  /*  Bit pack the common section.  "pos" is the bit position within the
      buffer "buf".  */

  pos = 0;

  bit_pack (buf, pos, hd.record_size_bits, rec->header.record_size);
  pos += hd.record_size_bits;

  bit_pack (buf, pos, hd.record_type_bits, rec->header.record_type);
  pos += hd.record_type_bits;

  temp_int = NINT (rec->header.latitude * hd.latitude_scale);
  bit_pack (buf, pos, hd.latitude_bits, temp_int);
  pos += hd.latitude_bits;

  temp_int = NINT (rec->header.longitude * hd.longitude_scale);
  bit_pack (buf, pos, hd.longitude_bits, temp_int);
  pos += hd.longitude_bits;

  /* This ordering doesn't match everywhere else but there's no technical
     reason to change it from its V1 ordering.  To do so would force
     another conditional in unpack_partial_tide_record. */

  bit_pack (buf, pos, hd.tzfile_bits, rec->header.tzfile);
  pos += hd.tzfile_bits;

  pack_string (buf, &pos, clip_string(rec->header.name));

  bit_pack (buf, pos, hd.station_bits, rec->header.reference_station);
  pos += hd.station_bits;

  bit_pack (buf, pos, hd.country_bits, rec->country);
  pos += hd.country_bits;

  pack_string (buf, &pos, clip_string(rec->source));

  bit_pack (buf, pos, hd.restriction_bits, rec->restriction);
  pos += hd.restriction_bits;

  pack_string (buf, &pos, clip_string(rec->comments));
  pack_string (buf, &pos, clip_string(rec->notes));

  bit_pack (buf, pos, hd.legalese_bits, rec->legalese);
  pos += hd.legalese_bits;

  pack_string (buf, &pos, clip_string(rec->station_id_context));
  pack_string (buf, &pos, clip_string(rec->station_id));

  bit_pack (buf, pos, hd.date_bits, rec->date_imported);
  pos += hd.date_bits;

  /* No clipping on xfields -- trailing \n required by syntax */
  pack_string (buf, &pos, rec->xfields);

  bit_pack (buf, pos, hd.dir_unit_bits, rec->direction_units);
  pos += hd.dir_unit_bits;

  bit_pack (buf, pos, hd.direction_bits, rec->min_direction);
  pos += hd.direction_bits;

  bit_pack (buf, pos, hd.direction_bits, rec->max_direction);
  pos += hd.direction_bits;

  /* The units-to-level-units compatibility hack is in check_tide_record */
  bit_pack (buf, pos, hd.level_unit_bits, rec->level_units);
  pos += hd.level_unit_bits;

  /*  Bit pack record type 1 records.  */

  if (rec->header.record_type == REFERENCE_STATION) {
      temp_int = NINT (rec->datum_offset * hd.datum_offset_scale);
      bit_pack (buf, pos, hd.datum_offset_bits, temp_int);
      pos += hd.datum_offset_bits;

      bit_pack (buf, pos, hd.datum_bits, rec->datum);
      pos += hd.datum_bits;

      bit_pack (buf, pos, hd.time_bits, rec->zone_offset);
      pos += hd.time_bits;

      bit_pack (buf, pos, hd.date_bits, rec->expiration_date);
      pos += hd.date_bits;

      bit_pack (buf, pos, hd.months_on_station_bits,
	  rec->months_on_station);
      pos += hd.months_on_station_bits;

      bit_pack (buf, pos, hd.date_bits, rec->last_date_on_station);
      pos += hd.date_bits;

      bit_pack (buf, pos, hd.confidence_value_bits, rec->confidence);
      pos += hd.confidence_value_bits;

      bit_pack (buf, pos, hd.constituent_bits, constituent_count);
      pos += hd.constituent_bits;

      for (i = 0 ; i < hd.pub.constituents ; ++i)
      {
	  if (rec->amplitude[i] >= AMPLITUDE_EPSILON)
	  {
	      bit_pack (buf, pos, hd.constituent_bits, i);
	      pos += hd.constituent_bits;

	      temp_int = NINT (rec->amplitude[i] * hd.amplitude_scale);
	      assert (temp_int);
	      bit_pack (buf, pos, hd.amplitude_bits, temp_int);
	      pos += hd.amplitude_bits;

	      temp_int = NINT (rec->epoch[i] * hd.epoch_scale);
	      bit_pack (buf, pos, hd.epoch_bits, temp_int);
	      pos += hd.epoch_bits;
	  }
      }
  }

  /*  Bit pack record type 2 records.  */
  else if (rec->header.record_type == SUBORDINATE_STATION) {
      bit_pack (buf, pos, hd.time_bits, rec->min_time_add);
      pos += hd.time_bits;

      temp_int = NINT (rec->min_level_add * hd.level_add_scale);
      bit_pack (buf, pos, hd.level_add_bits, temp_int);
      pos += hd.level_add_bits;

      temp_int = NINT (rec->min_level_multiply * hd.level_multiply_scale);
      bit_pack (buf, pos, hd.level_multiply_bits, temp_int);
      pos += hd.level_multiply_bits;

      bit_pack (buf, pos, hd.time_bits, rec->max_time_add);
      pos += hd.time_bits;

      temp_int = NINT (rec->max_level_add * hd.level_add_scale);
      bit_pack (buf, pos, hd.level_add_bits, temp_int);
      pos += hd.level_add_bits;

      temp_int = NINT (rec->max_level_multiply * hd.level_multiply_scale);
      bit_pack (buf, pos, hd.level_multiply_bits, temp_int);
      pos += hd.level_multiply_bits;

      bit_pack (buf, pos, hd.time_bits, rec->flood_begins);
      pos += hd.time_bits;

      bit_pack (buf, pos, hd.time_bits, rec->ebb_begins);
      pos += hd.time_bits;
  }

  else {
    fprintf (stderr, "libtcd error:  Record type %d is undefined\n",
	     rec->header.record_type);
    exit (-1);
  }

  *bufsize = rec->header.record_size;
  assert (*bufsize == bits2bytes (pos));
}


/*****************************************************************************\

    Function        write_tide_record - writes a tide record to the database

    Synopsis        write_tide_record (num, rec);

                    NV_INT32 num            record number:
                                            >= 0 overwrite record num
                                              -1 write at current file position
                    TIDE_RECORD *rec        tide record

    Returns         NV_BOOL                 NVTrue if successful

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

    hd.end_of_file is not updated by this function in any event.

\*****************************************************************************/

static NV_BOOL write_tide_record (NV_INT32 num, TIDE_RECORD *rec)
{
    NV_U_BYTE               *buf = NULL;
    NV_U_INT32              bufsize = 0;

    if (!fp) {
      fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
      return NVFalse;
    }
    write_protect();

    pack_tide_record (rec, &buf, &bufsize);

    if (num == -1)
      ;
    else if (num >= 0)
      fseek (fp, tindex[num].address, SEEK_SET);
    else
      assert (0);

    fwrite (buf, bufsize, 1, fp);
    free (buf);
    modified = NVTrue;
    return NVTrue;
}


/*****************************************************************************\

    Function        read_next_tide_record - reads the next tide record from
                    the database

    Synopsis        read_next_tide_record (rec);

                    TIDE_RECORD *rec        tide record

    Returns         NV_INT32                record number of the tide record

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_INT32 read_next_tide_record (TIDE_RECORD *rec)
{
  return (read_tide_record (current_record + 1, rec));
}


/*****************************************************************************\

    Function        unpack_tide_record - convert TIDE_RECORD from packed form

    Synopsis        unpack_tide_record (buf, bufsize, rec);

                    NV_U_BYTE *buf          packed record (in)
                    NV_U_INT32 bufsize      size of buf in bytes (in)
                    TIDE_RECORD *rec        tide record (in-out)

                    rec must be allocated by the caller.

    Returns         void

    Author          Extracted from read_tide_record by David Flater
    Date            2006-05-26

    rec->header.record_number is initialized from the global current_record.

\*****************************************************************************/

static void unpack_tide_record (NV_U_BYTE *buf, NV_U_INT32 bufsize,
TIDE_RECORD *rec) {
  NV_INT32                temp_int;
  NV_U_INT32              i, j, pos, count;

  assert (rec);

  /* Initialize record */
  memset (rec, 0, sizeof (TIDE_RECORD));
  {
    int r = find_dir_units ("degrees true");
    assert (r > 0);
    rec->direction_units = (NV_U_BYTE)r;
  }
  rec->min_direction = rec->max_direction = 361;
  rec->flood_begins = rec->ebb_begins = NULLSLACKOFFSET;
  rec->header.record_number = current_record;

  unpack_partial_tide_record (buf, bufsize, rec, &pos);

  switch (rec->header.record_type) {
  case REFERENCE_STATION:
  case SUBORDINATE_STATION:
    break;
  default:
    fprintf (stderr, "libtcd fatal error: tried to read type %d tide record.\n", rec->header.record_type);
    fprintf (stderr, "This version of libtcd only supports types 1 and 2.  Perhaps you should\nupgrade.\n");
    exit (-1);
  }

  switch (hd.pub.major_rev) {

    /************************* TCD V1 *****************************/
  case 0:
  case 1:

    /*  "pos" is the bit position within the buffer "buf".  */

    rec->country = bit_unpack (buf, pos, hd.country_bits);
    pos += hd.country_bits;

    /* pedigree */
    pos += hd.pedigree_bits;

    unpack_string (buf, bufsize, &pos, rec->source, ONELINER_LENGTH, "source field");

    rec->restriction = bit_unpack (buf, pos, hd.restriction_bits);
    pos += hd.restriction_bits;

    unpack_string (buf, bufsize, &pos, rec->comments, MONOLOGUE_LENGTH, "comments field");

    if (rec->header.record_type == REFERENCE_STATION) {
      rec->level_units = bit_unpack (buf, pos, hd.level_unit_bits);
#ifdef COMPAT114
      rec->units = rec->level_units;
#endif
      pos += hd.level_unit_bits;

      temp_int = signed_bit_unpack (buf, pos, hd.datum_offset_bits);
      rec->datum_offset = (NV_FLOAT32) temp_int / hd.datum_offset_scale;
      pos += hd.datum_offset_bits;

      rec->datum = bit_unpack (buf, pos, hd.datum_bits);
      pos += hd.datum_bits;

      rec->zone_offset = signed_bit_unpack (buf, pos, hd.time_bits);
      pos += hd.time_bits;

      rec->expiration_date = bit_unpack (buf, pos, hd.date_bits);
      pos += hd.date_bits;

      rec->months_on_station = bit_unpack (buf, pos,
          hd.months_on_station_bits);
      pos += hd.months_on_station_bits;

      rec->last_date_on_station = bit_unpack (buf, pos, hd.date_bits);
      pos += hd.date_bits;

      rec->confidence = bit_unpack (buf, pos, hd.confidence_value_bits);
      pos += hd.confidence_value_bits;

      for (i = 0 ; i < hd.pub.constituents ; ++i) {
        rec->amplitude[i] = 0.0;
        rec->epoch[i] = 0.0;
      }

      count = bit_unpack (buf, pos, hd.constituent_bits);
      pos += hd.constituent_bits;

      for (i = 0 ; i < count ; ++i) {
        j = bit_unpack (buf, pos, hd.constituent_bits);
        pos += hd.constituent_bits;

        rec->amplitude[j] = (NV_FLOAT32) bit_unpack (buf, pos,
            hd.amplitude_bits) / hd.amplitude_scale;
        pos += hd.amplitude_bits;

        rec->epoch[j] = (NV_FLOAT32) bit_unpack (buf, pos, hd.epoch_bits) /
            hd.epoch_scale;
        pos += hd.epoch_bits;
      }
    } else if (rec->header.record_type == SUBORDINATE_STATION) {
      rec->level_units = bit_unpack (buf, pos, hd.level_unit_bits);
      pos += hd.level_unit_bits;

      rec->direction_units = bit_unpack (buf, pos, hd.dir_unit_bits);
      pos += hd.dir_unit_bits;

      /* avg_level_units */
      pos += hd.level_unit_bits;

      rec->min_time_add = signed_bit_unpack (buf, pos, hd.time_bits);
      pos += hd.time_bits;

      temp_int = signed_bit_unpack (buf, pos, hd.level_add_bits);
      rec->min_level_add = (NV_FLOAT32) temp_int / hd.level_add_scale;
      pos += hd.level_add_bits;

      /* Signed in V1 */
      temp_int = signed_bit_unpack (buf, pos, hd.level_multiply_bits);
      rec->min_level_multiply = (NV_FLOAT32) temp_int /
          hd.level_multiply_scale;
      pos += hd.level_multiply_bits;

      /* min_avg_level */
      pos += hd.level_add_bits;

      rec->min_direction = bit_unpack (buf, pos, hd.direction_bits);
      pos += hd.direction_bits;

      rec->max_time_add = signed_bit_unpack (buf, pos, hd.time_bits);
      pos += hd.time_bits;

      temp_int = signed_bit_unpack (buf, pos, hd.level_add_bits);
      rec->max_level_add = (NV_FLOAT32) temp_int / hd.level_add_scale;
      pos += hd.level_add_bits;

      /* Signed in V1 */
      temp_int = signed_bit_unpack (buf, pos, hd.level_multiply_bits);
      rec->max_level_multiply = (NV_FLOAT32) temp_int /
          hd.level_multiply_scale;
      pos += hd.level_multiply_bits;

      /* max_avg_level */
      pos += hd.level_add_bits;

      rec->max_direction = bit_unpack (buf, pos, hd.direction_bits);
      pos += hd.direction_bits;

      rec->flood_begins = signed_bit_unpack (buf, pos, hd.time_bits);
      pos += hd.time_bits;

      rec->ebb_begins = signed_bit_unpack (buf, pos, hd.time_bits);
      pos += hd.time_bits;
    } else {
      assert (0);
    }
    break;

    /************************* TCD V2 *****************************/
  case 2:
    rec->country = bit_unpack (buf, pos, hd.country_bits);
    pos += hd.country_bits;

    unpack_string (buf, bufsize, &pos, rec->source, ONELINER_LENGTH, "source field");

    rec->restriction = bit_unpack (buf, pos, hd.restriction_bits);
    pos += hd.restriction_bits;

    unpack_string (buf, bufsize, &pos, rec->comments, MONOLOGUE_LENGTH, "comments field");
    unpack_string (buf, bufsize, &pos, rec->notes, MONOLOGUE_LENGTH, "notes field");

    rec->legalese = bit_unpack (buf, pos, hd.legalese_bits);
    pos += hd.legalese_bits;

    unpack_string (buf, bufsize, &pos, rec->station_id_context, ONELINER_LENGTH, "station_id_context field");
    unpack_string (buf, bufsize, &pos, rec->station_id, ONELINER_LENGTH, "station_id field");

    rec->date_imported = bit_unpack (buf, pos, hd.date_bits);
    pos += hd.date_bits;

    unpack_string (buf, bufsize, &pos, rec->xfields, MONOLOGUE_LENGTH, "xfields field");

    rec->direction_units = bit_unpack (buf, pos, hd.dir_unit_bits);
    pos += hd.dir_unit_bits;

    rec->min_direction = bit_unpack (buf, pos, hd.direction_bits);
    pos += hd.direction_bits;

    rec->max_direction = bit_unpack (buf, pos, hd.direction_bits);
    pos += hd.direction_bits;

    rec->level_units = bit_unpack (buf, pos, hd.level_unit_bits);
#ifdef COMPAT114
    rec->units = rec->level_units;
#endif
    pos += hd.level_unit_bits;

    if (rec->header.record_type == REFERENCE_STATION) {
      temp_int = signed_bit_unpack (buf, pos, hd.datum_offset_bits);
      rec->datum_offset = (NV_FLOAT32) temp_int / hd.datum_offset_scale;
      pos += hd.datum_offset_bits;

      rec->datum = bit_unpack (buf, pos, hd.datum_bits);
      pos += hd.datum_bits;

      rec->zone_offset = signed_bit_unpack (buf, pos, hd.time_bits);
      pos += hd.time_bits;

      rec->expiration_date = bit_unpack (buf, pos, hd.date_bits);
      pos += hd.date_bits;

      rec->months_on_station = bit_unpack (buf, pos,
          hd.months_on_station_bits);
      pos += hd.months_on_station_bits;

      rec->last_date_on_station = bit_unpack (buf, pos, hd.date_bits);
      pos += hd.date_bits;

      rec->confidence = bit_unpack (buf, pos, hd.confidence_value_bits);
      pos += hd.confidence_value_bits;

      for (i = 0 ; i < hd.pub.constituents ; ++i) {
        rec->amplitude[i] = 0.0;
        rec->epoch[i] = 0.0;
      }

      count = bit_unpack (buf, pos, hd.constituent_bits);
      pos += hd.constituent_bits;

      for (i = 0 ; i < count ; ++i) {
        j = bit_unpack (buf, pos, hd.constituent_bits);
        pos += hd.constituent_bits;

        rec->amplitude[j] = (NV_FLOAT32) bit_unpack (buf, pos,
            hd.amplitude_bits) / hd.amplitude_scale;
        pos += hd.amplitude_bits;

        rec->epoch[j] = (NV_FLOAT32) bit_unpack (buf, pos, hd.epoch_bits) /
            hd.epoch_scale;
        pos += hd.epoch_bits;
      }
    } else if (rec->header.record_type == SUBORDINATE_STATION) {
      rec->min_time_add = signed_bit_unpack (buf, pos, hd.time_bits);
      pos += hd.time_bits;

      temp_int = signed_bit_unpack (buf, pos, hd.level_add_bits);
      rec->min_level_add = (NV_FLOAT32) temp_int / hd.level_add_scale;
      pos += hd.level_add_bits;

      /* Made unsigned in V2 */
      temp_int = bit_unpack (buf, pos, hd.level_multiply_bits);
      rec->min_level_multiply = (NV_FLOAT32) temp_int /
          hd.level_multiply_scale;
      pos += hd.level_multiply_bits;

      rec->max_time_add = signed_bit_unpack (buf, pos, hd.time_bits);
      pos += hd.time_bits;

      temp_int = signed_bit_unpack (buf, pos, hd.level_add_bits);
      rec->max_level_add = (NV_FLOAT32) temp_int / hd.level_add_scale;
      pos += hd.level_add_bits;

      /* Made unsigned in V2 */
      temp_int = bit_unpack (buf, pos, hd.level_multiply_bits);
      rec->max_level_multiply = (NV_FLOAT32) temp_int /
          hd.level_multiply_scale;
      pos += hd.level_multiply_bits;

      rec->flood_begins = signed_bit_unpack (buf, pos, hd.time_bits);
      pos += hd.time_bits;

      rec->ebb_begins = signed_bit_unpack (buf, pos, hd.time_bits);
      pos += hd.time_bits;
    } else {
      assert (0);
    }
    break;

  default:
    assert (0);
  }

  assert (pos <= bufsize*8);
}


/*****************************************************************************\

    Function        read_tide_record - reads tide record "num" from the
                    database

    Synopsis        read_tide_record (num, rec);

                    NV_INT32 num            record number (in)
                    TIDE_RECORD *rec        tide record (in-out)

                    rec must be allocated by the caller.

    Returns         NV_INT32                num if success, -1 if failure

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_INT32 read_tide_record (NV_INT32 num, TIDE_RECORD *rec)
{
  NV_U_BYTE               *buf;
  NV_U_INT32              bufsize;

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    return -1;
  }

  if (num < 0 || num >= (NV_INT32)hd.pub.number_of_records)
    return -1;
  assert (rec);

  bufsize = tindex[num].record_size;
  if ((buf = (NV_U_BYTE *) calloc (bufsize, sizeof (NV_U_BYTE))) == NULL)
  {
      perror ("Allocating read_tide_record buffer");
      exit (-1);
  }

  current_record = num;
  require (fseek (fp, tindex[num].address, SEEK_SET) == 0);
  require (fread (buf, tindex[num].record_size, 1, fp) == 1);
  unpack_tide_record (buf, bufsize, rec);
  free (buf);
  return num;
}


/*****************************************************************************\

    Function        add_tide_record - adds a tide record to the database

    Synopsis        add_tide_record (rec);

                    TIDE_RECORD *rec        tide record

    Returns         NV_BOOL                 NVTrue if successful

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_BOOL add_tide_record (TIDE_RECORD *rec, DB_HEADER_PUBLIC *db)
{
    NV_INT32                pos;

    if (!fp) {
      fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
      return NVFalse;
    }
    write_protect();

    if (!check_tide_record (rec))
      return NVFalse;

    fseek (fp, hd.end_of_file, SEEK_SET);
    pos = ftell (fp);
    assert (pos > 0);

    rec->header.record_number = hd.pub.number_of_records++;

    if (write_tide_record (-1, rec))
    {
        if ((tindex = (TIDE_INDEX *) realloc (tindex, hd.pub.number_of_records *
            sizeof (TIDE_INDEX))) == NULL)
        {
            perror ("Allocating more index records");
            exit (-1);
        }

        tindex[rec->header.record_number].address = pos;
        tindex[rec->header.record_number].record_size = rec->header.record_size;
        tindex[rec->header.record_number].record_type = rec->header.record_type;
        tindex[rec->header.record_number].reference_station =
            rec->header.reference_station;
        assert (rec->header.tzfile >= 0);
        tindex[rec->header.record_number].tzfile = rec->header.tzfile;
        tindex[rec->header.record_number].lat = NINT (rec->header.latitude *
            hd.latitude_scale);
        tindex[rec->header.record_number].lon = NINT (rec->header.longitude *
            hd.longitude_scale);


        if ((tindex[rec->header.record_number].name =
            (NV_CHAR *) calloc (strlen (rec->header.name) + 1,
            sizeof (NV_CHAR))) == NULL)
        {
            perror ("Allocating index name memory");
            exit (-1);
        }


        strcpy (tindex[rec->header.record_number].name, rec->header.name);
        pos = ftell (fp);
        assert (pos > 0);
        hd.end_of_file = pos;
        modified = NVTrue;

        /*  Get the new number of records.  */
        if (db)
          *db = hd.pub;

        return NVTrue;
    }

    return NVFalse;
}


/*****************************************************************************\

    Function        delete_tide_record - deletes a record and all subordinate
                    records from the database

    Synopsis        delete_tide_record (num);

                    NV_INT32 num            record number

    Returns         NV_BOOL                 NVTrue if successful

    Author          Jan C. Depner (redone by David Flater)
    Date            08/01/02 (2006-05-26)

    See libtcd.html for changelog.

\*****************************************************************************/

NV_BOOL delete_tide_record (NV_INT32 num, DB_HEADER_PUBLIC *db)
{
  NV_INT32          i, newrecnum, *map;
  NV_U_BYTE         **allrecs_packed;

  if (!fp) {
    fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
    return NVFalse;
  }
  write_protect();

  if (num < 0 || num >= (NV_INT32)hd.pub.number_of_records) return NVFalse;

  /* Allocate workspace */

  if (!(map = (NV_INT32 *) malloc (hd.pub.number_of_records * sizeof(NV_INT32)))) {
    perror ("libtcd: delete_tide_record: can't malloc");
    return NVFalse;
  }
  if (!(allrecs_packed = (NV_U_BYTE **) malloc (hd.pub.number_of_records * sizeof(NV_U_BYTE*)))) {
    perror ("libtcd: delete_tide_record: can't malloc");
    free (map);
    return NVFalse;
  }

  /* First pass: read in database, build record number map and mark records
     for deletion */

  require (fseek (fp, tindex[0].address, SEEK_SET) == 0);
  for (newrecnum=0,i=0; i<(NV_INT32)hd.pub.number_of_records; ++i) {
    assert (ftell(fp) == tindex[i].address);
    if (i == num || (tindex[i].record_type == SUBORDINATE_STATION && tindex[i].reference_station == num)) {
      map[i] = -1;
      allrecs_packed[i] = NULL;
      require (fseek (fp, tindex[i].record_size, SEEK_CUR) == 0);
    } else {
      map[i] = newrecnum++;
      if (!(allrecs_packed[i] = (NV_U_BYTE *) malloc (tindex[i].record_size))) {
	perror ("libtcd: delete_tide_record: can't malloc");
	for (--i; i>=0; --i)
	  free (allrecs_packed[i]);
	free (allrecs_packed);
	free (map);
	return NVFalse;
      }
      require (fread (allrecs_packed[i], tindex[i].record_size, 1, fp) == 1);
    }
  }

  /* Second pass: rewrite database and fix substation linkage */

  require (fseek (fp, tindex[0].address, SEEK_SET) == 0);
  require (ftruncate (fileno(fp), tindex[0].address) == 0);

  for (i=0; i<(NV_INT32)hd.pub.number_of_records; ++i)
    if (map[i] >= 0) {
      if (tindex[i].record_type == SUBORDINATE_STATION) {
        assert (tindex[i].reference_station >= 0);
        assert (tindex[i].reference_station <= (NV_INT32)hd.pub.number_of_records);
        if (map[tindex[i].reference_station] != tindex[i].reference_station) {
          /* Fix broken reference station linkage */
          TIDE_RECORD rec;
          unpack_tide_record (allrecs_packed[i], tindex[i].record_size, &rec);
          free (allrecs_packed[i]);
          rec.header.reference_station = map[tindex[i].reference_station];
          pack_tide_record (&rec, &(allrecs_packed[i]), &(tindex[i].record_size));
        }
      }
      require (fwrite (allrecs_packed[i], tindex[i].record_size, 1, fp) == 1);
      free (allrecs_packed[i]);
    }

  /* Free workspace (packed records were freed above) */

  free (allrecs_packed);
  free (map);

  /* Flush, reopen, renew.  The index is now garbage; close and reopen
     to reindex. */

  hd.end_of_file = ftell(fp);
  hd.pub.number_of_records = newrecnum;
  modified = NVTrue;
  close_tide_db ();
  open_tide_db (filename);

  if (db)
    *db = hd.pub;

  return NVTrue;
}


/*****************************************************************************\

    Function        update_tide_record - updates a tide record in the database

    Synopsis        update_tide_record (num, rec);

                    NV_INT32 num            record number
                    TIDE_RECORD *rec        tide record

    Returns         NV_BOOL                 NVTrue if successful

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

#ifdef COMPAT114
NV_BOOL update_tide_record (NV_INT32 num, TIDE_RECORD *rec)
#else
NV_BOOL update_tide_record (NV_INT32 num, TIDE_RECORD *rec, DB_HEADER_PUBLIC *db)
#endif
{
    NV_INT32                pos, size;
    TIDE_RECORD             tmp_rec;
    NV_U_BYTE               *block = NULL;

    if (!fp) {
      fprintf (stderr, "libtcd error: attempt to access database when database not open\n");
      return NVFalse;
    }
    write_protect();

    if (num < 0 || num >= (NV_INT32)hd.pub.number_of_records) return NVFalse;

    if (!check_tide_record (rec))
      return NVFalse;

    figure_size (rec);
    read_tide_record (num, &tmp_rec);
    if (rec->header.record_size != tmp_rec.header.record_size)
    {
        /*  Aaaaaaarrrrrgggggghhhh!!!!  We have to move stuff!  */

        /*  Save where we are - end of record being modified.  */
        pos = ftell (fp);
        assert (pos > 0);

        /*  Figure out how big a block we need to move.  */
        size = hd.end_of_file - pos;
        assert (size >= 0);

        /*  Allocate memory and read the block.  */
        if (size)
        {
            if ((block = (NV_U_BYTE *) calloc (size, sizeof (NV_U_BYTE))) ==
                NULL)
            {
                perror ("Allocating block");
                return NVFalse;
            }
            fread (block, size, 1, fp);
        }

        /*  Write out the modified record.  */
        write_tide_record (num, rec);

        /*  If we weren't at the end of file, move the block.  */
        if (size)
        {
            fwrite (block, size, 1, fp);
            free (block);
        }

        hd.end_of_file = ftell (fp);

        /*  Close the file and reopen it to index the records again.  */
        close_tide_db ();
        open_tide_db (filename);
    }

    /*  The easy way.  No change to the record size.  */
    else
    {
        write_tide_record (num, rec);

        /*  Save the header info in the index.  */
        tindex[num].record_size = rec->header.record_size;
        tindex[num].record_type = rec->header.record_type;
        tindex[num].reference_station = rec->header.reference_station;
        tindex[num].tzfile = rec->header.tzfile;
        tindex[num].lat = NINT (rec->header.latitude * hd.latitude_scale);
        tindex[num].lon = NINT (rec->header.longitude * hd.longitude_scale);

        /* AH maybe? */
        /* DWF: agree, same size record does not imply that name length
           is identical. */
	if (strcmp(tindex[num].name, rec->header.name) != 0) {
	  free(tindex[num].name);
	  tindex[num].name = (NV_CHAR *) calloc (strlen (rec->header.name) + 1, sizeof (NV_CHAR));
	  strcpy(tindex[num].name, rec->header.name);
	}
    }

#ifndef COMPAT114
    if (db)
      *db = hd.pub;
#endif

    return (NVTrue);
}


/*****************************************************************************\

    Function        infer_constituents - computes inferred constituents when
                    M2, S2, K1, and O1 are given.  This function fills the
                    remaining unfilled constituents.  The inferred constituents
                    are developed or decided based on article 230 of
                    "Manual of Harmonic Analysis and Prediction of Tides",
                    Paul Schureman, C & GS special publication no. 98,
                    October 1971.  This function is really just for NAVO
                    since we go to weird places and put in tide gages for
                    ridiculously short periods of time so we only get a
                    few major constituents developed.  This function was
                    modified from the NAVO FORTRAN program pred_tide_corr,
                    subroutine infer.ftn, 08-oct-86.

    Synopsis        infer_constituents (rec);

                    TIDE_RECORD rec         tide record

    Returns         NV_BOOL                 NVFalse if not enough constituents
                                            available to infer others

    Author          Jan C. Depner
    Date            08/01/02

    See libtcd.html for changelog.

\*****************************************************************************/

NV_BOOL infer_constituents (TIDE_RECORD *rec)
{
    NV_U_INT32        i, j;
    NV_INT32          m2, s2, k1, o1;
    NV_FLOAT32        epoch_m2, epoch_s2, epoch_k1, epoch_o1;

    assert (rec);
    require ((m2 = find_constituent ("M2")) >= 0);
    require ((s2 = find_constituent ("S2")) >= 0);
    require ((k1 = find_constituent ("K1")) >= 0);
    require ((o1 = find_constituent ("O1")) >= 0);

    if (rec->amplitude[m2] == 0.0 || rec->amplitude[s2] == 0.0 ||
        rec->amplitude[k1] == 0.0 || rec->amplitude[o1] == 0.0)
        return (NVFalse);

    epoch_m2 = rec->epoch[m2];
    epoch_s2 = rec->epoch[s2];
    epoch_k1 = rec->epoch[k1];
    epoch_o1 = rec->epoch[o1];

    for (i = 0 ; i < hd.pub.constituents ; ++i)
    {
        if (rec->amplitude[i] == 0.0 && rec->epoch[i] == 0.0)
        {
            for (j = 0 ; j < INFERRED_SEMI_DIURNAL_COUNT ; ++j)
            {
                if (!strcmp (inferred_semi_diurnal[j], get_constituent (i)))
                {
                    /*  Compute the inferred semi-diurnal constituent.  */

                    rec->amplitude[i] = (semi_diurnal_coeff[j] / coeff[0]) *
                        rec->amplitude[m2];

                    if (fabs ((NV_FLOAT64) (epoch_s2 - epoch_m2)) > 180.0)
                    {
                        if (epoch_s2 < epoch_m2)
                        {
                            epoch_s2 += 360.0;
                        }
                        else
                        {
                            epoch_m2 += 360.0;
                        }
                    }
                    rec->epoch[i] = epoch_m2 + ((hd.speed[i] - hd.speed[m2]) /
                        (hd.speed[s2] - hd.speed[m2])) * (epoch_s2 - epoch_m2);
                }
            }


            for (j = 0 ; j < INFERRED_DIURNAL_COUNT ; ++j)
            {
                if (!strcmp (inferred_diurnal[j], get_constituent (i)))
                {
                    /*  Compute the inferred diurnal constituent.  */

                    rec->amplitude[i] = (diurnal_coeff[j] / coeff[1]) *
                        rec->amplitude[o1];

                    if (fabs ((NV_FLOAT64) (epoch_k1 - epoch_o1)) > 180.0)
                    {
                        if (epoch_k1 < epoch_o1)
                        {
                            epoch_k1 += 360.0;
                        }
                        else
                        {
                            epoch_o1 += 360.0;
                        }
                    }
                    rec->epoch[i] = epoch_o1 + ((hd.speed[i] - hd.speed[o1]) /
                        (hd.speed[k1] - hd.speed[o1])) * (epoch_k1 - epoch_o1);
                }
            }
        }
    }

    return (NVTrue);
}