File: dbdata.c

package info (click to toggle)
whitedb 0.7.2-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 2,452 kB
  • ctags: 2,681
  • sloc: ansic: 31,714; python: 790; lex: 359; java: 277; makefile: 172; yacc: 138; sh: 87; sed: 36
file content (3075 lines) | stat: -rw-r--r-- 87,586 bytes parent folder | download
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
/*
* $Id:  $
* $Version: $
*
* Copyright (c) Tanel Tammet 2004,2005,2006,2007,2008,2009
*
* Contact: tanel.tammet@gmail.com
*
* This file is part of WhiteDB
*
* WhiteDB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* WhiteDB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with WhiteDB.  If not, see <http://www.gnu.org/licenses/>.
*
*/

 /** @file dbdata.c
 *  Procedures for handling actual data: strings, integers, records,  etc
 *
 */

/* ====== Includes =============== */


#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
/* For Sleep() */
#include <windows.h>
#endif

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <time.h>
#include <sys/timeb.h>
//#include <math.h>

#ifdef __cplusplus
extern "C" {
#endif

#ifdef _WIN32
#include "../config-w32.h"
#else
#include "../config.h"
#endif
#include "dballoc.h"
#include "dbdata.h"
#include "dbhash.h"
#include "dblog.h"
#include "dbindex.h"
#include "dbcompare.h"
#include "dblock.h"

/* ====== Private headers and defs ======== */

#ifdef _WIN32
//Thread-safe localtime_r appears not to be present on windows: emulate using win localtime, which is thread-safe.
static struct tm * localtime_r (const time_t *timer, struct tm *result);
#define sscanf sscanf_s  // warning: needs extra buflen args for string etc params
#define snprintf sprintf_s
#endif


/* ======= Private protos ================ */

#ifdef USE_BACKLINKING
static gint remove_backlink_index_entries(void *db, gint *record,
  gint value, gint depth);
static gint restore_backlink_index_entries(void *db, gint *record,
  gint value, gint depth);
#endif

static int isleap(unsigned yr);
static unsigned months_to_days (unsigned month);
static long years_to_days (unsigned yr);
static long ymd_to_scalar (unsigned yr, unsigned mo, unsigned day);
static void scalar_to_ymd (long scalar, unsigned *yr, unsigned *mo, unsigned *day);

static gint free_field_encoffset(void* db,gint encoffset);
static gint find_create_longstr(void* db, char* data, char* extrastr, gint type, gint length);

#ifdef USE_CHILD_DB
static void *get_ptr_owner(void *db, gint encoded);
static int is_local_offset(void *db, gint offset);
#endif

static gint show_data_error(void* db, char* errmsg);
static gint show_data_error_nr(void* db, char* errmsg, gint nr);
static gint show_data_error_double(void* db, char* errmsg, double nr);
static gint show_data_error_str(void* db, char* errmsg, char* str);


/* ====== Functions ============== */



/* ------------ full record handling ---------------- */


void* wg_create_record(void* db, wg_int length) {
  void *rec = wg_create_raw_record(db, length);
  /* Index all the created NULL fields to ensure index consistency */
  if(rec) {
    if(wg_index_add_rec(db, rec) < -1)
      return NULL; /* index error */
  }
  return rec;
}

/*
 * Creates the record and initializes the fields
 * to NULL, but does not update indexes. This is useful in two
 * scenarios: 1. fields are immediately initialized to something
 * else, making indexing NULLs useless 2. record will have
 * a RECORD_META_NOTDATA bit set, so the fields should not
 * be indexed at all.
 *
 * In the first case, it is required that wg_set_new_field()
 * is called on all the fields in the record. In the second case,
 * the caller is responsible for setting the meta bits, however
 * it is not mandatory to re-initialize all the fields.
 */
void* wg_create_raw_record(void* db, wg_int length) {
  gint offset;
  gint i;

#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error_nr(db,"wrong database pointer given to wg_create_record with length ",length);
    return 0;
  }
  if(length < 0) {
    show_data_error_nr(db, "invalid record length:",length);
    return 0;
  }
#endif

#ifdef USE_DBLOG
  /* Log first, modify shared memory next */
  if(dbmemsegh(db)->logging.active) {
    if(wg_log_create_record(db, length))
      return 0;
  }
#endif

  offset=wg_alloc_gints(db,
                     &(dbmemsegh(db)->datarec_area_header),
                    length+RECORD_HEADER_GINTS);
  if (!offset) {
    show_data_error_nr(db,"cannot create a record of size ",length);
#ifdef USE_DBLOG
    if(dbmemsegh(db)->logging.active) {
      wg_log_encval(db, 0);
    }
#endif
    return 0;
  }

  /* Init header */
  dbstore(db, offset+RECORD_META_POS*sizeof(gint), 0);
  dbstore(db, offset+RECORD_BACKLINKS_POS*sizeof(gint), 0);
  for(i=RECORD_HEADER_GINTS;i<length+RECORD_HEADER_GINTS;i++) {
    dbstore(db,offset+(i*(sizeof(gint))),0);
  }

#ifdef USE_DBLOG
  /* Append the created offset to log */
  if(dbmemsegh(db)->logging.active) {
    if(wg_log_encval(db, offset))
      return 0; /* journal error */
  }
#endif

  return offsettoptr(db,offset);
}

/** Delete record from database
 * returns 0 on success
 * returns -1 if the record is referenced by others and cannot be deleted.
 * returns -2 on general error
 * returns -3 on fatal error
 *
 * XXX: when USE_BACKLINKING is off, this function should be used
 * with extreme care.
 */
gint wg_delete_record(void* db, void *rec) {
  gint offset;
  gint* dptr;
  gint* dendptr;
  gint data;

#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db, "wrong database pointer given to wg_delete_record");
    return -2;
  }
#endif

#ifdef USE_BACKLINKING
  if(*((gint *) rec + RECORD_BACKLINKS_POS))
    return -1;
#endif

#ifdef USE_DBLOG
  /* Log first, modify shared memory next */
  if(dbmemsegh(db)->logging.active) {
    if(wg_log_delete_record(db, ptrtooffset(db, rec)))
      return -3;
  }
#endif

  /* Remove data from index */
  if(!is_special_record(rec)) {
    if(wg_index_del_rec(db, rec) < -1)
      return -3; /* index error */
  }

  offset = ptrtooffset(db, rec);
#if defined(CHECK) && defined(USE_CHILD_DB)
  /* Check if it's a local record */
  if(!is_local_offset(db, offset)) {
    show_data_error(db, "not deleting an external record");
    return -2;
  }
#endif

  /* Loop over fields, freeing them */
  dendptr = (gint *) (((char *) rec) + datarec_size_bytes(*((gint *)rec)));
  for(dptr=(gint *)rec+RECORD_HEADER_GINTS; dptr<dendptr; dptr++) {
    data = *dptr;

#ifdef USE_BACKLINKING
    /* Is the field value a record pointer? If so, remove the backlink. */
#ifdef USE_CHILD_DB
    if(wg_get_encoded_type(db, data) == WG_RECORDTYPE &&
      is_local_offset(db, decode_datarec_offset(data))) {
#else
    if(wg_get_encoded_type(db, data) == WG_RECORDTYPE) {
#endif
      gint *child = (gint *) wg_decode_record(db, data);
      gint *next_offset = child + RECORD_BACKLINKS_POS;
      gcell *old = NULL;

      while(*next_offset) {
        old = (gcell *) offsettoptr(db, *next_offset);
        if(old->car == offset) {
          gint old_offset = *next_offset;
          *next_offset = old->cdr; /* remove from list chain */
          wg_free_listcell(db, old_offset); /* free storage */
          goto recdel_backlink_removed;
        }
        next_offset = &(old->cdr);
      }
      show_data_error(db, "Corrupt backlink chain");
      return -3; /* backlink error */
    }
recdel_backlink_removed:
#endif

    if(isptr(data)) free_field_encoffset(db,data);
  }

  /* Free the record storage */
  wg_free_object(db,
    &(dbmemsegh(db)->datarec_area_header),
    offset);

  return 0;
}


/** Get the first data record from the database
 *  Uses header meta bits to filter out special records
 *  (rules, system records etc)
 */
void* wg_get_first_record(void* db) {
  void *res = wg_get_first_raw_record(db);
  if(res && is_special_record(res))
    return wg_get_next_record(db, res); /* find first data record */
  return res;
}

/** Get the next data record from the database
 *  Uses header meta bits to filter out special records
 */
void* wg_get_next_record(void* db, void* record) {
  void *res = record;
  do {
    res = wg_get_next_raw_record(db, res);
  } while(res && is_special_record(res));
  return res;
}

/** Get the first record from the database
 *
 */
void* wg_get_first_raw_record(void* db) {
  db_subarea_header* arrayadr;
  gint firstoffset;
  void* res;

#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_get_first_record");
    return NULL;
  }
#endif
  arrayadr=&((dbmemsegh(db)->datarec_area_header).subarea_array[0]);
  firstoffset=((arrayadr[0]).alignedoffset); // do NOT skip initial "used" marker
  //printf("arrayadr %x firstoffset %d \n",(uint)arrayadr,firstoffset);
  res=wg_get_next_raw_record(db,offsettoptr(db,firstoffset));
  return res;
}

/** Get the next record from the database
 *
 */
void* wg_get_next_raw_record(void* db, void* record) {
  gint curoffset;
  gint head;
  db_subarea_header* arrayadr;
  gint last_subarea_index;
  gint i;
  gint found;
  gint subareastart;
  gint subareaend;
  gint freemarker;

  curoffset=ptrtooffset(db,record);
  //printf("curroffset %d record %x\n",curoffset,(uint)record);
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_get_first_record");
    return NULL;
  }
  head=dbfetch(db,curoffset);
  if (isfreeobject(head)) {
    show_data_error(db,"wrong record pointer (free) given to wg_get_next_record");
    return NULL;
  }
#endif
  freemarker=0; //assume input pointer to used object
  head=dbfetch(db,curoffset);
  while(1) {
    // increase offset to next memory block
    curoffset=curoffset+(freemarker ? getfreeobjectsize(head) : getusedobjectsize(head));
    head=dbfetch(db,curoffset);
    //printf("new curoffset %d head %d isnormaluseobject %d isfreeobject %d \n",
    //       curoffset,head,isnormalusedobject(head),isfreeobject(head));
    // check if found a normal used object
    if (isnormalusedobject(head)) return offsettoptr(db,curoffset); //return ptr to normal used object
    if (isfreeobject(head)) {
      freemarker=1;
      // loop start leads us to next object
    } else {
      // found a special object (dv or end marker)
      freemarker=0;
      if (dbfetch(db,curoffset+sizeof(gint))==SPECIALGINT1DV) {
        // we have reached a dv object
        continue; // loop start leads us to next object
      } else {
        // we have reached an end marker, have to find the next subarea
        // first locate subarea for this offset
        arrayadr=&((dbmemsegh(db)->datarec_area_header).subarea_array[0]);
        last_subarea_index=(dbmemsegh(db)->datarec_area_header).last_subarea_index;
        found=0;
        for(i=0;(i<=last_subarea_index)&&(i<SUBAREA_ARRAY_SIZE);i++) {
          subareastart=((arrayadr[i]).alignedoffset);
          subareaend=((arrayadr[i]).offset)+((arrayadr[i]).size);
          if (curoffset>=subareastart && curoffset<subareaend) {
            found=1;
            break;
          }
        }
        if (!found) {
          show_data_error(db,"wrong record pointer (out of area) given to wg_get_next_record");
          return NULL;
        }
        // take next subarea, while possible
        i++;
        if (i>last_subarea_index || i>=SUBAREA_ARRAY_SIZE) {
          //printf("next used object not found: i %d curoffset %d \n",i,curoffset);
          return NULL;
        }
        //printf("taking next subarea i %d\n",i);
        curoffset=((arrayadr[i]).alignedoffset);  // curoffset is now the special start marker
        head=dbfetch(db,curoffset);
        // loop start will lead us to next object from special marker
      }
    }
  }
}


/* ------------ backlink chain recursive functions ------------------- */

#ifdef USE_BACKLINKING

/** Remove index entries in backlink chain recursively.
 *  Needed for index maintenance when records are compared by their
 *  contens, as change in contents also changes the value of the entire
 *  record and thus affects it's placement in the index.
 *  Returns 0 for success
 *  Returns -1 in case of errors.
 */
static gint remove_backlink_index_entries(void *db, gint *record,
  gint value, gint depth) {
  gint col, length, err = 0;
  db_memsegment_header *dbh = dbmemsegh(db);

  if(!is_special_record(record)) {
    /* Find all fields in the record that match value (which is actually
     * a reference to a child record in encoded form) and remove it from
     * indexes. It will be recreated in the indexes by wg_set_field() later.
     */
    length = getusedobjectwantedgintsnr(*record) - RECORD_HEADER_GINTS;
    if(length > MAX_INDEXED_FIELDNR)
      length = MAX_INDEXED_FIELDNR + 1;

    for(col=0; col<length; col++) {
      if(*(record + RECORD_HEADER_GINTS + col) == value) {
        /* Changed value is always a WG_RECORDDTYPE field, therefore
         * we don't need to deal with index templates here
         * (record links are not allowed in templates).
         */
        if(dbh->index_control_area_header.index_table[col]) {
          if(wg_index_del_field(db, record, col) < -1)
            return -1;
        }
      }
    }
  }

  /* If recursive depth is not exchausted, continue with the parents
   * of this record.
   */
  if(depth > 0) {
    gint backlink_list = *(record + RECORD_BACKLINKS_POS);
    if(backlink_list) {
      gcell *next = (gcell *) offsettoptr(db, backlink_list);
      for(;;) {
        err = remove_backlink_index_entries(db,
          (gint *) offsettoptr(db, next->car),
          wg_encode_record(db, record), depth-1);
        if(err)
          return err;
        if(!next->cdr)
          break;
        next = (gcell *) offsettoptr(db, next->cdr);
      }
    }
  }

  return 0;
}

/** Add index entries in backlink chain recursively.
 *  Called after doing remove_backling_index_entries() and updating
 *  data in the record that originated the call. This recreates the
 *  entries in the indexes for all the records that were affected.
 *  Returns 0 for success
 *  Returns -1 in case of errors.
 */
static gint restore_backlink_index_entries(void *db, gint *record,
  gint value, gint depth) {
  gint col, length, err = 0;
  db_memsegment_header *dbh = dbmemsegh(db);

  if(!is_special_record(record)) {
    /* Find all fields in the record that match value (which is actually
     * a reference to a child record in encoded form) and add it back to
     * indexes.
     */
    length = getusedobjectwantedgintsnr(*record) - RECORD_HEADER_GINTS;
    if(length > MAX_INDEXED_FIELDNR)
      length = MAX_INDEXED_FIELDNR + 1;

    for(col=0; col<length; col++) {
      if(*(record + RECORD_HEADER_GINTS + col) == value) {
        if(dbh->index_control_area_header.index_table[col]) {
          if(wg_index_add_field(db, record, col) < -1)
            return -1;
        }
      }
    }
  }

  /* Continue to the parents until depth==0 */
  if(depth > 0) {
    gint backlink_list = *(record + RECORD_BACKLINKS_POS);
    if(backlink_list) {
      gcell *next = (gcell *) offsettoptr(db, backlink_list);
      for(;;) {
        err = restore_backlink_index_entries(db,
          (gint *) offsettoptr(db, next->car),
          wg_encode_record(db, record), depth-1);
        if(err)
          return err;
        if(!next->cdr)
          break;
        next = (gcell *) offsettoptr(db, next->cdr);
      }
    }
  }

  return 0;
}

#endif

/* ------------ field handling: data storage and fetching ---------------- */


wg_int wg_get_record_len(void* db, void* record) {

#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_get_record_len");
    return -1;
  }
#endif
  return ((gint)(getusedobjectwantedgintsnr(*((gint*)record))))-RECORD_HEADER_GINTS;
}

wg_int* wg_get_record_dataarray(void* db, void* record) {

#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_get_record_dataarray");
    return NULL;
  }
#endif
  return (((gint*)record)+RECORD_HEADER_GINTS);
}

/** Update contents of one field
 *  returns 0 if successful
 *  returns -1 if invalid db pointer passed (by recordcheck macro)
 *  returns -2 if invalid record passed (by recordcheck macro)
 *  returns -3 for fatal index error
 *  returns -4 for backlink-related error
 *  returns -5 for invalid external data
 *  returns -6 for journal error
 */
wg_int wg_set_field(void* db, void* record, wg_int fieldnr, wg_int data) {
  gint* fieldadr;
  gint fielddata;
  gint* strptr;
#ifdef USE_BACKLINKING
  gint backlink_list;           /** start of backlinks for this record */
  gint rec_enc = WG_ILLEGAL;    /** this record as encoded value. */
#endif
  db_memsegment_header *dbh = dbmemsegh(db);
#ifdef USE_CHILD_DB
  void *offset_owner = dbmemseg(db);
#endif

#ifdef CHECK
  recordcheck(db,record,fieldnr,"wg_set_field");
#endif

#ifdef USE_DBLOG
  /* Do not proceed before we've logged the operation */
  if(dbh->logging.active) {
    if(wg_log_set_field(db,record,fieldnr,data))
      return -6; /* journal error, cannot write */
  }
#endif

  /* Read the old encoded value */
  fieldadr=((gint*)record)+RECORD_HEADER_GINTS+fieldnr;
  fielddata=*fieldadr;

  /* Update index(es) while the old value is still in the db */
#ifdef USE_INDEX_TEMPLATE
  if(!is_special_record(record) && fieldnr<=MAX_INDEXED_FIELDNR &&\
    (dbh->index_control_area_header.index_table[fieldnr] ||\
     dbh->index_control_area_header.index_template_table[fieldnr])) {
#else
  if(!is_special_record(record) && fieldnr<=MAX_INDEXED_FIELDNR &&\
    dbh->index_control_area_header.index_table[fieldnr]) {
#endif
    if(wg_index_del_field(db, record, fieldnr) < -1)
      return -3; /* index error */
  }

  /* If there are backlinks, go up the chain and remove the reference
   * to this record from all indexes (updating a field in the record
   * causes the value of the record to change). Note that we only go
   * as far as the recursive comparison depth - records higher in the
   * hierarchy are not affected.
   */
#if defined(USE_BACKLINKING) && (WG_COMPARE_REC_DEPTH > 0)
  backlink_list = *((gint *) record + RECORD_BACKLINKS_POS);
  if(backlink_list) {
    gint err;
    gcell *next = (gcell *) offsettoptr(db, backlink_list);
    rec_enc = wg_encode_record(db, record);
    for(;;) {
      err = remove_backlink_index_entries(db,
        (gint *) offsettoptr(db, next->car),
        rec_enc, WG_COMPARE_REC_DEPTH-1);
      if(err) {
        return -4; /* override the error code, for now. */
      }
      if(!next->cdr)
        break;
      next = (gcell *) offsettoptr(db, next->cdr);
    }
  }
#endif

#ifdef USE_CHILD_DB
  /* Get the offset owner */
  if(isptr(data)) {
    offset_owner = get_ptr_owner(db, data);
    if(!offset_owner) {
      show_data_error(db, "External reference not recognized");
      return -5;
    }
  }
#endif

#ifdef USE_BACKLINKING
  /* Is the old field value a record pointer? If so, remove the backlink.
   * XXX: this can be optimized to use a custom macro instead of
   * wg_get_encoded_type().
   */
#ifdef USE_CHILD_DB
  /* Only touch local records */
  if(wg_get_encoded_type(db, fielddata) == WG_RECORDTYPE &&
    offset_owner == dbmemseg(db)) {
#else
  if(wg_get_encoded_type(db, fielddata) == WG_RECORDTYPE) {
#endif
    gint *rec = (gint *) wg_decode_record(db, fielddata);
    gint *next_offset = rec + RECORD_BACKLINKS_POS;
    gint parent_offset = ptrtooffset(db, record);
    gcell *old = NULL;

    while(*next_offset) {
      old = (gcell *) offsettoptr(db, *next_offset);
      if(old->car == parent_offset) {
        gint old_offset = *next_offset;
        *next_offset = old->cdr; /* remove from list chain */
        wg_free_listcell(db, old_offset); /* free storage */
        goto setfld_backlink_removed;
      }
      next_offset = &(old->cdr);
    }
    show_data_error(db, "Corrupt backlink chain");
    return -4; /* backlink error */
  }
setfld_backlink_removed:
#endif

  //printf("wg_set_field adr %d offset %d\n",fieldadr,ptrtooffset(db,fieldadr));
  if (isptr(fielddata)) {
    //printf("wg_set_field freeing old data\n");
    free_field_encoffset(db,fielddata);
  }
  (*fieldadr)=data; // store data to field
#ifdef USE_CHILD_DB
  if (islongstr(data) && offset_owner == dbmemseg(db)) {
#else
  if (islongstr(data)) {
#endif
    // increase data refcount for longstr-s
    strptr = (gint *) offsettoptr(db,decode_longstr_offset(data));
    ++(*(strptr+LONGSTR_REFCOUNT_POS));
  }

  /* Update index after new value is written */
#ifdef USE_INDEX_TEMPLATE
  if(!is_special_record(record) && fieldnr<=MAX_INDEXED_FIELDNR &&\
    (dbh->index_control_area_header.index_table[fieldnr] ||\
     dbh->index_control_area_header.index_template_table[fieldnr])) {
#else
  if(!is_special_record(record) && fieldnr<=MAX_INDEXED_FIELDNR &&\
    dbh->index_control_area_header.index_table[fieldnr]) {
#endif
    if(wg_index_add_field(db, record, fieldnr) < -1)
      return -3;
  }

#ifdef USE_BACKLINKING
  /* Is the new field value a record pointer? If so, add a backlink */
#ifdef USE_CHILD_DB
  if(wg_get_encoded_type(db, data) == WG_RECORDTYPE &&
    offset_owner == dbmemseg(db)) {
#else
  if(wg_get_encoded_type(db, data) == WG_RECORDTYPE) {
#endif
    gint *rec = (gint *) wg_decode_record(db, data);
    gint *next_offset = rec + RECORD_BACKLINKS_POS;
    gint new_offset = wg_alloc_fixlen_object(db,
      &(dbmemsegh(db)->listcell_area_header));
    gcell *new_cell = (gcell *) offsettoptr(db, new_offset);

    while(*next_offset)
      next_offset = &(((gcell *) offsettoptr(db, *next_offset))->cdr);
    new_cell->car = ptrtooffset(db, record);
    new_cell->cdr = 0;
    *next_offset = new_offset;
  }
#endif

#if defined(USE_BACKLINKING) && (WG_COMPARE_REC_DEPTH > 0)
  /* Create new entries in indexes in all referring records */
  if(backlink_list) {
    gint err;
    gcell *next = (gcell *) offsettoptr(db, backlink_list);
    for(;;) {
      err = restore_backlink_index_entries(db,
        (gint *) offsettoptr(db, next->car),
        rec_enc, WG_COMPARE_REC_DEPTH-1);
      if(err) {
        return -4;
      }
      if(!next->cdr)
        break;
      next = (gcell *) offsettoptr(db, next->cdr);
    }
  }
#endif

  return 0;
}

/** Write contents of one field.
 *
 *  Used to initialize fields in records that have been created with
 *  wg_create_raw_record().
 *
 *  This function ignores the previous contents of the field. The
 *  rationale is that newly created fields do not have any meaningful
 *  content and this allows faster writing. It is up to the programmer
 *  to ensure that this function is not called on fields that already
 *  contain data.
 *
 *  returns 0 if successful
 *  returns -1 if invalid db pointer passed
 *  returns -2 if invalid record or field passed
 *  returns -3 for fatal index error
 *  returns -4 for backlink-related error
 *  returns -5 for invalid external data
 *  returns -6 for journal error
 */
wg_int wg_set_new_field(void* db, void* record, wg_int fieldnr, wg_int data) {
  gint* fieldadr;
  gint* strptr;
#ifdef USE_BACKLINKING
  gint backlink_list;           /** start of backlinks for this record */
#endif
  db_memsegment_header *dbh = dbmemsegh(db);
#ifdef USE_CHILD_DB
  void *offset_owner = dbmemseg(db);
#endif

#ifdef CHECK
  recordcheck(db,record,fieldnr,"wg_set_field");
#endif

#ifdef USE_DBLOG
  /* Do not proceed before we've logged the operation */
  if(dbh->logging.active) {
    if(wg_log_set_field(db,record,fieldnr,data))
      return -6; /* journal error, cannot write */
  }
#endif

#ifdef USE_CHILD_DB
  /* Get the offset owner */
  if(isptr(data)) {
    offset_owner = get_ptr_owner(db, data);
    if(!offset_owner) {
      show_data_error(db, "External reference not recognized");
      return -5;
    }
  }
#endif

  /* Write new value */
  fieldadr=((gint*)record)+RECORD_HEADER_GINTS+fieldnr;
#ifdef CHECK
  if(*fieldadr) {
    show_data_error(db,"wg_set_new_field called on field that contains data");
    return -2;
  }
#endif
  (*fieldadr)=data;

#ifdef USE_CHILD_DB
  if (islongstr(data) && offset_owner == dbmemseg(db)) {
#else
  if (islongstr(data)) {
#endif
    // increase data refcount for longstr-s
    strptr = (gint *) offsettoptr(db,decode_longstr_offset(data));
    ++(*(strptr+LONGSTR_REFCOUNT_POS));
  }

  /* Update index after new value is written */
#ifdef USE_INDEX_TEMPLATE
  if(!is_special_record(record) && fieldnr<=MAX_INDEXED_FIELDNR &&\
    (dbh->index_control_area_header.index_table[fieldnr] ||\
     dbh->index_control_area_header.index_template_table[fieldnr])) {
#else
  if(!is_special_record(record) && fieldnr<=MAX_INDEXED_FIELDNR &&\
    dbh->index_control_area_header.index_table[fieldnr]) {
#endif
    if(wg_index_add_field(db, record, fieldnr) < -1)
      return -3;
  }

#ifdef USE_BACKLINKING
  /* Is the new field value a record pointer? If so, add a backlink */
#ifdef USE_CHILD_DB
  if(wg_get_encoded_type(db, data) == WG_RECORDTYPE &&
    offset_owner == dbmemseg(db)) {
#else
  if(wg_get_encoded_type(db, data) == WG_RECORDTYPE) {
#endif
    gint *rec = (gint *) wg_decode_record(db, data);
    gint *next_offset = rec + RECORD_BACKLINKS_POS;
    gint new_offset = wg_alloc_fixlen_object(db,
      &(dbmemsegh(db)->listcell_area_header));
    gcell *new_cell = (gcell *) offsettoptr(db, new_offset);

    while(*next_offset)
      next_offset = &(((gcell *) offsettoptr(db, *next_offset))->cdr);
    new_cell->car = ptrtooffset(db, record);
    new_cell->cdr = 0;
    *next_offset = new_offset;
  }
#endif

#if defined(USE_BACKLINKING) && (WG_COMPARE_REC_DEPTH > 0)
  /* Create new entries in indexes in all referring records. Normal
   * usage scenario would be that the record is also new, so that
   * there are no backlinks, however this is not guaranteed.
   */
  backlink_list = *((gint *) record + RECORD_BACKLINKS_POS);
  if(backlink_list) {
    gint err;
    gcell *next = (gcell *) offsettoptr(db, backlink_list);
    gint rec_enc = wg_encode_record(db, record);
    for(;;) {
      err = restore_backlink_index_entries(db,
        (gint *) offsettoptr(db, next->car),
        rec_enc, WG_COMPARE_REC_DEPTH-1);
      if(err) {
        return -4;
      }
      if(!next->cdr)
        break;
      next = (gcell *) offsettoptr(db, next->cdr);
    }
  }
#endif

  return 0;
}

wg_int wg_set_int_field(void* db, void* record, wg_int fieldnr, gint data) {
  gint fielddata;
  fielddata=wg_encode_int(db,data);
  //printf("wg_set_int_field data %d encoded %d\n",data,fielddata);
  if (fielddata==WG_ILLEGAL) return -1;
  return wg_set_field(db,record,fieldnr,fielddata);
}

wg_int wg_set_double_field(void* db, void* record, wg_int fieldnr, double data) {
  gint fielddata;

  fielddata=wg_encode_double(db,data);
  if (fielddata==WG_ILLEGAL) return -1;
  return wg_set_field(db,record,fieldnr,fielddata);
}

wg_int wg_set_str_field(void* db, void* record, wg_int fieldnr, char* data) {
  gint fielddata;

  fielddata=wg_encode_str(db,data,NULL);
  if (fielddata==WG_ILLEGAL) return -1;
  return wg_set_field(db,record,fieldnr,fielddata);
}

wg_int wg_set_rec_field(void* db, void* record, wg_int fieldnr, void* data) {
  gint fielddata;

  fielddata=wg_encode_record(db,data);
  if (fielddata==WG_ILLEGAL) return -1;
  return wg_set_field(db,record,fieldnr,fielddata);
}

/** Special case of updating a field value without a write-lock.
 *
 *  Operates like wg_set_field but takes a previous value in a field
 *  as an additional argument for atomicity check.
 *
 *  This special case does not require a write lock: however,
 *  you MUST still get a read-lock before the operation while
 *  doing parallel processing, otherwise the operation
 *  may corrupt the database: no complex write operations should
 *  happen in parallel to this operation.
 *
 *  NB! the operation may still confuse other parallel readers, changing
 *  the value in a record they have just read. Use only if this is
 *  known to not create problems for other processes.
 *
 *  It can be only used to write an immediate value (NULL, short int,
 *  char, date, time) to a non-indexed field containing also an
 *  immediate field: checks whether these conditions hold.
 *
 *  The operation will fail if the original value passed has been
 *  overwritten before we manage to store a new value: this is
 *  a guaranteed atomic check and enables correct operation of
 *  several parallel wg_set_atomic_field operations
 *  changing the same field.
 *
 *  returns 0 if successful
 *  returns -1 if wrong db pointer
 *  returns -2 if wrong fieldnr
 *  returns -10 if new value non-immediate
 *  returns -11 if old value non-immediate
 *  returns -12 if cannot fetch old data
 *  returns -13 if the field has an index
 *  returns -14 if logging is active
 *  returns -15 if the field value has been changed from old_data
 *  may return other field-setting error codes from wg_set_new_field
 *
 */

wg_int wg_update_atomic_field(void* db, void* record, wg_int fieldnr, wg_int data, wg_int old_data) {
  gint* fieldadr;
  db_memsegment_header *dbh = dbmemsegh(db);
  gint tmp;

  // basic sanity check
#ifdef CHECK
  recordcheck(db,record,fieldnr,"wg_update_atomic_field");
#endif
  // check whether new value and old value are direct values in a record
  if (!isimmediatedata(data)) return -10;
  if (!isimmediatedata(old_data)) return -11;
  // check whether there is index on the field
#ifdef USE_INDEX_TEMPLATE
  if(!is_special_record(record) && fieldnr<=MAX_INDEXED_FIELDNR &&\
    (dbh->index_control_area_header.index_table[fieldnr] ||\
     dbh->index_control_area_header.index_template_table[fieldnr])) {
#else
  if(!is_special_record(record) && fieldnr<=MAX_INDEXED_FIELDNR &&\
    dbh->index_control_area_header.index_table[fieldnr]) {
#endif
    return -13;
  }
  // check that no logging is used
#ifdef USE_DBLOG
  if(dbh->logging.active) {
    return -14;
  }
#endif
  // checks passed, do atomic field setting
  fieldadr=((gint*)record)+RECORD_HEADER_GINTS+fieldnr;
  tmp=wg_compare_and_swap(fieldadr, old_data, data);
  if (tmp) return 0;
  else return -15;
}


/** Special case of setting a field value without a write-lock.
 *
 * Calls wg_update_atomic_field iteratively until compare-and-swap succeeds.
 *
 * The restrictions and error codes from wg_update_atomic_field apply.
 * returns 0 if successful
 * returns -1...-15 with an error defined before in wg_update_atomic_field.
 * returns -17 if atomic assignment failed after a large number (1000) of tries
*/

wg_int wg_set_atomic_field(void* db, void* record, wg_int fieldnr, wg_int data) {
  gint* fieldadr;
  gint old,r;
  int i;
#ifdef _WIN32
  int ts=1;
#else
  struct timespec ts;
#endif

  // basic sanity check
#ifdef CHECK
  recordcheck(db,record,fieldnr,"wg_set_atomic_field");
#endif
  fieldadr=((gint*)record)+RECORD_HEADER_GINTS+fieldnr;
  for(i=0;;i++) {
    // loop until preconditions fail or addition succeeds and
    // the old value is not changed during compare-and-swap
    old=*fieldadr;
    r=wg_update_atomic_field(db,record,fieldnr,data,old);
    if (!r) return 0;
    if (r!=-15) return r; // -15 is field changed error
    // here compare-and-swap failed, try again
    if (i>1000) return -17; // possibly a deadlock
    if (i%10!=0) continue; // sleep only every tenth loop
    // several loops passed, sleep a bit
#ifdef _WIN32
    Sleep(ts); // 1000 for loops take ca 0.1 sec
#else
    ts.tv_sec=0;
    ts.tv_nsec=100+i;
    nanosleep(&ts,NULL); // 1000 for loops take ca 60 microsec
#endif
  }
  return -17; // should not reach here
}


/** Special case of adding to an int field without a write-lock.
 *
 * fieldnr must contain a smallint and the result of addition
 * must also be a smallint.
 *
 * The restrictions and error codes from wg_update_atomic_field apply.
 *
 * returns 0 if successful
 * returns -1...-15 with an error defined before in wg_set_atomic_field.
 * returns -16 if the result of the addition does not fit into a smallint
 * returns -17 if atomic assignment failed after a large number (1000) of tries
 *
*/

wg_int wg_add_int_atomic_field(void* db, void* record, wg_int fieldnr, int data) {
  gint* fieldadr;
  gint old,nxt,r;
  int i,sum;
#ifdef _WIN32
  int ts=1;
#else
  struct timespec ts;
#endif

  // basic sanity check
#ifdef CHECK
  recordcheck(db,record,fieldnr,"wg_add_int_atomic_field");
#endif
  fieldadr=((gint*)record)+RECORD_HEADER_GINTS+fieldnr;
  for(i=0;;i++) {
    // loop until preconditions fail or addition succeeds and
    // the old value is not changed during compare-and-swap
    old=*fieldadr;
    if (!issmallint(old)) return -11;
    sum=wg_decode_int(db,(gint)old)+data;
    if (!fits_smallint(sum)) return -16;
    nxt=encode_smallint(sum);
    r=wg_update_atomic_field(db,record,fieldnr,nxt,old);
    if (!r) return 0;
    if (r!=-15) return r; // -15 is field changed error
    // here compare-and-swap failed, try again
    if (i>1000) return -17; // possibly a deadlock
    if (i%10!=0) continue; // sleep only every tenth loop
    // several loops passed, sleep a bit
#ifdef _WIN32
    Sleep(ts); // 1000 for loops take ca 0.1 sec
#else
    ts.tv_sec=0;
    ts.tv_nsec=100+i;
    nanosleep(&ts,NULL); // 1000 for loops take ca 60 microsec
#endif
  }
  return -17; // should not reach here
}


wg_int wg_get_field(void* db, void* record, wg_int fieldnr) {

#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error_nr(db,"wrong database pointer given to wg_get_field",fieldnr);
    return WG_ILLEGAL;
  }
  if (fieldnr<0 || (getusedobjectwantedgintsnr(*((gint*)record))<=fieldnr+RECORD_HEADER_GINTS)) {
    show_data_error_nr(db,"wrong field number given to wg_get_field",fieldnr);\
    return WG_ILLEGAL;
  }
#endif
  //printf("wg_get_field adr %d offset %d\n",
  //       (((gint*)record)+RECORD_HEADER_GINTS+fieldnr),
  //       ptrtooffset(db,(((gint*)record)+RECORD_HEADER_GINTS+fieldnr)));
  return *(((gint*)record)+RECORD_HEADER_GINTS+fieldnr);
}

wg_int wg_get_field_type(void* db, void* record, wg_int fieldnr) {

#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error_nr(db,"wrong database pointer given to wg_get_field_type",fieldnr);\
    return 0;
  }
  if (fieldnr<0 || (getusedobjectwantedgintsnr(*((gint*)record))<=fieldnr+RECORD_HEADER_GINTS)) {
    show_data_error_nr(db,"wrong field number given to wg_get_field_type",fieldnr);\
    return 0;
  }
#endif
  return wg_get_encoded_type(db,*(((gint*)record)+RECORD_HEADER_GINTS+fieldnr));
}

/* ------------- general operations -------------- */



wg_int wg_free_encoded(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_free_encoded");
    return 0;
  }
#endif
  if (isptr(data)) {
    gint *strptr;

    /* XXX: Major hack: since free_field_encoffset() decrements
     * the refcount, but wg_encode_str() does not (which is correct),
     * before, increment the refcount once before we free the
     * object. If the string is in use already, this will be a
     * no-op, otherwise it'll be successfully freed anyway.
     */
#ifdef USE_CHILD_DB
    if (islongstr(data) &&
      is_local_offset(db, decode_longstr_offset(data))) {
#else
    if (islongstr(data)) {
#endif
      // increase data refcount for longstr-s
      strptr = (gint *) offsettoptr(db,decode_longstr_offset(data));
      ++(*(strptr+LONGSTR_REFCOUNT_POS));
    }
    return free_field_encoffset(db,data);
  }
  return 0;
}

/** properly removes ptr (offset) to data
*
* assumes fielddata is offset to allocated data
* depending on type of fielddata either deallocates pointed data or
* removes data back ptr or decreases refcount
*
* in case fielddata points to record or longstring, these
* are freed only if they have no more pointers
*
* returns non-zero in case of error
*/

static gint free_field_encoffset(void* db,gint encoffset) {
  gint offset;
#if 0
  gint* dptr;
  gint* dendptr;
  gint data;
  gint i;
#endif
  gint tmp;
  gint* objptr;
  gint* extrastr;

  // takes last three bits to decide the type
  // fullint is represented by two options: 001 and 101
  switch(encoffset&NORMALPTRMASK) {
    case DATARECBITS:
#if 0
/* This section of code in quarantine */
      // remove from list
      // refcount check
      offset=decode_datarec_offset(encoffset);
      tmp=dbfetch(db,offset+sizeof(gint)*LONGSTR_REFCOUNT_POS);
      tmp--;
      if (tmp>0) {
        dbstore(db,offset+LONGSTR_REFCOUNT_POS,tmp);
      } else {
        // free frompointers structure
        // loop over fields, freeing them
        dptr=offsettoptr(db,offset);
        dendptr=(gint*)(((char*)dptr)+datarec_size_bytes(*dptr));
        for(i=0,dptr=dptr+RECORD_HEADER_GINTS;dptr<dendptr;dptr++,i++) {
          data=*dptr;
          if (isptr(data)) free_field_encoffset(db,data);
        }
        // really free object from area
        wg_free_object(db,&(dbmemsegh(db)->datarec_area_header),offset);
      }
#endif
      break;
    case LONGSTRBITS:
      offset=decode_longstr_offset(encoffset);
#ifdef USE_CHILD_DB
      if(!is_local_offset(db, offset))
        break; /* Non-local reference, ignore it */
#endif
      // refcount check
      tmp=dbfetch(db,offset+sizeof(gint)*LONGSTR_REFCOUNT_POS);
      tmp--;
      if (tmp>0) {
        dbstore(db,offset+sizeof(gint)*LONGSTR_REFCOUNT_POS,tmp);
      } else {
        objptr = (gint *) offsettoptr(db,offset);
        extrastr=(gint*)(((char*)(objptr))+(sizeof(gint)*LONGSTR_EXTRASTR_POS));
        tmp=*extrastr;
        // remove from hash
        wg_remove_from_strhash(db,encoffset);
        // remove extrastr
        if (tmp!=0) free_field_encoffset(db,tmp);
        *extrastr=0;
        // really free object from area
        wg_free_object(db,&(dbmemsegh(db)->longstr_area_header),offset);
      }
      break;
    case SHORTSTRBITS:
#ifdef USE_CHILD_DB
      offset = decode_shortstr_offset(encoffset);
      if(!is_local_offset(db, offset))
        break; /* Non-local reference, ignore it */
      wg_free_shortstr(db, offset);
#else
      wg_free_shortstr(db,decode_shortstr_offset(encoffset));
#endif
      break;
    case FULLDOUBLEBITS:
#ifdef USE_CHILD_DB
      offset = decode_fulldouble_offset(encoffset);
      if(!is_local_offset(db, offset))
        break; /* Non-local reference, ignore it */
      wg_free_doubleword(db, offset);
#else
      wg_free_doubleword(db,decode_fulldouble_offset(encoffset));
#endif
      break;
    case FULLINTBITSV0:
#ifdef USE_CHILD_DB
      offset = decode_fullint_offset(encoffset);
      if(!is_local_offset(db, offset))
        break; /* Non-local reference, ignore it */
      wg_free_word(db, offset);
#else
      wg_free_word(db,decode_fullint_offset(encoffset));
#endif
      break;
    case FULLINTBITSV1:
#ifdef USE_CHILD_DB
      offset = decode_fullint_offset(encoffset);
      if(!is_local_offset(db, offset))
        break; /* Non-local reference, ignore it */
      wg_free_word(db, offset);
#else
      wg_free_word(db,decode_fullint_offset(encoffset));
#endif
      break;

  }
  return 0;
}



/* ------------- data encoding and decoding ------------ */


/** determines the type of encoded data
*
* returns a zero-or-bigger macro integer value from wg_db_api.h beginning:
*
* #define WG_NULLTYPE 1
* #define WG_RECORDTYPE 2
* #define WG_INTTYPE 3
* #define WG_DOUBLETYPE 4
* #define WG_STRTYPE 5
* ... etc ...
*
* returns a negative number -1 in case of error
*
*/


wg_int wg_get_encoded_type(void* db, wg_int data) {
  gint fieldoffset;
  gint tmp;

#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_get_encoded_type");
    return 0;
  }
#endif
  if (!data) return WG_NULLTYPE;
  if (((data)&NONPTRBITS)==NONPTRBITS) {
    // data is one of the non-pointer types
    if (isvar(data)) return (gint)WG_VARTYPE;
    if (issmallint(data)) return (gint)WG_INTTYPE;
    switch(data&LASTBYTEMASK) {
      case CHARBITS: return WG_CHARTYPE;
      case FIXPOINTBITS: return WG_FIXPOINTTYPE;
      case DATEBITS: return WG_DATETYPE;
      case TIMEBITS: return WG_TIMETYPE;
      case TINYSTRBITS: return WG_STRTYPE;
      case VARBITS: return WG_VARTYPE;
      case ANONCONSTBITS: return WG_ANONCONSTTYPE;
      default: return -1;
    }
  }
  // here we know data must be of ptr type
  // takes last three bits to decide the type
  // fullint is represented by two options: 001 and 101
  //printf("cp0\n");
  switch(data&NORMALPTRMASK) {
    case DATARECBITS: return (gint)WG_RECORDTYPE;
    case LONGSTRBITS:
      //printf("cp1\n");
      fieldoffset=decode_longstr_offset(data)+LONGSTR_META_POS*sizeof(gint);
      //printf("fieldoffset %d\n",fieldoffset);
      tmp=dbfetch(db,fieldoffset);
      //printf("str meta %d lendiff %d subtype %d\n",
      //  tmp,(tmp&LONGSTR_META_LENDIFMASK)>>LONGSTR_META_LENDIFSHFT,tmp&LONGSTR_META_TYPEMASK);
      return tmp&LONGSTR_META_TYPEMASK; // WG_STRTYPE, WG_URITYPE, WG_XMLLITERALTYPE
    case SHORTSTRBITS:   return (gint)WG_STRTYPE;
    case FULLDOUBLEBITS: return (gint)WG_DOUBLETYPE;
    case FULLINTBITSV0:  return (gint)WG_INTTYPE;
    case FULLINTBITSV1:  return (gint)WG_INTTYPE;
    default: return -1;
  }
  return 0;
}


char* wg_get_type_name(void* db, wg_int type) {
  switch (type) {
    case WG_NULLTYPE: return "null";
    case WG_RECORDTYPE: return "record";
    case WG_INTTYPE: return "int";
    case WG_DOUBLETYPE: return "double";
    case WG_STRTYPE: return "string";
    case WG_XMLLITERALTYPE: return "xmlliteral";
    case WG_URITYPE: return "uri";
    case WG_BLOBTYPE: return "blob";
    case WG_CHARTYPE: return "char";
    case WG_FIXPOINTTYPE: return "fixpoint";
    case WG_DATETYPE: return "date";
    case WG_TIMETYPE: return "time";
    case WG_ANONCONSTTYPE: return "anonconstant";
    case WG_VARTYPE: return "var";
    default: return "unknown";
  }
}


wg_int wg_encode_null(void* db, char* data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_encode_null");
    return WG_ILLEGAL;
  }
  if (data!=NULL) {
    show_data_error(db,"data given to wg_encode_null is not NULL");
    return WG_ILLEGAL;
  }
#endif
#ifdef USE_DBLOG
/* Skip logging values that do not cause storage allocation.
  if(dbh->logging.active) {
    if(wg_log_encode(db, WG_NULLTYPE, NULL, 0, NULL, 0))
      return WG_ILLEGAL;
  }
*/
#endif
  return (gint)0;
}

char* wg_decode_null(void* db,wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_null");
    return NULL;
  }
  if (data!=(gint)0) {
    show_data_error(db,"data given to wg_decode_null is not an encoded NULL");
    return NULL;
  }
#endif
  return NULL;
}

wg_int wg_encode_int(void* db, wg_int data) {
  gint offset;
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_encode_int");
    return WG_ILLEGAL;
  }
#endif
  if (fits_smallint(data)) {
    return encode_smallint(data);
  } else {
#ifdef USE_DBLOG
    /* Log before allocating. Note this call is skipped when
     * we have a small int.
     */
    if(dbmemsegh(db)->logging.active) {
      if(wg_log_encode(db, WG_INTTYPE, &data, 0, NULL, 0))
        return WG_ILLEGAL;
    }
#endif
    offset=alloc_word(db);
    if (!offset) {
      show_data_error_nr(db,"cannot store an integer in wg_set_int_field: ",data);
#ifdef USE_DBLOG
      if(dbmemsegh(db)->logging.active) {
        wg_log_encval(db, WG_ILLEGAL);
      }
#endif
      return WG_ILLEGAL;
    }
    dbstore(db,offset,data);
#ifdef USE_DBLOG
    if(dbmemsegh(db)->logging.active) {
      if(wg_log_encval(db, encode_fullint_offset(offset)))
        return WG_ILLEGAL; /* journal error */
    }
#endif
    return encode_fullint_offset(offset);
  }
}

wg_int wg_decode_int(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_int");
    return 0;
  }
#endif
  if (issmallint(data)) return decode_smallint(data);
  if (isfullint(data)) return dbfetch(db,decode_fullint_offset(data));
  show_data_error_nr(db,"data given to wg_decode_int is not an encoded int: ",data);
  return 0;
}



wg_int wg_encode_char(void* db, char data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_encode_char");
    return WG_ILLEGAL;
  }
#endif
#ifdef USE_DBLOG
/* Skip logging values that do not cause storage allocation.
  if(dbh->logging.active) {
    if(wg_log_encode(db, WG_CHARTYPE, &data, 0, NULL, 0))
      return WG_ILLEGAL;
  }
*/
#endif
  return (wg_int)(encode_char((wg_int)data));
}


char wg_decode_char(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_char");
    return 0;
  }
#endif
  return (char)(decode_char(data));
}


wg_int wg_encode_double(void* db, double data) {
  gint offset;

#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_encode_double");
    return WG_ILLEGAL;
  }
#endif
#ifdef USE_DBLOG
  /* Log before allocating. */
  if(dbmemsegh(db)->logging.active) {
    if(wg_log_encode(db, WG_DOUBLETYPE, &data, 0, NULL, 0))
      return WG_ILLEGAL;
  }
#endif
  if (0) {
    // possible future case for tiny floats
  } else {
    offset=alloc_doubleword(db);
    if (!offset) {
      show_data_error_double(db,"cannot store a double in wg_set_double_field: ",data);
#ifdef USE_DBLOG
      if(dbmemsegh(db)->logging.active) {
        wg_log_encval(db, WG_ILLEGAL);
      }
#endif
      return WG_ILLEGAL;
    }
    *((double*)(offsettoptr(db,offset)))=data;
#ifdef USE_DBLOG
    if(dbmemsegh(db)->logging.active) {
      if(wg_log_encval(db, encode_fulldouble_offset(offset)))
        return WG_ILLEGAL; /* journal error */
    }
#endif
    return encode_fulldouble_offset(offset);
  }
}

double wg_decode_double(void* db, wg_int data) {

#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_double");
    return 0;
  }
#endif
  if (isfulldouble(data)) return *((double*)(offsettoptr(db,decode_fulldouble_offset(data))));
  show_data_error_nr(db,"data given to wg_decode_double is not an encoded double: ",data);
  return 0;
}


wg_int wg_encode_fixpoint(void* db, double data) {

#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_encode_fixpoint");
    return WG_ILLEGAL;
  }
  if (!fits_fixpoint(data)) {
    show_data_error(db,"argument given to wg_encode_fixpoint too big or too small");
    return WG_ILLEGAL;
  }
#endif
#ifdef USE_DBLOG
/* Skip logging values that do not cause storage allocation.
  if(dbh->logging.active) {
    if(wg_log_encode(db, WG_FIXPOINTTYPE, &data, 0, NULL, 0))
      return WG_ILLEGAL;
  }
*/
#endif
  return encode_fixpoint(data);
}

double wg_decode_fixpoint(void* db, wg_int data) {

#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_double");
    return 0;
  }
#endif
  if (isfixpoint(data)) return decode_fixpoint(data);
  show_data_error_nr(db,"data given to wg_decode_fixpoint is not an encoded fixpoint: ",data);
  return 0;
}


wg_int wg_encode_date(void* db, int data) {

#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_encode_date");
    return WG_ILLEGAL;
  }
  if (!fits_date(data)) {
    show_data_error(db,"argument given to wg_encode_date too big or too small");
    return WG_ILLEGAL;
  }
#endif
#ifdef USE_DBLOG
/* Skip logging values that do not cause storage allocation.
  if(dbh->logging.active) {
    if(wg_log_encode(db, WG_DATETYPE, &data, 0, NULL, 0))
      return WG_ILLEGAL;
  }
*/
#endif
  return encode_date(data);
}

int wg_decode_date(void* db, wg_int data) {

#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_date");
    return 0;
  }
#endif
  if (isdate(data)) return decode_date(data);
  show_data_error_nr(db,"data given to wg_decode_date is not an encoded date: ",data);
  return 0;
}

wg_int wg_encode_time(void* db, int data) {

#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_encode_time");
    return WG_ILLEGAL;
  }
  if (!fits_time(data)) {
    show_data_error(db,"argument given to wg_encode_time too big or too small");
    return WG_ILLEGAL;
  }
#endif
#ifdef USE_DBLOG
/* Skip logging values that do not cause storage allocation.
  if(dbh->logging.active) {
    if(wg_log_encode(db, WG_TIMETYPE, &data, 0, NULL, 0))
      return WG_ILLEGAL;
  }
*/
#endif
  return encode_time(data);
}

int wg_decode_time(void* db, wg_int data) {

#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_time");
    return 0;
  }
#endif
  if (istime(data)) return decode_time(data);
  show_data_error_nr(db,"data given to wg_decode_time is not an encoded time: ",data);
  return 0;
}

int wg_current_utcdate(void* db) {
  time_t ts;
  int epochadd=719163; // y 1970 m 1 d 1

  ts=time(NULL); // secs since Epoch 1970
  return (int)(ts/(24*60*60))+epochadd;
}

int wg_current_localdate(void* db) {
  time_t esecs;
  int res;
  struct tm ctime;

  esecs=time(NULL); // secs since Epoch 1970tstruct.time;
  localtime_r(&esecs,&ctime);
  res=ymd_to_scalar(ctime.tm_year+1900,ctime.tm_mon+1,ctime.tm_mday);
  return res;
}


int wg_current_utctime(void* db) {
  struct timeb tstruct;
  int esecs;
  int days;
  int secs;
  int milli;
  int secsday=24*60*60;

  ftime(&tstruct);
  esecs=(int)(tstruct.time);
  milli=tstruct.millitm;
  days=esecs/secsday;
  secs=esecs-(days*secsday);
  return (secs*100)+(milli/10);
}

int wg_current_localtime(void* db) {
  struct timeb tstruct;
  time_t esecs;
  int secs;
  int milli;
  struct tm ctime;

  ftime(&tstruct);
  esecs=tstruct.time;
  milli=tstruct.millitm;
  localtime_r(&esecs,&ctime);
  secs=ctime.tm_hour*60*60+ctime.tm_min*60+ctime.tm_sec;
  return (secs*100)+(milli/10);
}

int wg_strf_iso_datetime(void* db, int date, int time, char* buf) {
  unsigned yr, mo, day, hr, min, sec, spart;
  int t=time;
  int c;

  hr=t/(60*60*100);
  t=t-(hr*(60*60*100));
  min=t/(60*100);
  t=t-(min*(60*100));
  sec=t/100;
  t=t-(sec*(100));
  spart=t;

  scalar_to_ymd(date,&yr,&mo,&day);
  c=snprintf(buf,24,"%04d-%02d-%02dT%02d:%02d:%02d.%02d",yr,mo,day,hr,min,sec,spart);
  return(c);
}

int wg_strp_iso_date(void* db, char* inbuf) {
  int sres;
  int yr=0;
  int mo=0;
  int day=0;
  int res;

  sres=sscanf(inbuf,"%4d-%2d-%2d",&yr,&mo,&day);
  if (sres<3 || yr<0 || mo<1 || mo>12 || day<1 || day>31) return -1;
  res=ymd_to_scalar(yr,mo,day);
  return res;
}


int wg_strp_iso_time(void* db, char* inbuf) {
  int sres;
  int hr=0;
  int min=0;
  int sec=0;
  int prt=0;

  sres=sscanf(inbuf,"%2d:%2d:%2d.%2d",&hr,&min,&sec,&prt);
  if (sres<3 || hr<0 || hr>24 || min<0 || min>60 || sec<0 || sec>60 || prt<0 || prt>99) return -1;
  return hr*(60*60*100)+min*(60*100)+sec*100+prt;
}


int wg_ymd_to_date(void* db, int yr, int mo, int day) {
  if (yr<0 || mo<1 || mo>12 || day<1 || day>31) return -1;
  return ymd_to_scalar(yr,mo,day);
}


int wg_hms_to_time(void* db, int hr, int min, int sec, int prt) {
  if (hr<0 || hr>24 || min<0 || min>60 || sec<0 || sec>60 || prt<0 || prt>99)
    return -1;
  return hr*(60*60*100)+min*(60*100)+sec*100+prt;
}


void wg_date_to_ymd(void* db, int date, int *yr, int *mo, int *day) {
  unsigned int y, m, d;

  scalar_to_ymd(date, &y, &m, &d);
  *yr=y;
  *mo=m;
  *day=d;
}


void wg_time_to_hms(void* db, int time, int *hr, int *min, int *sec, int *prt) {
  int t=time;

  *hr=t/(60*60*100);
  t=t-(*hr * (60*60*100));
  *min=t/(60*100);
  t=t-(*min * (60*100));
  *sec=t/100;
  t=t-(*sec * (100));
  *prt=t;
}


// record

wg_int wg_encode_record(void* db, void* data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_encode_char");
    return WG_ILLEGAL;
  }
#endif
#ifdef USE_DBLOG
/* Skip logging values that do not cause storage allocation.
  if(dbh->logging.active) {
    if(wg_log_encode(db, WG_RECORDTYPE, &data, 0, NULL, 0))
      return WG_ILLEGAL;
  }
*/
#endif
  return (wg_int)(encode_datarec_offset(ptrtooffset(db,data)));
}


void* wg_decode_record(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_encode_char");
    return 0;
  }
#endif
  return (void*)(offsettoptr(db,decode_datarec_offset(data)));
}





/* ============================================

Separate string, xmlliteral, uri, blob funs
call universal funs defined later

============================================== */

/* string */

wg_int wg_encode_str(void* db, char* str, char* lang) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_encode_str");
    return WG_ILLEGAL;
  }
  if (str==NULL) {
    show_data_error(db,"NULL string ptr given to wg_encode_str");
    return WG_ILLEGAL;
  }
#endif
  /* Logging handled inside wg_encode_unistr() */
  return wg_encode_unistr(db,str,lang,WG_STRTYPE);
}


char* wg_decode_str(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_str");
    return NULL;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_str is 0, not an encoded string");
    return NULL;
  }
#endif
  return wg_decode_unistr(db,data,WG_STRTYPE);
}


wg_int wg_decode_str_len(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_str_len");
    return -1;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_str_len is 0, not an encoded string");
    return -1;
  }
#endif
  return wg_decode_unistr_len(db,data,WG_STRTYPE);
}



wg_int wg_decode_str_copy(void* db, wg_int data, char* strbuf, wg_int buflen) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_str_copy");
    return -1;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_str_copy is 0, not an encoded string");
    return -1;
  }
  if (strbuf==NULL) {
     show_data_error(db,"buffer given to wg_decode_str_copy is 0, not a valid buffer pointer");
    return -1;
  }
  if (buflen<1) {
     show_data_error(db,"buffer len given to wg_decode_str_copy is 0 or less");
    return -1;
  }
#endif
  return wg_decode_unistr_copy(db,data,strbuf,buflen,WG_STRTYPE);
}


char* wg_decode_str_lang(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_str");
    return NULL;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_str_lang is 0, not an encoded string");
    return NULL;
  }
#endif
  return wg_decode_unistr_lang(db,data,WG_STRTYPE);
}


wg_int wg_decode_str_lang_len(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_str_lang_len");
    return -1;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_str_lang_len is 0, not an encoded string");
    return -1;
  }
#endif
  return wg_decode_unistr_lang_len(db,data,WG_STRTYPE);
}



wg_int wg_decode_str_lang_copy(void* db, wg_int data, char* langbuf, wg_int buflen) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_str_lang_copy");
    return -1;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_str_lang_copy is 0, not an encoded string");
    return -1;
  }
  if (langbuf==NULL) {
     show_data_error(db,"buffer given to wg_decode_str_lang_copy is 0, not a valid buffer pointer");
    return -1;
  }
  if (buflen<1) {
     show_data_error(db,"buffer len given to wg_decode_str_lang_copy is 0 or less");
    return -1;
  }
#endif
  return wg_decode_unistr_lang_copy(db,data,langbuf,buflen,WG_STRTYPE);
}


/* xmlliteral */


wg_int wg_encode_xmlliteral(void* db, char* str, char* xsdtype) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_encode_xmlliteral");
    return WG_ILLEGAL;
  }
  if (str==NULL) {
    show_data_error(db,"NULL string ptr given to wg_encode_xmlliteral");
    return WG_ILLEGAL;
  }
  if (xsdtype==NULL) {
    show_data_error(db,"NULL xsdtype ptr given to wg_encode_xmlliteral");
    return WG_ILLEGAL;
  }
#endif
  /* Logging handled inside wg_encode_unistr() */
  return wg_encode_unistr(db,str,xsdtype,WG_XMLLITERALTYPE);
}


char* wg_decode_xmlliteral(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_xmlliteral");
    return NULL;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_xmlliteral is 0, not an encoded xmlliteral");
    return NULL;
  }
#endif
  return wg_decode_unistr(db,data,WG_XMLLITERALTYPE);
}


wg_int wg_decode_xmlliteral_len(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_xmlliteral_len");
    return -1;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_xmlliteral_len is 0, not an encoded xmlliteral");
    return -1;
  }
#endif
  return wg_decode_unistr_len(db,data,WG_XMLLITERALTYPE);
}



wg_int wg_decode_xmlliteral_copy(void* db, wg_int data, char* strbuf, wg_int buflen) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_xmlliteral_copy");
    return -1;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_xmlliteral_copy is 0, not an encoded xmlliteral");
    return -1;
  }
  if (strbuf==NULL) {
     show_data_error(db,"buffer given to wg_decode_xmlliteral_copy is 0, not a valid buffer pointer");
    return -1;
  }
  if (buflen<1) {
     show_data_error(db,"buffer len given to wg_decode_xmlliteral_copy is 0 or less");
    return -1;
  }
#endif
  return wg_decode_unistr_copy(db,data,strbuf,buflen,WG_XMLLITERALTYPE);
}


char* wg_decode_xmlliteral_xsdtype(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_xmlliteral");
    return NULL;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_xmlliteral_xsdtype is 0, not an encoded xmlliteral");
    return NULL;
  }
#endif
  return wg_decode_unistr_lang(db,data,WG_XMLLITERALTYPE);
}


wg_int wg_decode_xmlliteral_xsdtype_len(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_xmlliteral_xsdtype_len");
    return -1;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_xmlliteral_lang_xsdtype is 0, not an encoded xmlliteral");
    return -1;
  }
#endif
  return wg_decode_unistr_lang_len(db,data,WG_XMLLITERALTYPE);
}



wg_int wg_decode_xmlliteral_xsdtype_copy(void* db, wg_int data, char* langbuf, wg_int buflen) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_xmlliteral_xsdtype_copy");
    return -1;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_xmlliteral_xsdtype_copy is 0, not an encoded xmlliteral");
    return -1;
  }
  if (langbuf==NULL) {
     show_data_error(db,"buffer given to wg_decode_xmlliteral_xsdtype_copy is 0, not a valid buffer pointer");
    return -1;
  }
  if (buflen<1) {
     show_data_error(db,"buffer len given to wg_decode_xmlliteral_xsdtype_copy is 0 or less");
    return -1;
  }
#endif
  return wg_decode_unistr_lang_copy(db,data,langbuf,buflen,WG_XMLLITERALTYPE);
}


/* uri */


wg_int wg_encode_uri(void* db, char* str, char* prefix) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_encode_uri");
    return WG_ILLEGAL;
  }
  if (str==NULL) {
    show_data_error(db,"NULL string ptr given to wg_encode_uri");
    return WG_ILLEGAL;
  }
#endif
  /* Logging handled inside wg_encode_unistr() */
  return wg_encode_unistr(db,str,prefix,WG_URITYPE);
}


char* wg_decode_uri(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_uri");
    return NULL;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_uri is 0, not an encoded string");
    return NULL;
  }
#endif
  return wg_decode_unistr(db,data,WG_URITYPE);
}


wg_int wg_decode_uri_len(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_uri_len");
    return -1;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_uri_len is 0, not an encoded string");
    return -1;
  }
#endif
  return wg_decode_unistr_len(db,data,WG_URITYPE);
}



wg_int wg_decode_uri_copy(void* db, wg_int data, char* strbuf, wg_int buflen) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_uri_copy");
    return -1;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_uri_copy is 0, not an encoded string");
    return -1;
  }
  if (strbuf==NULL) {
     show_data_error(db,"buffer given to wg_decode_uri_copy is 0, not a valid buffer pointer");
    return -1;
  }
  if (buflen<1) {
     show_data_error(db,"buffer len given to wg_decode_uri_copy is 0 or less");
    return -1;
  }
#endif
  return wg_decode_unistr_copy(db,data,strbuf,buflen,WG_URITYPE);
}


char* wg_decode_uri_prefix(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_uri_prefix");
    return NULL;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_uri_prefix is 0, not an encoded uri");
    return NULL;
  }
#endif
  return wg_decode_unistr_lang(db,data,WG_URITYPE);
}


wg_int wg_decode_uri_prefix_len(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_uri_prefix_len");
    return -1;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_uri_prefix_len is 0, not an encoded string");
    return -1;
  }
#endif
  return wg_decode_unistr_lang_len(db,data,WG_URITYPE);
}



wg_int wg_decode_uri_prefix_copy(void* db, wg_int data, char* langbuf, wg_int buflen) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_uri_prefix_copy");
    return -1;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_uri_prefix_copy is 0, not an encoded string");
    return -1;
  }
  if (langbuf==NULL) {
     show_data_error(db,"buffer given to wg_decode_uri_prefix_copy is 0, not a valid buffer pointer");
    return -1;
  }
  if (buflen<1) {
     show_data_error(db,"buffer len given to wg_decode_uri_prefix_copy is 0 or less");
    return -1;
  }
#endif
  return wg_decode_unistr_lang_copy(db,data,langbuf,buflen,WG_URITYPE);
}


/* blob */


wg_int wg_encode_blob(void* db, char* str, char* type, wg_int len) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_encode_blob");
    return WG_ILLEGAL;
  }
  if (str==NULL) {
    show_data_error(db,"NULL string ptr given to wg_encode_blob");
    return WG_ILLEGAL;
  }
#endif
  return wg_encode_uniblob(db,str,type,WG_BLOBTYPE,len);
}


char* wg_decode_blob(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_blob");
    return NULL;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_blob is 0, not an encoded string");
    return NULL;
  }
#endif
  return wg_decode_unistr(db,data,WG_BLOBTYPE);
}


wg_int wg_decode_blob_len(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_blob_len");
    return -1;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_blob_len is 0, not an encoded string");
    return -1;
  }
#endif
  return wg_decode_unistr_len(db,data,WG_BLOBTYPE)+1;
}



wg_int wg_decode_blob_copy(void* db, wg_int data, char* strbuf, wg_int buflen) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_blob_copy");
    return -1;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_blob_copy is 0, not an encoded string");
    return -1;
  }
  if (strbuf==NULL) {
     show_data_error(db,"buffer given to wg_decode_blob_copy is 0, not a valid buffer pointer");
    return -1;
  }
  if (buflen<1) {
     show_data_error(db,"buffer len given to wg_decode_blob_copy is 0 or less");
    return -1;
  }
#endif
  return wg_decode_unistr_copy(db,data,strbuf,buflen,WG_BLOBTYPE);
}


char* wg_decode_blob_type(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_blob_type");
    return NULL;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_blob_type is 0, not an encoded blob");
    return NULL;
  }
#endif
  return wg_decode_unistr_lang(db,data,WG_BLOBTYPE);
}


wg_int wg_decode_blob_type_len(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_blob_type_len");
    return -1;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_blob_type_len is 0, not an encoded string");
    return -1;
  }
#endif
  return wg_decode_unistr_lang_len(db,data,WG_BLOBTYPE);
}



wg_int wg_decode_blob_type_copy(void* db, wg_int data, char* langbuf, wg_int buflen) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_blob_type_copy");
    return -1;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_blob_type_copy is 0, not an encoded string");
    return -1;
  }
  if (langbuf==NULL) {
     show_data_error(db,"buffer given to wg_decode_blob_type_copy is 0, not a valid buffer pointer");
    return -1;
  }
  if (buflen<1) {
     show_data_error(db,"buffer len given to wg_decode_blob_type_copy is 0 or less");
    return -1;
  }
#endif
  return wg_decode_unistr_lang_copy(db,data,langbuf,buflen,WG_BLOBTYPE);
}


/* anonconst */


wg_int wg_encode_anonconst(void* db, char* str) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_encode_anonconst");
    return WG_ILLEGAL;
  }
  if (str==NULL) {
    show_data_error(db,"NULL string ptr given to wg_encode_anonconst");
    return WG_ILLEGAL;
  }
#endif
  //return wg_encode_unistr(db,str,NULL,WG_ANONCONSTTYPE);
  /* Logging handled inside wg_encode_unistr() */
  return wg_encode_unistr(db,str,NULL,WG_URITYPE);
}


char* wg_decode_anonconst(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_anonconst");
    return NULL;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_anonconst is 0, not an encoded anonconst");
    return NULL;
  }
#endif
  //return wg_decode_unistr(db,data,WG_ANONCONSTTYPE);
  return wg_decode_unistr(db,data,WG_URITYPE);
}


/* var */


wg_int wg_encode_var(void* db, wg_int varnr) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_encode_var");
    return WG_ILLEGAL;
  }
  if (!fits_var(varnr)) {
    show_data_error(db,"int given to wg_encode_var too big/small");
    return WG_ILLEGAL;
  }
#endif
#ifdef USE_DBLOG
/* Skip logging values that do not cause storage allocation.
  if(dbh->logging.active) {
    if(wg_log_encode(db, WG_VARTYPE, &data, 0, NULL, 0))
      return WG_ILLEGAL;
  }
*/
#endif
  return encode_var(varnr);
}


wg_int wg_decode_var(void* db, wg_int data) {
#ifdef CHECK
  if (!dbcheck(db)) {
    show_data_error(db,"wrong database pointer given to wg_decode_var");
    return -1;
  }
  if (!data) {
    show_data_error(db,"data given to wg_decode_var is 0, not an encoded var");
    return -1;
  }
#endif
  return decode_var(data);
}




/* ============================================

Universal funs for string, xmlliteral, uri, blob

============================================== */


gint wg_encode_unistr(void* db, char* str, char* lang, gint type) {
  gint offset;
  gint len;
#ifdef USETINYSTR
  gint res;
#endif
  char* dptr;
  char* sptr;
  char* dendptr;

  len=(gint)(strlen(str));
#ifdef USE_DBLOG
  /* Log before allocating. */
  if(dbmemsegh(db)->logging.active) {
    gint extlen = 0;
    if(lang) extlen = strlen(lang);
    if(wg_log_encode(db, type, str, len, lang, extlen))
      return WG_ILLEGAL;
  }
#endif
#ifdef USETINYSTR
/* XXX: add tinystr support to logging */
#ifdef USE_DBLOG
#error USE_DBLOG and USETINYSTR are incompatible
#endif
  if (lang==NULL && type==WG_STRTYPE && len<(sizeof(gint)-1)) {
    res=TINYSTRBITS; // first zero the field and set last byte to mask
    if (LITTLEENDIAN) {
      dptr=((char*)(&res))+1; // type bits stored in lowest addressed byte
    } else {
      dptr=((char*)(&res));  // type bits stored in highest addressed byte
    }
    memcpy(dptr,str,len+1);
    return res;
  }
#endif
  if (lang==NULL && type==WG_STRTYPE && len<SHORTSTR_SIZE) {
    // short string, store in a fixlen area
    offset=alloc_shortstr(db);
    if (!offset) {
      show_data_error_str(db,"cannot store a string in wg_encode_unistr",str);
#ifdef USE_DBLOG
      if(dbmemsegh(db)->logging.active) {
        wg_log_encval(db, WG_ILLEGAL);
      }
#endif
      return WG_ILLEGAL;
    }
    // loop over bytes, storing them starting from offset
    dptr = (char *) offsettoptr(db,offset);
    dendptr=dptr+SHORTSTR_SIZE;
    //
    //strcpy(dptr,sptr);
    //memset(dptr+len,0,SHORTSTR_SIZE-len);
    //
    for(sptr=str; (*dptr=*sptr)!=0; sptr++, dptr++) {}; // copy string
    for(dptr++; dptr<dendptr; dptr++) { *dptr=0; }; // zero the rest
    // store offset to field
#ifdef USE_DBLOG
    if(dbmemsegh(db)->logging.active) {
      if(wg_log_encval(db, encode_shortstr_offset(offset)))
        return WG_ILLEGAL; /* journal error */
    }
#endif
    return encode_shortstr_offset(offset);
    //dbstore(db,ptrtoffset(record)+RECORD_HEADER_GINTS+fieldnr,encode_shortstr_offset(offset));
  } else {
    offset=find_create_longstr(db,str,lang,type,len+1);
    if (!offset) {
      show_data_error_nr(db,"cannot create a string of size ",len);
#ifdef USE_DBLOG
      if(dbmemsegh(db)->logging.active) {
        wg_log_encval(db, WG_ILLEGAL);
      }
#endif
      return WG_ILLEGAL;
    }
#ifdef USE_DBLOG
    if(dbmemsegh(db)->logging.active) {
      if(wg_log_encval(db, encode_longstr_offset(offset)))
        return WG_ILLEGAL; /* journal error */
    }
#endif
    return encode_longstr_offset(offset);
  }
}


gint wg_encode_uniblob(void* db, char* str, char* lang, gint type, gint len) {
  gint offset;

  if (0) {
  } else {
    offset=find_create_longstr(db,str,lang,type,len);
    if (!offset) {
      show_data_error_nr(db,"cannot create a blob of size ",len);
      return WG_ILLEGAL;
    }
    return encode_longstr_offset(offset);
  }
}


static gint find_create_longstr(void* db, char* data, char* extrastr, gint type, gint length) {
  db_memsegment_header* dbh = dbmemsegh(db);
  gint offset;
  size_t i;
  gint tmp;
  gint lengints;
  gint lenrest;
  char* lstrptr;
  gint old=0;
  int hash;
  gint hasharrel;
  gint res;

  if (0) {
  } else {

    // find hash, check if exists and use if found
    hash=wg_hash_typedstr(db,data,extrastr,type,length);
    //hasharrel=((gint*)(offsettoptr(db,((db->strhash_area_header).arraystart))))[hash];
    hasharrel=dbfetch(db,((dbh->strhash_area_header).arraystart)+(sizeof(gint)*hash));
    //printf("hash %d((dbh->strhash_area_header).arraystart)+(sizeof(gint)*hash) %d hasharrel %d\n",
    //        hash,((dbh->strhash_area_header).arraystart)+(sizeof(gint)*hash), hasharrel);
    if (hasharrel) old=wg_find_strhash_bucket(db,data,extrastr,type,length,hasharrel);
    //printf("old %d \n",old);
    if (old) {
      //printf("str found in hash\n");
      return old;
    }
    //printf("str not found in hash\n");
    //printf("hasharrel 1 %d \n",hasharrel);
    // equal string not found in hash
    // allocate a new string
    lengints=length/sizeof(gint);  // 7/4=1, 8/4=2, 9/4=2,
    lenrest=length%sizeof(gint);  // 7%4=3, 8%4=0, 9%4=1,
    if (lenrest) lengints++;
    offset=wg_alloc_gints(db,
                     &(dbmemsegh(db)->longstr_area_header),
                    lengints+LONGSTR_HEADER_GINTS);
    if (!offset) {
      //show_data_error_nr(db,"cannot create a data string/blob of size ",length);
      return 0;
    }
    lstrptr=(char*)(offsettoptr(db,offset));
    // store string contents
    memcpy(lstrptr+(LONGSTR_HEADER_GINTS*sizeof(gint)),data,length);
    //zero the rest
    for(i=0;lenrest && i<sizeof(gint)-lenrest;i++) {
/*    for(i=0;i<lenrest;i++) {*/
      *(lstrptr+length+(LONGSTR_HEADER_GINTS*sizeof(gint))+i)=0;
    }
    // if extrastr exists, encode extrastr and store ptr to longstr record field
    if (extrastr!=NULL) {
      tmp=wg_encode_str(db,extrastr,NULL);
      if (tmp==WG_ILLEGAL) {
        //show_data_error_nr(db,"cannot create an (extra)string of size ",strlen(extrastr));
        return 0;
      }
      dbstore(db,offset+LONGSTR_EXTRASTR_POS*sizeof(gint),tmp);
      // increase extrastr refcount
      if(islongstr(tmp)) {
        gint *strptr = (gint *) offsettoptr(db,decode_longstr_offset(tmp));
        ++(*(strptr+LONGSTR_REFCOUNT_POS));
      }
    } else {
      dbstore(db,offset+LONGSTR_EXTRASTR_POS*sizeof(gint),0); // no extrastr ptr
    }
    // store metainfo: full obj len and str len difference, plus type
    tmp=(getusedobjectsize(*((gint*)lstrptr))-length)<<LONGSTR_META_LENDIFSHFT;
    tmp=tmp|type; // subtype of str stored in lowest byte of meta
    //printf("storing obj size %d, str len %d lengints %d lengints*4 %d lenrest %d lendiff %d metaptr %d meta %d \n",
    //  getusedobjectsize(*((gint*)lstrptr)),strlen(data),lengints,lengints*4,lenrest,
    //  (getusedobjectsize(*((gint*)lstrptr))-length),
    //  ((gint*)(offsettoptr(db,offset)))+LONGSTR_META_POS,
    //  tmp);
    dbstore(db,offset+LONGSTR_META_POS*sizeof(gint),tmp); // type and str length diff
    dbstore(db,offset+LONGSTR_REFCOUNT_POS*sizeof(gint),0); // not pointed from anywhere yet
    dbstore(db,offset+LONGSTR_BACKLINKS_POS*sizeof(gint),0); // no backlinks yet
    // encode
    res=encode_longstr_offset(offset);
    // store to hash and update hashchain
    dbstore(db,((dbh->strhash_area_header).arraystart)+(sizeof(gint)*hash),res);
    //printf("hasharrel 2 %d \n",hasharrel);
    dbstore(db,offset+LONGSTR_HASHCHAIN_POS*sizeof(gint),hasharrel); // store old hash array el
    // return result
    return res;
  }

}



char* wg_decode_unistr(void* db, gint data, gint type) {
  gint* objptr;
  char* dataptr;
#ifdef USETINYSTR
  if (type==WG_STRTYPE && istinystr(data)) {
    if (LITTLEENDIAN) {
      dataptr=((char*)(&data))+1; // type bits stored in lowest addressed byte
    } else {
      dataptr=((char*)(&data));  // type bits stored in highest addressed byte
    }
    return dataptr;
  }
#endif
  if (isshortstr(data)) {
    dataptr=(char*)(offsettoptr(db,decode_shortstr_offset(data)));
    return dataptr;
  }
  if (islongstr(data)) {
    objptr = (gint *) offsettoptr(db,decode_longstr_offset(data));
    dataptr=((char*)(objptr))+(LONGSTR_HEADER_GINTS*sizeof(gint));
    return dataptr;
  }
  show_data_error(db,"data given to wg_decode_unistr is not an encoded string");
  return NULL;
}


char* wg_decode_unistr_lang(void* db, gint data, gint type) {
  gint* objptr;
  gint* fldptr;
  gint fldval;
  char* res;

#ifdef USETINYSTR
  if (type==WG_STRTYPE && istinystr(data)) {
    return NULL;
  }
#endif
  if (type==WG_STRTYPE && isshortstr(data)) {
    return NULL;
  }
  if (islongstr(data)) {
    objptr = (gint *) offsettoptr(db,decode_longstr_offset(data));
    fldptr=((gint*)objptr)+LONGSTR_EXTRASTR_POS;
    fldval=*fldptr;
    if (fldval==0) return NULL;
    res=wg_decode_unistr(db,fldval,type);
    return res;
  }
  show_data_error(db,"data given to wg_decode_unistr_lang is not an encoded string");
  return NULL;
}

/**
* return length of the main string, not including terminating 0
*
*
*/

gint wg_decode_unistr_len(void* db, gint data, gint type) {
  char* dataptr;
  gint* objptr;
  gint objsize;
  gint strsize;

#ifdef USETINYSTR
  if (type==WG_STRTYPE && istinystr(data)) {
    if (LITTLEENDIAN) {
      dataptr=((char*)(&data))+1; // type bits stored in lowest addressed byte
    } else {
      dataptr=((char*)(&data));  // type bits stored in highest addressed byte
    }
    strsize=strlen(dataptr);
    return strsize;
  }
#endif
  if (isshortstr(data)) {
    dataptr=(char*)(offsettoptr(db,decode_shortstr_offset(data)));
    strsize=strlen(dataptr);
    return strsize;
  }
  if (islongstr(data)) {
    objptr = (gint *) offsettoptr(db,decode_longstr_offset(data));
    objsize=getusedobjectsize(*objptr);
    dataptr=((char*)(objptr))+(LONGSTR_HEADER_GINTS*sizeof(gint));
    //printf("dataptr to read from %d str '%s' of len %d\n",dataptr,dataptr,strlen(dataptr));
    strsize=objsize-(((*(objptr+LONGSTR_META_POS))&LONGSTR_META_LENDIFMASK)>>LONGSTR_META_LENDIFSHFT);
    return strsize-1;
  }
  show_data_error(db,"data given to wg_decode_unistr_len is not an encoded string");
  return 0;
}

/**
* copy string, return length of a copied string, not including terminating 0
*
* return -1 in case of error
*
*/

gint wg_decode_unistr_copy(void* db, gint data, char* strbuf, gint buflen, gint type) {
  gint i;
  gint* objptr;
  char* dataptr;
  gint objsize;
  gint strsize;

#ifdef USETINYSTR
  if (type==WG_STRTYPE && istinystr(data)) {
    if (LITTLEENDIAN) {
      dataptr=((char*)(&data))+1; // type bits stored in lowest addressed byte
    } else {
      dataptr=((char*)(&data));  // type bits stored in highest addressed byte
    }
    strsize=strlen(dataptr)+1;
    if (strsize>=sizeof(gint)) {
      show_data_error_nr(db,"wrong data stored as tinystr, impossible length:",strsize);
      return 0;
    }
    if (buflen<strsize) {
      show_data_error_nr(db,"insufficient buffer length given to wg_decode_unistr_copy:",buflen);
      return 0;
    }
    memcpy(strbuf,dataptr,strsize);
    //printf("tinystr was read to strbuf '%s'\n",strbuf);
    return strsize-1;
  }
#endif
  if (type==WG_STRTYPE && isshortstr(data)) {
    dataptr=(char*)(offsettoptr(db,decode_shortstr_offset(data)));
    for (i=1;i<SHORTSTR_SIZE && (*dataptr)!=0; i++,dataptr++,strbuf++) {
      if (i>=buflen) {
        show_data_error_nr(db,"insufficient buffer length given to wg_decode_unistr_copy:",buflen);
        return -1;
      }
      *strbuf=*dataptr;
    }
    *strbuf=0;
    return i-1;
  }
  if (islongstr(data)) {
    objptr = (gint *) offsettoptr(db,decode_longstr_offset(data));
    objsize=getusedobjectsize(*objptr);
    dataptr=((char*)(objptr))+(LONGSTR_HEADER_GINTS*sizeof(gint));
    //printf("dataptr to read from %d str '%s' of len %d\n",dataptr,dataptr,strlen(dataptr));
    strsize=objsize-(((*(objptr+LONGSTR_META_POS))&LONGSTR_META_LENDIFMASK)>>LONGSTR_META_LENDIFSHFT);
    //printf("objsize %d metaptr %d meta %d lendiff %d strsize %d \n",
    //  objsize,((gint*)objptr+LONGSTR_META_POS),*((gint*)objptr+LONGSTR_META_POS),
    //  (((*(objptr+LONGSTR_META_POS))&LONGSTR_META_LENDIFMASK)>>LONGSTR_META_LENDIFSHFT),strsize);
    if(buflen<strsize) {
      show_data_error_nr(db,"insufficient buffer length given to wg_decode_unistr_copy:",buflen);
      return -1;
    }
    memcpy(strbuf,dataptr,strsize);
    //*(dataptr+strsize)=0;
    //printf("copied str %s with strsize %d\n",strbuf,strlen(strbuf));
    if (type==WG_BLOBTYPE) return strsize;
    else return strsize-1;
  }
  show_data_error(db,"data given to wg_decode_unistr_copy is not an encoded string");
  return -1;
}

/**
* return length of the lang string, not including terminating 0
*
*
*/

gint wg_decode_unistr_lang_len(void* db, gint data, gint type) {
  char* langptr;
  gint len;

  langptr=wg_decode_unistr_lang(db,data,type);
  if (langptr==NULL) {
    return 0;
  }
  len=strlen(langptr);
  return len;
}


/**
* copy lang string, return length of a copied string, not including terminating 0
* in case of NULL lang write a single 0 to beginning of buffer and return 0
*
* return -1 in case of error
*
*/

gint wg_decode_unistr_lang_copy(void* db, gint data, char* strbuf, gint buflen, gint type) {
  char* langptr;
  gint len;

  langptr=wg_decode_unistr_lang(db,data,type);
  if (langptr==NULL) {
    *strbuf=0;
    return 0;
  }
  len=strlen(langptr);
  if (len>=buflen) {
    show_data_error_nr(db,"insufficient buffer length given to wg_decode_unistr_lang_copy:",buflen);
    return -1;
  }
  memcpy(strbuf,langptr,len+1);
  return len;
}





/* ----------- calendar and time functions ------------------- */

/*

Scalar date routines used are written and given to public domain by Ray Gardner.

*/

static int isleap(unsigned yr) {
  return yr % 400 == 0 || (yr % 4 == 0 && yr % 100 != 0);
}

static unsigned months_to_days (unsigned month) {
  return (month * 3057 - 3007) / 100;
}

static long years_to_days (unsigned yr) {
  return yr * 365L + yr / 4 - yr / 100 + yr / 400;
}

static long ymd_to_scalar (unsigned yr, unsigned mo, unsigned day) {
  long scalar;
  scalar = day + months_to_days(mo);
  if ( mo > 2 )                         /* adjust if past February */
      scalar -= isleap(yr) ? 1 : 2;
  yr--;
  scalar += years_to_days(yr);
  return scalar;
}

static void scalar_to_ymd (long scalar, unsigned *yr, unsigned *mo, unsigned *day) {
  unsigned n;                /* compute inverse of years_to_days() */

  for ( n = (unsigned)((scalar * 400L) / 146097L); years_to_days(n) < scalar;) n++; /* 146097 == years_to_days(400) */
  *yr = n;
  n = (unsigned)(scalar - years_to_days(n-1));
  if ( n > 59 ) {                       /* adjust if past February */
    n += 2;
    if (isleap(*yr))  n -= n > 62 ? 1 : 2;
  }
  *mo = (n * 100 + 3007) / 3057;    /* inverse of months_to_days() */
  *day = n - months_to_days(*mo);
}

/*

Thread-safe localtime_r appears not to be present on windows: emulate using win localtime_s, which is thread-safe

*/

#ifdef _WIN32
static struct tm * localtime_r (const time_t *timer, struct tm *result) {
   struct tm local_result;
   int res;

   res = localtime_s (&local_result,timer);
   if (!res) return NULL;
   //if (local_result == NULL || result == NULL) return NULL;
   memcpy (result, &local_result, sizeof (result));
   return result;
}
#endif


/* ------ value offset translation ---- */

/* Translate externally encoded value in relation to current base address
 *
 * Data argument is a value encoded in the database extdb. Returned value is
 * translated so that it can be used in WhiteDB API functions with the
 * database db.
 */
gint wg_encode_external_data(void *db, void *extdb, gint encoded) {
#ifdef USE_CHILD_DB
  return wg_translate_hdroffset(db, dbmemseg(extdb), encoded);
#else
  show_data_error(db, "child databases support is not enabled.");
  return WG_ILLEGAL;
#endif
}

#ifdef USE_CHILD_DB

gint wg_translate_hdroffset(void *db, void *exthdr, gint encoded) {
  gint extoff = ptrtooffset(db, exthdr); /* relative offset of external db */

  /* Only pointer-type values need translating */
  if(isptr(encoded)) {
    switch(encoded&NORMALPTRMASK) {
      case DATARECBITS:
        return encode_datarec_offset(
          decode_datarec_offset(encoded) + extoff);
      case LONGSTRBITS:
        return encode_longstr_offset(
          decode_longstr_offset(encoded) + extoff);
      case SHORTSTRBITS:
        return encode_shortstr_offset(
          decode_shortstr_offset(encoded) + extoff);
      case FULLDOUBLEBITS:
        return encode_fulldouble_offset(
          decode_fulldouble_offset(encoded) + extoff);
      case FULLINTBITSV0:
      case FULLINTBITSV1:
        return encode_fullint_offset(
          decode_fullint_offset(encoded) + extoff);
      default:
        /* XXX: it's not entirely correct to fail silently here, but
         * we can only end up here if new pointer types are added without
         * updating this function.
         */
        break;
    }
  }
  return encoded;
}

/** Return base address that an encoded value is "native" to.
 *
 * The external database must be registered first for the offset
 * to be recognized. Returns NULL if none of the registered
 * databases match.
 */
static void *get_ptr_owner(void *db, gint encoded) {
  gint offset = 0;

  if(isptr(encoded)) {
    switch(encoded&NORMALPTRMASK) {
      case DATARECBITS:
        offset = decode_datarec_offset(encoded);
      case LONGSTRBITS:
        offset = decode_longstr_offset(encoded);
      case SHORTSTRBITS:
        offset = decode_shortstr_offset(encoded);
      case FULLDOUBLEBITS:
        offset = decode_fulldouble_offset(encoded);
      case FULLINTBITSV0:
      case FULLINTBITSV1:
        offset = decode_fullint_offset(encoded);
      default:
        break;
    }
  } else {
    return dbmemseg(db); /* immediate values default to "Local" */
  }

  if(!offset)
    return NULL; /* data values do not point at memsegment header
                  * start anyway. */

  if(offset > 0 && offset < dbmemsegh(db)->size) {
    return dbmemseg(db);  /* "Local" record */
  } else {
    int i;
    db_memsegment_header* dbh = dbmemsegh(db);

    for(i=0; i<dbh->extdbs.count; i++) {
      if(offset > dbh->extdbs.offset[i] && \
        offset < dbh->extdbs.offset[i] + dbh->extdbs.size[i]) {
        return (void *) (dbmemsegbytes(db) + dbh->extdbs.offset[i]);
      }
    }
    return NULL;
  }
}

/** Check if an offset is "native" to the current database.
 *
 * Returns 1 if the offset is local, 0 otherwise.
 */
static int is_local_offset(void *db, gint offset) {
  if(offset > 0 && offset < dbmemsegh(db)->size) {
      return 1;  /* "Local" data */
  }
  return 0;
}
#endif

/** Return base address that the record belongs to.
 *
 *  Takes pointer values as arguments.
 *  The external database must be registered first for the offset
 *  to be recognized. Returns NULL if none of the registered
 *  databases match.
 *  XXX: needed to compile the lib under windows even
 *  if child databases are disabled.
 */
void *wg_get_rec_owner(void *db, void *rec) {
  int i;
  db_memsegment_header* dbh = dbmemsegh(db);

  if((gint) rec > (gint) dbmemseg(db)) {
    void *eodb = (void *) (dbmemsegbytes(db) + dbh->size);
    if((gint) rec < (gint) eodb)
      return dbmemseg(db);  /* "Local" record */
  }

  for(i=0; i<dbh->extdbs.count; i++) {
    void *base = (void *) (dbmemsegbytes(db) + dbh->extdbs.offset[i]);
    void *eodb = (void *) (((char *) base) + dbh->extdbs.size[i]);
    if((gint) rec > (gint) base && (gint) rec < (gint) eodb) {
      return base;
    }
  }
  show_data_error(db, "invalid pointer in wg_get_rec_base_offset");
  return NULL;
}

/* ------------ errors ---------------- */


static gint show_data_error(void* db, char* errmsg) {
#ifdef WG_NO_ERRPRINT
#else
  fprintf(stderr,"wg data handling error: %s\n",errmsg);
#endif
  return -1;

}

static gint show_data_error_nr(void* db, char* errmsg, gint nr) {
#ifdef WG_NO_ERRPRINT
#else
  fprintf(stderr,"wg data handling error: %s %d\n", errmsg, (int) nr);
#endif
  return -1;

}

static gint show_data_error_double(void* db, char* errmsg, double nr) {
#ifdef WG_NO_ERRPRINT
#else
  fprintf(stderr,"wg data handling error: %s %f\n",errmsg,nr);
#endif
  return -1;

}

static gint show_data_error_str(void* db, char* errmsg, char* str) {
#ifdef WG_NO_ERRPRINT
#else
  fprintf(stderr,"wg data handling error: %s %s\n",errmsg,str);
#endif
  return -1;
}

#ifdef __cplusplus
}
#endif