File: mxBeeBase.c

package info (click to toggle)
egenix-mx-base 3.2.1-1.1
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 8,496 kB
  • sloc: ansic: 21,976; python: 17,192; sh: 137; makefile: 116
file content (1911 lines) | stat: -rw-r--r-- 43,475 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
/* 
  mxBeeBase -- BeeBase C extension

  Copyright (c) 1998-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com
  Copyright (c) 2000-2011, eGenix.com Software GmbH; mailto:info@egenix.com
  See the documentation for further copyright information or contact
  the author (mailto:mal@lemburg.com).

*/

/* Define this to aid in finding memory leaks */
/*#define MAL_MEM_DEBUG*/
/*#define MAL_DEBUG*/

/* Logging file used by debugging facility */
#ifndef MAL_DEBUG_OUTPUTFILE
# define MAL_DEBUG_OUTPUTFILE "mxBeeBase.log"
#endif

/* We want all our symbols to be exported */
#define MX_BUILDING_MXBEEBASE

/* Mark the module as Py_ssize_t clean. */
#define PY_SSIZE_T_CLEAN 1

/* Setup mxstdlib memory management */
#if 1
# define MAL_USE_PYMALLOC
#else
# define MAL_USE_C_MALLOC
#endif

#include "mx.h"
#include "mxBeeBase.h"

/* Version number: Major.Minor.Patchlevel */
#define MXBEEBASE_VERSION "3.2.1"

/* Define these to have the module use free lists (saves malloc calls) */
/*#define MXBEEINDEX_FREELIST*/
#define MXBEECURSOR_FREELIST

/* --- module doc-string -------------------------------------------------- */

static char *Module_docstring = 

 MXBEEBASE_MODULE" -- BeeBase objects and functions. Version "MXBEEBASE_VERSION"\n\n"

 "Copyright (c) 1998-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com\n"
 "Copyright (c) 2000-2011, eGenix.com Software GmbH; mailto:info@egenix.com\n\n"
 "                 All Rights Reserved\n\n"
 "See the documentation for further information on copyrights,\n"
 "or contact the author."
;

/* --- module globals ----------------------------------------------------- */

static PyObject *mxBeeIndex_Error;		/* Exception object */
static PyObject *mxBeeCursor_Error;		/* Exception object */

/* Special keys */
static PyObject *mxBeeIndex_FirstKey;		/* First key */
static PyObject *mxBeeIndex_LastKey;		/* Last key */

/* Free lists for BeeIndex objects */
#ifdef MXBEEINDEX_FREELIST
static mxBeeIndexObject *mxBeeIndex_FreeList = NULL;
#endif

/* Free lists for BeeCursor objects */
#ifdef MXBEECURSOR_FREELIST
static mxBeeCursorObject *mxBeeCursor_FreeList = NULL;
#endif

/* Flag telling us whether the module was initialized or not. */
static int mxBeeBase_Initialized = 0;

/* --- forward declarations ----------------------------------------------- */

staticforward PyTypeObject mxBeeIndex_Type;
staticforward PyMethodDef mxBeeIndex_Methods[];

staticforward PyTypeObject mxBeeCursor_Type;
staticforward PyMethodDef mxBeeCursor_Methods[];

staticforward
mxBeeCursorObject *mxBeeCursor_New(mxBeeIndexObject *beeindex,   /* Index object */
				   bCursor *c                 /* bCursor */
				   );

/* --- internal macros ---------------------------------------------------- */

#define _mxBeeIndex_Check(v) \
        (((mxBeeIndexObject *)(v))->ob_type == &mxBeeIndex_Type)

#define _mxBeeCursor_Check(v) \
        (((mxBeeCursorObject *)(v))->ob_type == &mxBeeCursor_Type)

/* --- module helpers ----------------------------------------------------- */

/* Create an exception object, insert it into the module dictionary
   under the given name and return the object pointer; this is NULL in
   case an error occurred. */

static 
PyObject *insexc(PyObject *moddict,
		 char *name)
{
    PyObject *v;
    char fullname[256];
    char *modname;
    char *dot;
    
    v = PyDict_GetItemString(moddict, "__name__");
    if (v == NULL)
	modname = NULL;
    else
	modname = PyString_AsString(v);
    if (modname == NULL) {
	PyErr_Clear();
	modname = MXBEEBASE_MODULE;
    }
    /* The symbols from this extension are imported into
       mx.<packagename>. We trim the name to not confuse the user with
       an overly long package path. */
    strcpy(fullname, modname);
    dot = strchr(fullname, '.');
    if (dot)
	dot = strchr(dot+1, '.');
    if (dot)
	strcpy(dot+1, name);
    else
	sprintf(fullname, "%s.%s", modname, name);


    v = PyErr_NewException(fullname, NULL, NULL);
    if (v == NULL)
	return NULL;
    if (PyDict_SetItemString(moddict,name,v))
	return NULL;
    return v;
}

#if 0
/* Helper for adding integer constants to a dictionary. Check for
   errors with PyErr_Occurred() */
static 
void insint(PyObject *dict,
	    char *name,
	    int value)
{
    PyObject *v = PyInt_FromLong((long)value);
    PyDict_SetItemString(dict, name, v);
    Py_XDECREF(v);
}
#endif

/* Helper for adding objects to dictionaries. Check for errors with
   PyErr_Occurred() */
static 
void insobj(PyObject *dict,
	    char *name,
	    PyObject *v)
{
    PyDict_SetItemString(dict, name, v);
    Py_XDECREF(v);
}

/* Helper for adding objects to dictionaries. Check for errors with
   PyErr_Occurred() */
static 
PyObject *insstr(PyObject *dict,
		 char *name,
		 char *value)
{
    PyObject *v;
    
    v = PyString_FromString(value);
    if (!v)
	return NULL;
    if (PyDict_SetItemString(dict, name, v))
	return NULL;
    return v;
}

/* --- Internal functions --- */

void mxBeeBase_ReportError(bError rc) 
{
    switch (rc) {

    case bErrKeyNotFound:
	Py_Error(PyExc_KeyError,
		 "key not found");

    case bErrDupKeys:
	Py_Error(PyExc_KeyError,
		 "duplicate key");

    case bErrSectorSize:
	Py_Error(PyExc_ValueError,
		 "illegal sector size (too small or not 0 mod 4)");

    case bErrFileNotOpen:
	Py_ErrorWithArg(PyExc_IOError,
			"could not open file: '%s'",strerror(errno));

    case bErrFileExists:
	Py_Error(PyExc_IOError,
		 "file exists");

    case bErrNotWithDupKeys:
	Py_Error(mxBeeIndex_Error,
		 "not allowed with duplicate keys");

    case bErrBufferInvalid:
	Py_Error(mxBeeCursor_Error,
		 "buffer invalid - no data available");

    case bErrIO:
	Py_ErrorWith2Args(PyExc_IOError,
			  "in BeeIndex: '%s' (btr.c line %i)",strerror(errno),
			  bErrLineNo);

    case bErrMemory:
	Py_ErrorWithArg(PyExc_MemoryError,
			"in BeeIndex (line %i)",bErrLineNo);

    default:
	Py_Error(PyExc_SystemError,
		 "unknown error");
    }
 onError:
    return;
}

/* --- BeeBase Index Object -------------------------------------------*/

/* --- Allocation --- */

static
mxBeeIndexObject *mxBeeIndex_New(char *filename,   /* name of beeindex file */
				 int filemode,	   /* how to open the
						      file */
				 int keySize,      /* length of key in
						      bytes */
				 int sectorSize,   /* size of sector
						      on disk */
				 bCompFunc comp,   /* key compare
						      function */
				 mxObjectFromKeyFunc ofk, /* key
							     conversion */
				 mxKeyFromObjectFunc kfo, /* functions */
				 int allow_dupkeys /* allow duplicate
						      keys ? */
				 )
{
    mxBeeIndexObject *beeindex = 0;
    bDescription *info;
    bError rc;
    char *iName = strdup(filename);

    if (iName == NULL)
	Py_Error(PyExc_MemoryError,
		 "Out of memory");

    /* Allocate the object */
#ifdef MXBEEINDEX_FREELIST
    if (mxBeeIndex_FreeList) {
	beeindex = mxBeeIndex_FreeList;
	mxBeeIndex_FreeList = *(mxBeeIndexObject **)mxBeeIndex_FreeList;
	beeindex->ob_type = &mxBeeIndex_Type;
	_Py_NewReference(beeindex);
    }
    else
#endif 
	 {
	beeindex = PyObject_NEW(mxBeeIndexObject,&mxBeeIndex_Type);
	if (beeindex == NULL)
	    goto onError;
    }

    /* Init description */
    info = &beeindex->info;
    info->iName = iName;
    info->keySize = keySize;
    info->dupKeys = (allow_dupkeys != 0);
    info->sectorSize = sectorSize;
    info->comp = comp;
    info->filemode = filemode;

    /* Conversion routines */
    beeindex->ObjectFromKey = ofk;
    beeindex->KeyFromObject = kfo;

    /* Reset update count (also see mxBeeIndex_Clear()) */
    beeindex->updates = 0;

    /* Invalidate length cache */
    beeindex->length = -1;
    beeindex->length_state = -1;
    
    /* Open the beeindex */
    rc = bOpen(beeindex->info, &(beeindex->handle));
    if (rc != bErrOk) {
	beeindex->handle = 0;
	mxBeeBase_ReportError(rc);
	goto onError;
    }

    DPRINTF("mxBeeIndex_New: instance at %0lx\n",(long)beeindex);

    return beeindex;

 onError:
    Py_XDECREF(beeindex);
    return NULL;
}

/* --- Deallocation --- */

static
void mxBeeIndex_Free(mxBeeIndexObject *beeindex)
{
    DPRINTF("mxBeeIndex_Free: instance at %0lx\n",(long)beeindex);

    if (beeindex->handle)
	/* Close beeindex file, flushing any unsaved data */
	bClose(beeindex->handle);

    /* Free filename */
    free(beeindex->info.iName);
    beeindex->info.iName = NULL;
    
#ifdef MXBEEINDEX_FREELIST
    /* Append to free list */
    *(mxBeeIndexObject **)beeindex = mxBeeIndex_FreeList;
    mxBeeIndex_FreeList = beeindex;
#else
    PyObject_Del(beeindex);
#endif
}

/* --- Key management routines --- */

/* Use Python strings as keys (these may not contain embedded NULs) */
static
void *mxBeeIndex_KeyFromString(mxBeeIndexObject *beeindex,
			       PyObject *key)
{
    Py_Assert(PyString_Check(key),
	      PyExc_TypeError,
	      "keys must be strings");
    Py_AssertWithArg((int)PyString_GET_SIZE(key) < beeindex->info.keySize,
		     PyExc_TypeError,
		     "keys must not exceed length %li",
		     (unsigned long)beeindex->info.keySize - 1);
    Py_Assert((unsigned int) PyString_GET_SIZE(key) == strlen(PyString_AS_STRING(key)),
	      PyExc_TypeError,
	      "keys may not have embedded null bytes");

    return (void*)PyString_AS_STRING(key);
    
 onError:
    return NULL;
}

static
PyObject *mxBeeIndex_StringFromKey(mxBeeIndexObject *beeindex,
				   void *key)
{
    return PyString_FromString((char*)key);
}

static
int mxBeeIndex_CompareStrings(size_t keysize, 
			      const void *key1, 
			      const void *key2) 
{
    return strcmp((char*)key1, (char*)key2);
}

/* Use fixed length Python strings as keys (these may contain embedded
   NULs) */
static
void *mxBeeIndex_KeyFromFixedLengthString(mxBeeIndexObject *beeindex,
					  PyObject *key)
{
    Py_Assert(PyString_Check(key),
	      PyExc_TypeError,
	      "keys must be strings");
    Py_AssertWithArg((int)PyString_GET_SIZE(key) == beeindex->info.keySize - 1,
		     PyExc_TypeError,
		     "keys must have fixed length %li",
		     (unsigned long)beeindex->info.keySize - 1);

    return (void*)PyString_AS_STRING(key);
    
 onError:
    return NULL;
}

static
PyObject *mxBeeIndex_FixedLengthStringFromKey(mxBeeIndexObject *beeindex,
					      void *key)
{
    return PyString_FromStringAndSize((char*)key, 
				      (Py_ssize_t)(beeindex->info.keySize - 1));
}

static
int mxBeeIndex_CompareFixedLengthStrings(size_t keysize, 
					 const void *key1, 
					 const void *key2) 
{
    return memcmp((char*)key1, (char*)key2, keysize);
}

/* Use Python integer as keys */
static
void *mxBeeIndex_KeyFromInteger(mxBeeIndexObject *beeindex,
				PyObject *key)
{
    Py_Assert(PyInt_Check(key),
	      PyExc_TypeError,
	      "keys must be integers");
    return (void*)&PyInt_AS_LONG(key);
    
 onError:
    return NULL;
}

static
PyObject *mxBeeIndex_IntegerFromKey(mxBeeIndexObject *beeindex,
				    void *key)
{
    return PyInt_FromLong(*(long*)key);
}

static
int mxBeeIndex_CompareLongs(size_t keysize, 
			    const void *key1, 
			    const void *key2) 
{
    unsigned long a = *(unsigned long *)key1;
    unsigned long b = *(unsigned long *)key2;
    return (a == b) ? CC_EQ : (a > b) ? CC_GT : CC_LT;
}

/* Use Python floats as keys */
static
void *mxBeeIndex_KeyFromFloat(mxBeeIndexObject *beeindex,
			      PyObject *key)
{
    Py_Assert(PyFloat_Check(key),
	      PyExc_TypeError,
	      "keys must be floats");
    return (void*)&PyFloat_AS_DOUBLE(key);
    
 onError:
    return NULL;
}

static
PyObject *mxBeeIndex_FloatFromKey(mxBeeIndexObject *beeindex,
				  void *key)
{
    return PyFloat_FromDouble(*(double*)key);
}

static
int mxBeeIndex_CompareDoubles(size_t keysize, 
			      const void *key1, 
			      const void *key2) 
{
    double a = *(double *)key1;
    double b = *(double *)key2;
    return (a == b) ? CC_EQ : (a > b) ? CC_GT : CC_LT;
}

/* Python object to record address conversion.

   Returns 0 and raises an exception in case of an error. 
*/
static
bRecAddr mxBeeIndex_RecordAddressFromObject(PyObject *address)
{
    unsigned long value;
    
    if (!address)
	goto onError;

    /* Short cut */
    if (PyInt_Check(address))
	return (bRecAddr)PyInt_AS_LONG(address);

    /* file.tell() will return longs on platforms which have long file
       support */
    if (PyLong_Check(address))
	value = PyLong_AsUnsignedLong(address);
    else
	value = (unsigned long) PyInt_AsLong(address);
    if (value == (unsigned long) -1 && PyErr_Occurred())
	goto onError;
    return (bRecAddr)value;
    
 onError:
    PyErr_SetString(PyExc_TypeError,
		    "record address must be an integer or long");
    return 0;
}

/* Record address to Python object conversion.

   If the value fits into an Python integer object, then an integer is
   returned. Otherwise, a Python long object is used.

   Returns NULL and raises an exception in case of an error. 

*/
static
PyObject *mxBeeIndex_ObjectFromRecordAddress(bRecAddr recaddr)
{
    if ((unsigned long)recaddr > INT_MAX)
	return PyLong_FromUnsignedLong((unsigned long)recaddr);
    else
	return PyInt_FromLong((long)recaddr);
}

/* --- API functions --- */

static
long mxBeeIndex_FindKey(mxBeeIndexObject *self,
			PyObject *obj)
{
    bError rc;
    bCursor c;
    bRecAddr record = 0;
    void *key = self->KeyFromObject(self,obj);
    
    if (!key)
	goto onError;

    rc = bFindKey(self->handle,&c,key,&record);
    if (rc != bErrOk) {
	mxBeeBase_ReportError(rc);
	goto onError;
    }
    return (long)record;

 onError:
    return -1;
}

static
int mxBeeIndex_DeleteKey(mxBeeIndexObject *self,
			 PyObject *obj)
{
    bError rc;
    bRecAddr record = 0;
    void *key = self->KeyFromObject(self,obj);
    
    if (!key)
	goto onError;
    
    rc = bDeleteKey(self->handle,key,&record);
    if (rc != bErrOk) {
	mxBeeBase_ReportError(rc);
	goto onError;
    }

    /* Increment update count */
    self->updates++;

    return 0;

 onError:
    return -1;
   
}

static
int mxBeeIndex_SetKey(mxBeeIndexObject *self,
		      PyObject *obj,
		      PyObject *recaddr)
{
    bError rc;
    bRecAddr record;
    void *key = self->KeyFromObject(self,obj);
    
    if (!key)
	goto onError;
    
    record = mxBeeIndex_RecordAddressFromObject(recaddr);
    if (record == 0 && PyErr_Occurred())
	goto onError;

    /* Either insert or update the key; if dupkeys are allowed, only
       inserts are possible */
    if (!self->info.dupKeys) {
	rc = bUpdateKey(self->handle,key,record);
	if (rc == bErrKeyNotFound)
	    rc = bInsertKey(self->handle,key,record);
    }
    else
	rc = bInsertKey(self->handle,key,record);
    
    if (rc != bErrOk) {
	mxBeeBase_ReportError(rc);
	goto onError;
    }

    /* Increment update count */
    self->updates++;

    return 0;

 onError:
    return -1;
}

/* Clear the beeindex by reopening the file as new file. */

static
int mxBeeIndex_Clear(mxBeeIndexObject *self)
{
    bError rc;
    int filemode = self->info.filemode;

    Py_Assert(filemode != 1,
	      PyExc_IOError,
	      "beeindex is read-only");

    /* Close the file */
    if (self->handle)
	bClose(self->handle);

    /* Reopen the file as new file */
    self->info.filemode = 2;

    /* Open the beeindex */
    rc = bOpen(self->info,&(self->handle));
    if (rc != bErrOk) {
	mxBeeBase_ReportError(rc);
	goto onError;
    }

    /* Increment the update count */
    self->updates++;

    /* Invalidate length cache */
    self->length = -1;
    self->length_state = -1;
    
    /* Restore filemode */
    self->info.filemode = filemode;

    DPRINTF("mxBeeIndex_Clear: instance at %0lx\n",(long)self);

    return 0;

 onError:
    return -1;
}

/* --- Methods --- */

#define beeindex ((mxBeeIndexObject*)self)

Py_C_Function( mxBeeIndex_flush,
	       "flush()\n\n"
	       "Flush all buffers"
	       )
{
    bError rc;
    
    Py_NoArgsCheck();

    Py_Assert(beeindex->handle != NULL,
	      mxBeeIndex_Error,
	      "index is closed");
    rc = bFlush(beeindex->handle);
    if (rc != bErrOk) {
	mxBeeBase_ReportError(rc);
	goto onError;
    }
    Py_ReturnNone();

 onError:
    return NULL;
}

Py_C_Function( mxBeeIndex_close,
	       "close()\n\n"
	       "Close the index and flush all buffers"
	       )
{
    bError rc;
    
    Py_NoArgsCheck();

    if (beeindex->handle) {
	rc = bClose(beeindex->handle);
	if (rc != bErrOk) {
	    mxBeeBase_ReportError(rc);
	    goto onError;
	}
	beeindex->handle = NULL;
    }
    Py_ReturnNone();
    
 onError:
    return NULL;
}

Py_C_Function( mxBeeIndex_clear,
	       "clear()\n\n"
	       "Clear the index"
	       )
{
    Py_NoArgsCheck();

    if (mxBeeIndex_Clear(beeindex))
	goto onError;
    Py_ReturnNone();
    
 onError:
    return NULL;
}

Py_C_Function( mxBeeIndex_get,
	       "get(key,default=None)\n\n"
	       "Find the value for key. If key is not found, default is\n"
	       "returned. With dupkeys enabled, the first matching key is\n"
	       "used."
	       )
{
    PyObject *obj,*def = Py_None;
    bCursor c;
    bError rc;
    void *key;
    bRecAddr record = 0;

    Py_Get2Args("O|O",obj,def);

    Py_Assert(beeindex->handle != NULL,
	      mxBeeIndex_Error,
	      "index is closed");

    /* Find key */
    key = beeindex->KeyFromObject(beeindex,obj);
    if (!key)
	goto onError;
    rc = bFindKey(beeindex->handle,&c,key,&record);
    if (rc == bErrKeyNotFound) {
	Py_INCREF(def);
	return def;
    }
    if (rc != bErrOk) {
	mxBeeBase_ReportError(rc);
	goto onError;
    }
    return mxBeeIndex_ObjectFromRecordAddress(record);
    
 onError:
    return NULL;
}

Py_C_Function( mxBeeIndex_has_key,
	       "has_key(key)\n\n"
	       "Returns 1/0 depending on whether the key is found or not."
	       )
{
    PyObject *obj;
    bCursor c;
    bError rc;
    void *key;
    bRecAddr record = 0;

    Py_GetArg("O",obj);

    Py_Assert(beeindex->handle != NULL,
	      mxBeeIndex_Error,
	      "index is closed");

    /* Find key */
    key = beeindex->KeyFromObject(beeindex,obj);
    if (!key)
	goto onError;
    rc = bFindKey(beeindex->handle,&c,key,&record);
    if (rc == bErrKeyNotFound) {
	Py_INCREF(Py_False);
	return Py_False;
    }
    if (rc != bErrOk) {
	mxBeeBase_ReportError(rc);
	goto onError;
    }
    Py_INCREF(Py_True);
    return Py_True;
    
 onError:
    return NULL;
}

Py_C_Function( mxBeeIndex_cursor,
	       "cursor(key[,default])\n\n"
	       "Return a cursor pointing to key in the index. If dupkeys\n"
	       "are enabled, the cursors will always point to the first\n"
	       "of possibly multiple key entries found. In case no key\n"
	       "is found, default is returned if given or a KeyError\n"
	       "raised. Note that cursors only remain valid as long as\n"
	       "the index does not change."
	       )
{
    PyObject *obj,*v,*def = NULL;
    bCursor c;
    bError rc;

    Py_Get2Args("O|O",obj,def);

    Py_Assert(beeindex->handle != NULL,
	      mxBeeIndex_Error,
	      "index is closed");

    /* Find key */
    if (obj == mxBeeIndex_FirstKey)
	rc = bFindFirstKey(beeindex->handle,&c,NULL,NULL);
    else if (obj == mxBeeIndex_LastKey)
	rc = bFindLastKey(beeindex->handle,&c,NULL,NULL);
    else {
	void *key;
	key = beeindex->KeyFromObject(beeindex,obj);
	if (!key)
	    goto onError;
	rc = bFindKey(beeindex->handle,&c,key,NULL);
    }
    if (rc == bErrKeyNotFound && def) {
	Py_INCREF(def);
	return def;
    }
    if (rc != bErrOk) {
	mxBeeBase_ReportError(rc);
	goto onError;
    }

    /* Create cursor */
    v = (PyObject*)mxBeeCursor_New(beeindex,&c);
    if (!v)
	goto onError;

    return v;
    
 onError:
    return NULL;
}

Py_C_Function( mxBeeIndex_keys,
	       "keys()\n\n"
	       "Return a list of keys stored in the index. The list is\n"
	       "sorted ascending."
	       )
{
    bError rc;
    bCursor c;
    PyObject *v = 0;
    PyObject *w;

    Py_NoArgsCheck();

    Py_Assert(beeindex->handle != NULL,
	      mxBeeIndex_Error,
	      "index is closed");

    v = PyList_New(0);
    if (!v)
	goto onError;
    
    /* Find first */
    rc = bFindFirstKey(beeindex->handle,&c,NULL,NULL);
    if (rc == bErrKeyNotFound)
	return v;
    if (rc != bErrOk) {
	mxBeeBase_ReportError(rc);
	goto onError;
    }

    while (1) {
	w = beeindex->ObjectFromKey(beeindex,c.key);
	if (!w)
	    goto onError;
	PyList_Append(v,w);
	Py_DECREF(w);

	rc = bFindNextKey(beeindex->handle,&c,NULL,NULL);
	if (rc == bErrKeyNotFound)
	    break;
	if (rc != bErrOk) {
	    mxBeeBase_ReportError(rc);
	    goto onError;
	}
    }
    
    return v;
    
 onError:
    Py_XDECREF(v);
    return NULL;
}

Py_C_Function( mxBeeIndex_values,
	       "values()\n\n"
	       "Return a list of values stored in the index. The list is\n"
	       "sorted in ascending key order."
	       )
{
    bError rc;
    bCursor c;
    PyObject *v = 0;
    PyObject *w;
    bRecAddr rec;

    Py_NoArgsCheck();

    Py_Assert(beeindex->handle != NULL,
	      mxBeeIndex_Error,
	      "index is closed");

    v = PyList_New(0);
    if (!v)
	goto onError;

    /* Find first */
    rc = bFindFirstKey(beeindex->handle,&c,NULL,&rec);
    if (rc == bErrKeyNotFound)
	return v;
    if (rc != bErrOk) {
	mxBeeBase_ReportError(rc);
	goto onError;
    }

    while (1) {
	w = mxBeeIndex_ObjectFromRecordAddress(rec);
	if (!w)
	    goto onError;
	PyList_Append(v,w);
	Py_DECREF(w);

	rc = bFindNextKey(beeindex->handle,&c,NULL,&rec);
	if (rc == bErrKeyNotFound)
	    break;
	if (rc != bErrOk) {
	    mxBeeBase_ReportError(rc);
	    goto onError;
	}
    }
    
    return v;
    
 onError:
    Py_XDECREF(v);
    return NULL;
}

Py_C_Function( mxBeeIndex_items,
	       "items()\n\n"
	       "Return a list of (key,value) tuples of all items stored\n"
	       "in the index. The list is sorted ascending by key."
	       )
{
    bError rc;
    bCursor c;
    PyObject *v = 0;
    bRecAddr rec;

    Py_NoArgsCheck();

    Py_Assert(beeindex->handle != NULL,
	      mxBeeIndex_Error,
	      "index is closed");

    v = PyList_New(0);
    if (!v)
	goto onError;

    /* Find first */
    rc = bFindFirstKey(beeindex->handle,&c,NULL,&rec);
    if (rc == bErrKeyNotFound)
	return v;
    if (rc != bErrOk) {
	mxBeeBase_ReportError(rc);
	goto onError;
    }

    while (1) {
	PyObject *key,*value,*t;
	
	key = beeindex->ObjectFromKey(beeindex,c.key);
	if (!key)
	    goto onError;
	value = mxBeeIndex_ObjectFromRecordAddress(rec);
	if (!value) {
	    Py_DECREF(key);
	    goto onError;
	}
	t = PyTuple_New(2);
	if (!t) {
	    Py_DECREF(key);
	    Py_DECREF(value);
	    goto onError;
	}
	PyTuple_SET_ITEM(t,0,key);
	PyTuple_SET_ITEM(t,1,value);
	PyList_Append(v,t);
	Py_DECREF(t);

	rc = bFindNextKey(beeindex->handle,&c,NULL,&rec);
	if (rc == bErrKeyNotFound)
	    break;
	if (rc != bErrOk) {
	    mxBeeBase_ReportError(rc);
	    goto onError;
	}
    }
    
    return v;
    
 onError:
    Py_XDECREF(v);
    return NULL;
}

Py_C_Function( mxBeeIndex_delete,
	       "delete(key[,record])\n\n"
	       "Delete an entry. The record address is only needed in case\n"
	       "the index allows dupkeys."
	       )
{
    PyObject *obj;
    PyObject *recaddr = NULL;
    bError rc = bErrOk;
    bRecAddr record;
    void *key = NULL;
    
    Py_Get2Args("O|O",obj,recaddr);

    Py_Assert(beeindex->handle != NULL,
	      mxBeeIndex_Error,
	      "index is closed");

    if (beeindex->info.dupKeys)
	Py_Assert(recaddr != NULL,
		  PyExc_ValueError,
		  "record address must be given if dupkeys are allowed");

    key = beeindex->KeyFromObject(beeindex,obj);
    if (!key)
	goto onError;
    record = mxBeeIndex_RecordAddressFromObject(recaddr);
    if (record == 0 && PyErr_Occurred())
	goto onError;

    /* Delete key using record address if dupkeys is enabled */
    rc = bDeleteKey(beeindex->handle,key,&record);
    if (rc != bErrOk) {
	mxBeeBase_ReportError(rc);
	goto onError;
    }

    /* Increment update count */
    beeindex->updates++;

    Py_ReturnNone();

 onError:
    return NULL;
}

Py_C_Function( mxBeeIndex_update,
	       "update(key,value[,oldvalue])\n\n"
	       "Update an entry. The oldvalue is needed in case\n"
	       "the index allows dupkeys."
	       )
{
    PyObject *obj;
    bError rc = bErrOk;
    PyObject *value;
    PyObject *oldvalue = NULL;
    bRecAddr record, oldrecord;
    void *key = NULL;
    
    Py_Get3Args("OO|O",obj,value,oldvalue);

    Py_Assert(beeindex->handle != NULL,
	      mxBeeIndex_Error,
	      "index is closed");

    if (beeindex->info.dupKeys)
	Py_Assert(oldvalue != NULL,
		  PyExc_ValueError,
		  "oldvalue must be given if dupkeys are allowed");

    record = mxBeeIndex_RecordAddressFromObject(value);
    if (record == 0 && PyErr_Occurred())
	goto onError;
    if (oldvalue) {
	oldrecord = mxBeeIndex_RecordAddressFromObject(oldvalue);
	if (record == 0 && PyErr_Occurred())
	    goto onError;
    }
    else
	oldrecord = 0;
    key = beeindex->KeyFromObject(beeindex,obj);
    if (!key)
	goto onError;

    /* Delete key using oldrecord address if dupkeys is enabled */
    rc = bDeleteKey(beeindex->handle,key,&oldrecord);
    if (rc != bErrOk) {
	mxBeeBase_ReportError(rc);
	goto onError;
    }

    /* Insert the new key,value pair */
    rc = bInsertKey(beeindex->handle,key,record);
    if (rc != bErrOk) {
	mxBeeBase_ReportError(rc);
	goto onError;
    }

    /* Increment update count */
    beeindex->updates++;

    Py_ReturnNone();

 onError:
    return NULL;
}

Py_C_Function( mxBeeIndex_validate,
	       "validate()\n\n"
	       "Validates the BTree and return 1 for success and 0 for\n"
	       "failure. This is an internal debugging feature only."
	       )
{
    Py_NoArgsCheck();

    Py_Assert(beeindex->handle != NULL,
	      mxBeeIndex_Error,
	      "index is closed");

    return PyInt_FromLong(bValidateTree(beeindex->handle) == 0);
    
 onError:
    return NULL;
}

#undef beeindex

/* --- slots --- */

static
PyObject *mxBeeIndex_Getattr(PyObject *obj,
			     char *name)
{
    mxBeeIndexObject *self = (mxBeeIndexObject *)obj;
    
    if (Py_WantAttr(name,"closed"))
	return PyInt_FromLong((self->handle == NULL));

    else if (Py_WantAttr(name,"dupkeys"))
	return PyInt_FromLong(self->info.dupKeys);

    else if (Py_WantAttr(name,"filename"))
	return PyString_FromString(self->info.iName);

    else if (Py_WantAttr(name,"statistics")) {
	bHandle *handle = self->handle;
	Py_Assert(self->handle != NULL,
		  mxBeeIndex_Error,
		  "index is closed");
	return Py_BuildValue("iiiiiiiii",
			     self->updates,
			     handle->maxHeight,handle->nNodesIns,
			     handle->nNodesDel,handle->nKeysIns,
			     handle->nKeysDel,handle->nKeysUpd,
			     handle->nDiskReads,handle->nDiskWrites);
    }
    
    else if (Py_WantAttr(name,"__members__"))
	return Py_BuildValue("[ssss]",
			     "closed","statistics","dupkeys",
			     "filename");

    return Py_FindMethod(mxBeeIndex_Methods,
			 (PyObject *)self,name);
 onError:
    return NULL;
}

static
Py_ssize_t mxBeeIndex_Length(PyObject *obj)
{
    /* XXX Much too slow... */
    mxBeeIndexObject *self = (mxBeeIndexObject *)obj;
    bError rc;
    bCursor c;
    int i;
    
    Py_Assert(self->handle != NULL,
	      mxBeeIndex_Error,
	      "index is closed");

    if (self->length_state == self->updates)
	return self->length;

    /* Find first */
    rc = bFindFirstKey(self->handle,&c,NULL,NULL);
    if (rc == bErrKeyNotFound)
	return 0;
    if (rc != bErrOk) {
	mxBeeBase_ReportError(rc);
	goto onError;
    }
    i = 1;

    /* Scan all others */
    while (1) {
	rc = bFindNextKey(self->handle,&c,NULL,NULL);
	if (rc == bErrKeyNotFound)
	    break;
	if (rc != bErrOk) {
	    mxBeeBase_ReportError(rc);
	    goto onError;
	}
	i++;
    }

    self->length = i;
    self->length_state = self->updates;
    
    return i;

 onError:
    return -1;
}

static
PyObject *mxBeeIndex_Subscript(PyObject *obj,
			       PyObject *key)
{
    mxBeeIndexObject *self = (mxBeeIndexObject *)obj;
    bRecAddr record;

    Py_Assert(self->handle != NULL,
	      mxBeeIndex_Error,
	      "index is closed");

    record = mxBeeIndex_FindKey(self, key);
    if (record == -1 && PyErr_Occurred())
	goto onError;
    
    return mxBeeIndex_ObjectFromRecordAddress(record);

 onError:
    return NULL;
}

static
int mxBeeIndex_AssignSubscript(PyObject *obj,
			       PyObject *key,
			       PyObject *recaddr)
{
    mxBeeIndexObject *self = (mxBeeIndexObject *)obj;

    Py_Assert(self->handle != NULL,
	      mxBeeIndex_Error,
	      "index is closed");

    if (recaddr)
	return mxBeeIndex_SetKey(self, key, recaddr);
    else
	return mxBeeIndex_DeleteKey(self, key);

 onError:
    return -1;
}

/* Python Type Tables */

static PyMappingMethods mxBeeIndex_TypeAsMapping = {
	mxBeeIndex_Length, 		/*mp_length*/
	mxBeeIndex_Subscript, 		/*mp_subscript*/
	mxBeeIndex_AssignSubscript, 	/*mp_ass_subscript*/
};

statichere
PyTypeObject mxBeeIndex_Type = {
    PyObject_HEAD_INIT(0)		/* init at startup ! */
    0,			  		/*ob_size*/
    "BeeIndex",	  			/*tp_name*/
    sizeof(mxBeeIndexObject),      	/*tp_basicsize*/
    0,			  		/*tp_itemsize*/
    /* slots */
    (destructor)mxBeeIndex_Free,	/*tp_dealloc*/
    0,		  			/*tp_print*/
    mxBeeIndex_Getattr, 	 	/*tp_getattr*/
    0,		  			/*tp_setattr*/
    0,		 			/*tp_compare*/
    0,		  			/*tp_repr*/
    0,			 		/*tp_as_number*/
    0,					/*tp_as_sequence*/
    &mxBeeIndex_TypeAsMapping,		/*tp_as_mapping*/
    0,					/*tp_hash*/
    0,					/*tp_call*/
    0,					/*tp_str*/
    0,					/*tp_getattro*/
    0,					/*tp_setattro*/
    0,					/*tp_as_buffer*/
    0,					/*tp_xxx4*/
    0					/*tp_doc*/
};

/* Python Method Table */

statichere
PyMethodDef mxBeeIndex_Methods[] =
{   
    Py_MethodListEntry("get",mxBeeIndex_get),
    Py_MethodListEntry("cursor",mxBeeIndex_cursor),
    Py_MethodListEntry("has_key",mxBeeIndex_has_key),
    Py_MethodListEntryNoArgs("flush",mxBeeIndex_flush),
    Py_MethodListEntryNoArgs("close",mxBeeIndex_close),
    Py_MethodListEntryNoArgs("keys",mxBeeIndex_keys),
    Py_MethodListEntryNoArgs("values",mxBeeIndex_values),
    Py_MethodListEntryNoArgs("items",mxBeeIndex_items),
    Py_MethodListEntry("delete",mxBeeIndex_delete),
    Py_MethodListEntry("update",mxBeeIndex_update),
    Py_MethodListEntryNoArgs("clear",mxBeeIndex_clear),
    Py_MethodListEntryNoArgs("validate",mxBeeIndex_validate),
    {NULL,NULL} /* end of list */
};

/* --- BeeBase Cursor Object ------------------------------------------- */

statichere
mxBeeCursorObject *mxBeeCursor_New(mxBeeIndexObject *beeindex,   /* Index object */
				   bCursor *c                 /* bCursor */
				   )
{
    mxBeeCursorObject *cursor = 0;

    Py_Assert(beeindex->handle,
	      mxBeeCursor_Error,
	      "creating cursor for closed index");

    /* Allocate the object */
#ifdef MXBEEINDEX_FREELIST
    if (mxBeeCursor_FreeList) {
	cursor = mxBeeCursor_FreeList;
	mxBeeCursor_FreeList = *(mxBeeCursorObject **)mxBeeCursor_FreeList;
	cursor->ob_type = &mxBeeCursor_Type;
	_Py_NewReference(cursor);
    }
    else
#endif 
	 {
	cursor = PyObject_NEW(mxBeeCursorObject,&mxBeeCursor_Type);
	if (cursor == NULL)
	    goto onError;
    }

    /* Init vars */
    Py_INCREF(beeindex);
    cursor->beeindex = beeindex;
    memcpy(&cursor->c,c,sizeof(bCursor));
    cursor->adr = c->buffer->adr;
    cursor->updates = beeindex->updates;

    DPRINTF("mxBeeCursor_New: instance at %0lx\n",(long)cursor);

    return cursor;

 onError:
    Py_XDECREF(cursor);
    return NULL;
}

/* --- Deallocation --- */

static
void mxBeeCursor_Free(mxBeeCursorObject *cursor)
{
    DPRINTF("mxBeeCursor_Free: instance at %0lx\n",(long)cursor);

    /* Dereference beeindex object */
    Py_DECREF(cursor->beeindex);
    
#ifdef MXBEEINDEX_FREELIST
    /* Append to free list */
    *(mxBeeCursorObject **)cursor = mxBeeCursor_FreeList;
    mxBeeCursor_FreeList = cursor;
#else
    PyObject_Del(cursor);
#endif
}

/* --- API functions --- */

static
int mxBeeCursor_Invalid(mxBeeCursorObject *self)
{
    Py_Assert(self->beeindex->handle != NULL,
	      mxBeeCursor_Error,
	      "index is closed - cursor is invalid");
    Py_Assert(self->beeindex->updates == self->updates,
	      mxBeeCursor_Error,
	      "index was changed - cursor is invalid");
    Py_Assert(self->c.buffer && self->c.buffer->valid,
	      mxBeeCursor_Error,
	      "buffer was invalidated - cursor is invalid");
    Py_Assert(self->c.buffer->adr == self->adr,
	      mxBeeCursor_Error,
	      "buffer was overwritten - cursor is invalid");
    return 0;

 onError:
    return -1;
}

/* Move the cursor to the next beeindex key. If there are no further
   keys, return 0 and leave the cursor where it is. Otherwise return
   1. Returns -1 on error. */

static
int mxBeeCursor_NextKey(mxBeeCursorObject *self)
{
    bError rc;

    if (mxBeeCursor_Invalid(self))
	goto onError;

    /* Find key (updates cursor only on success) */
    rc = bFindNextKey(self->beeindex->handle,&self->c,NULL,NULL);
    if (rc == bErrKeyNotFound)
	return 0;
    if (rc != bErrOk) {
	mxBeeBase_ReportError(rc);
	goto onError;
    }

    /* Update cursor address */
    self->adr = self->c.buffer->adr;
    
    return 1;

 onError:
    return -1;
}

/* Move the cursor to the prev beeindex key. If there are no further
   keys, return 0 and leave the cursor where it is. Otherwise return
   1. Returns -1 on error. */

static
int mxBeeCursor_PrevKey(mxBeeCursorObject *self)
{
    bError rc;

    if (mxBeeCursor_Invalid(self))
	goto onError;

    /* Find key (updates cursor only on success) */
    rc = bFindPrevKey(self->beeindex->handle,&self->c,NULL,NULL);
    if (rc == bErrKeyNotFound)
	return 0;
    if (rc != bErrOk) {
	mxBeeBase_ReportError(rc);
	goto onError;
    }
    
    /* Update cursor address */
    self->adr = self->c.buffer->adr;
    
    return 1;

 onError:
    return -1;
}

static
PyObject *mxBeeCursor_GetKey(mxBeeCursorObject *self)
{
    PyObject *v;

    if (mxBeeCursor_Invalid(self))
	goto onError;

    /* Convert key to object */
    v = self->beeindex->ObjectFromKey(self->beeindex,self->c.key);
    if (!v)
	goto onError;

    return v;

 onError:
    return NULL;
}

static
PyObject *mxBeeCursor_GetValue(mxBeeCursorObject *self)
{
    bError rc;
    PyObject *v;
    bRecAddr rec;

    if (mxBeeCursor_Invalid(self))
	goto onError;

    /* Check that cursor is valid and read record address */
    rc = bCursorReadData(self->beeindex->handle,&self->c,NULL,&rec);
    if (rc != bErrOk) {
	mxBeeBase_ReportError(rc);
	goto onError;
    }

    v = mxBeeIndex_ObjectFromRecordAddress(rec);
    if (!v)
	goto onError;

    return v;

 onError:
    return NULL;
}

/* --- Methods --- */

#define cursor ((mxBeeCursorObject*)self)

Py_C_Function( mxBeeCursor_next,
	       "next()\n\n"
	       "Move to the next index entry. Returns 1 if there is another\n"
	       "entry, 0 otherwise. The cursor is not moved in case no\n"
	       "further entries exist."
	       )
{
    int found;
    PyObject *v;
    
    Py_NoArgsCheck();

    found = mxBeeCursor_NextKey(cursor);
    if (found < 0)
	goto onError;
    if (found) 
	v = Py_True;
    else
	v = Py_False;
    Py_INCREF(v);
    return v;

 onError:
    return NULL;
}

Py_C_Function( mxBeeCursor_prev,
	       "prev()\n\n"
	       "Move to the previous index entry. Returns 1 if there is\n"
	       "another entry, 0 otherwise. The cursor is not moved in\n"
	       "case no further entries exist."
	       )
{
    int found;
    PyObject *v;

    Py_NoArgsCheck();

    found = mxBeeCursor_PrevKey(cursor);
    if (found < 0)
	goto onError;
    if (found) 
	v = Py_True;
    else
	v = Py_False;
    Py_INCREF(v);
    return v;

 onError:
    return NULL;
}

Py_C_Function( mxBeeCursor_copy,
	       "copy()\n\n"
	       "Return a true copy of the cursor object. The copy can be\n"
	       "used independently from the original."
	       )
{
    Py_NoArgsCheck();

    if (mxBeeCursor_Invalid(cursor))
	goto onError;

    return (PyObject *)mxBeeCursor_New(cursor->beeindex,&cursor->c);

 onError:
    return NULL;
}

#undef cursor

/* --- slots --- */

static
PyObject *mxBeeCursor_Getattr(PyObject *obj,
			      char *name)
{
    mxBeeCursorObject *self = (mxBeeCursorObject *)obj;

    if (Py_WantAttr(name,"closed"))
	return PyInt_FromLong((self->beeindex->handle == NULL));

    if (Py_WantAttr(name,"key"))
	return mxBeeCursor_GetKey(self);

    if (Py_WantAttr(name,"value"))
	return mxBeeCursor_GetValue(self);

    if (Py_WantAttr(name,"valid")) {
	if (mxBeeCursor_Invalid(self)) {
	    PyErr_Clear();
	    Py_INCREF(Py_False);
	    return Py_False;
	}
	Py_INCREF(Py_True);
	return Py_True;
    }
    
    else if (Py_WantAttr(name,"__members__"))
	return Py_BuildValue("[ssss]",
			     "closed","key","value",
			     "valid");

    return Py_FindMethod(mxBeeCursor_Methods,
			 (PyObject *)self,name);
}

/* Python Type Tables */

statichere
PyTypeObject mxBeeCursor_Type = {
    PyObject_HEAD_INIT(0)		/* init at startup ! */
    0,			  		/*ob_size*/
    "BeeCursor",	  		/*tp_name*/
    sizeof(mxBeeCursorObject),      	/*tp_basicsize*/
    0,			  		/*tp_itemsize*/
    /* slots */
    (destructor)mxBeeCursor_Free,	/*tp_dealloc*/
    0,		  			/*tp_print*/
    mxBeeCursor_Getattr,  		/*tp_getattr*/
    0,		  			/*tp_setattr*/
    0,		 	       		/*tp_compare*/
    0,				  	/*tp_repr*/
    0,			 		/*tp_as_number*/
    0,					/*tp_as_sequence*/
    0,					/*tp_as_mapping*/
    0,					/*tp_hash*/
    0,					/*tp_call*/
    0,					/*tp_str*/
    0,					/*tp_getattro*/
    0,					/*tp_setattro*/
    0,					/*tp_as_buffer*/
    0,					/*tp_xxx4*/
    0					/*tp_doc*/
};

/* Python Method Table */

statichere
PyMethodDef mxBeeCursor_Methods[] =
{   
    Py_MethodListEntryNoArgs("next",mxBeeCursor_next),
    Py_MethodListEntryNoArgs("prev",mxBeeCursor_prev),
    Py_MethodListEntryNoArgs("copy",mxBeeCursor_copy),
    {NULL,NULL} /* end of list */
};

/* --- Module Interface ---------------------------------------------------- */

Py_C_Function_WithKeywords(
    mxBeeIndex_BeeStringIndex,
    "BeeStringIndex(filename,keysize,dupkeys=0,filemode=0,sectorsize=256)\n\n"
    )
{
    char *filename;
    int keysize;
    int sectorsize = 256;
    int dupkeys = 0;
    int filemode = 0;

    Py_KeywordsGet5Args("si|iii",
			filename,keysize,dupkeys,filemode,sectorsize);

    return (PyObject *)mxBeeIndex_New(filename,
				      filemode,
				      keysize + 1,
				      sectorsize,
				      mxBeeIndex_CompareStrings,
				      mxBeeIndex_StringFromKey,
				      mxBeeIndex_KeyFromString,
				      dupkeys);
 onError:
    return NULL;
}

Py_C_Function_WithKeywords(
    mxBeeIndex_BeeFixedLengthStringIndex,
    "BeeFixedLengthStringIndex(filename,keysize,dupkeys=0,filemode=0,sectorsize=256)\n\n"
    )
{
    char *filename;
    int keysize;
    int sectorsize = 256;
    int dupkeys = 0;
    int filemode = 0;

    Py_KeywordsGet5Args("si|iii",
			filename,keysize,dupkeys,filemode,sectorsize);

    return (PyObject *)mxBeeIndex_New(filename,
				      filemode,
				      keysize + 1,
				      sectorsize,
				      mxBeeIndex_CompareFixedLengthStrings,
				      mxBeeIndex_FixedLengthStringFromKey,
				      mxBeeIndex_KeyFromFixedLengthString,
				      dupkeys);
 onError:
    return NULL;
}

Py_C_Function_WithKeywords(
    mxBeeIndex_BeeIntegerIndex,
    "BeeIntegerIndex(filename,dupkeys=0,filemode=0,sectorsize=256)\n\n"
    )
{
    char *filename;
    int keysize = sizeof(long);
    int sectorsize = 256;
    int dupkeys = 0;
    int filemode = 0;

    Py_KeywordsGet4Args("s|iii",
			filename,dupkeys,filemode,sectorsize);

    return (PyObject *)mxBeeIndex_New(filename,
				      filemode,
				      keysize,
				      sectorsize,
				      mxBeeIndex_CompareLongs,
				      mxBeeIndex_IntegerFromKey,
				      mxBeeIndex_KeyFromInteger,
				      dupkeys);
 onError:
    return NULL;
}

Py_C_Function_WithKeywords(
    mxBeeIndex_BeeFloatIndex,
    "BeeFloatIndex(filename,dupkeys=0,filemode=0,sectorsize=256)\n\n"
    )
{
    char *filename;
    int keysize = sizeof(double);
    int sectorsize = 256;
    int dupkeys = 0;
    int filemode = 0;

    Py_KeywordsGet4Args("s|iii",
			filename,dupkeys,filemode,sectorsize);

    return (PyObject *)mxBeeIndex_New(filename,
				      filemode,
				      keysize,
				      sectorsize,
				      mxBeeIndex_CompareDoubles,
				      mxBeeIndex_FloatFromKey,
				      mxBeeIndex_KeyFromFloat,
				      dupkeys);
 onError:
    return NULL;
}

/* Python Method Table */

static 
PyMethodDef Module_methods[] =
{   
    Py_MethodWithKeywordsListEntry("BeeStringIndex",
				   mxBeeIndex_BeeStringIndex),
    Py_MethodWithKeywordsListEntry("BeeFixedLengthStringIndex",
				   mxBeeIndex_BeeFixedLengthStringIndex),
    Py_MethodWithKeywordsListEntry("BeeIntegerIndex",
				   mxBeeIndex_BeeIntegerIndex),
    Py_MethodWithKeywordsListEntry("BeeFloatIndex",
				   mxBeeIndex_BeeFloatIndex),
    {NULL,NULL} /* end of list */
};

/* Cleanup function */
static 
void mxBeeBaseModule_Cleanup(void)
{
#ifdef MXBEEINDEX_FREELIST
    {
	mxBeeIndexObject *d = mxBeeIndex_FreeList;
	while (d != NULL) {
	    mxBeeIndexObject *v = d;
	    d = *(mxBeeIndexObject **)d;
	    PyObject_Del(v);
	}
	mxBeeIndex_FreeList = NULL;
    }
#endif
#ifdef MXBEECURSOR_FREELIST
    {
	mxBeeCursorObject *d = mxBeeCursor_FreeList;
	while (d != NULL) {
	    mxBeeCursorObject *v = d;
	    d = *(mxBeeCursorObject **)d;
	    PyObject_Del(v);
	}
	mxBeeCursor_FreeList = NULL;
    }
#endif
    /* Reset mxBeeBase_Initialized flag */
    mxBeeBase_Initialized = 0;
}

/* Create PyMethodObjects and register them in the module's dict */
MX_EXPORT(void) 
     initmxBeeBase(void)
{
    PyObject *module, *moddict;

    if (mxBeeBase_Initialized)
	Py_Error(PyExc_SystemError,
		 "can't initialize "MXBEEBASE_MODULE" more than once");

    /* Init type objects */
    PyType_Init(mxBeeIndex_Type);
    PyType_Init(mxBeeCursor_Type);

    /* Create module */
    module = Py_InitModule4(MXBEEBASE_MODULE, /* Module name */
			    Module_methods, /* Method list */
			    Module_docstring, /* Module doc-string */
			    (PyObject *)NULL, /* always pass this as *self */
			    PYTHON_API_VERSION); /* API Version */
    if (module == NULL)
	goto onError;

    /* Init globals */
#ifdef MXBEEINDEX_FREELIST
    mxBeeIndex_FreeList = NULL;
#endif
#ifdef MXBEECURSOR_FREELIST
    mxBeeCursor_FreeList = NULL;
#endif

    /* Register cleanup function */
    if (Py_AtExit(mxBeeBaseModule_Cleanup))
	/* XXX what to do if we can't register that function ??? */;

    /* Add some constants to the module's dict */
    moddict = PyModule_GetDict(module);
    if (moddict == NULL)
	goto onError;
    insobj(moddict,"__version__",PyString_FromString(MXBEEBASE_VERSION));

    /* Errors */
    if (!(mxBeeIndex_Error = insexc(moddict,"BeeIndexError")))
	goto onError;
    if (!(mxBeeCursor_Error = insexc(moddict,"BeeCursorError")))
	goto onError;

    /* Special keys */
    mxBeeIndex_FirstKey = insstr(moddict,"FirstKey","FirstKey");
    if (!mxBeeIndex_FirstKey)
	goto onError;
    mxBeeIndex_LastKey = insstr(moddict,"LastKey","LastKey");
    if (!mxBeeIndex_LastKey)
	goto onError;

    /* Type objects */
    Py_INCREF(&mxBeeIndex_Type);
    PyDict_SetItemString(moddict,"BeeIndexType",
			 (PyObject *)&mxBeeIndex_Type);
    Py_INCREF(&mxBeeCursor_Type);
    PyDict_SetItemString(moddict,"BeeCursorType",
			 (PyObject *)&mxBeeCursor_Type);

    /* We are now initialized */
    mxBeeBase_Initialized = 1;

 onError:
    /* Check for errors and report them */
    if (PyErr_Occurred())
	Py_ReportModuleInitError(MXBEEBASE_MODULE);
    return;
}