File: BTree.c

package info (click to toggle)
hfsprogs 332.25-11
  • links: PTS
  • area: main
  • in suites: bullseye, buster, jessie, jessie-kfreebsd, sid, stretch
  • size: 6,440 kB
  • ctags: 7,805
  • sloc: ansic: 58,120; makefile: 25
file content (1804 lines) | stat: -rw-r--r-- 48,371 bytes parent folder | download | duplicates (3)
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
/*
 * Copyright (c) 1999, 2005 Apple Computer, Inc. All rights reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 * 
 * "Portions Copyright (c) 1999 Apple Computer, Inc.  All Rights
 * Reserved.  This file contains Original Code and/or Modifications of
 * Original Code as defined in and that are subject to the Apple Public
 * Source License Version 1.0 (the 'License').  You may not use this file
 * except in compliance with the License.  Please obtain a copy of the
 * License at http://www.apple.com/publicsource and read it before using
 * this file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT.  Please see the
 * License for the specific language governing rights and limitations
 * under the License."
 * 
 * @APPLE_LICENSE_HEADER_END@
 */
/*
	File:		BTree.c

	Contains:	Implementation of public interface routines for B-tree manager.

	Version:	HFS Plus 1.0

	Written by:	Gordon Sheridan and Bill Bruffey

	Copyright:	� 1992-1999 by Apple Computer, Inc., all rights reserved.
*/


#include "BTree.h"
#include "BTreePrivate.h"
//#include "HFSInstrumentation.h"


extern Boolean NodesAreContiguous(SFCB *fcb, UInt32 nodeSize);

/*-------------------------------------------------------------------------------
Routine:	CopyKey

Function:	Copy a BTree key.  Sanity check the key length; if it is too large,
			then set the copy's length to the BTree's maximum key length.

Inputs:		btcb		BTree whose key is being copied
			srcKey		Source key being copied

Output:		destKey		Destination where copy will be stored

Result:		none (void)
-------------------------------------------------------------------------------*/
static void CopyKey(BTreeControlBlockPtr btcb, const BTreeKey *srcKey, BTreeKey *destKey)
{
	unsigned	keySize = CalcKeySize(btcb, srcKey);
	unsigned	maxKeySize = MaxKeySize(btcb);
	int			fixLength = 0;
	
	/*
	 *	If the key length is too long (corrupted), then constrain the number
	 *	of bytes to copy.  Remember that we did this so we can also update
	 *	the copy's length field later.
	 */
	if (keySize > maxKeySize)
	{
		keySize = maxKeySize;
		fixLength = 1;
	}
	
	CopyMemory(srcKey, destKey, keySize);
	
	/*
	 *	If we had to constrain the key size above, then also update the
	 *	key length in the copy.  This will prevent the caller from dereferencing
	 *	part of the key which we never actually copied.
	 */
	if (fixLength)
	{
		if (btcb->attributes & kBTBigKeysMask)
			destKey->length16 = btcb->maxKeyLength;
		else
			destKey->length8 = btcb->maxKeyLength;
	}
}


//////////////////////////////////// Globals ////////////////////////////////////


/////////////////////////// BTree Module Entry Points ///////////////////////////


/*-------------------------------------------------------------------------------
Routine:	InitBTreeModule	-	Initialize BTree Module Global(s).

Function:	Initialize BTree code, if necessary

Input:		none

Output:		none

Result:		noErr		- success
			!= noErr	- can't happen
-------------------------------------------------------------------------------*/

OSStatus	InitBTreeModule(void)
{
	return noErr;
}


/*-------------------------------------------------------------------------------
Routine:	BTInitialize	-	Initialize a fork for access as a B*Tree.

Function:	Write Header node and create any map nodes necessary to map the fork
			as a B*Tree. If the fork is not large enough for the header node, the
			FS Agent is called to extend the LEOF. Additional map nodes will be
			allocated if necessary to represent the size of the fork. This allows
			the FS Agent to specify the initial size of B*Tree files.


Input:		pathPtr			- pointer to path control block
			maxKeyLength	- maximum length that will be used for any key in this B*Tree
			nodeSize		- node size for B*Tree (must be 2^n, 9 >= n >= 15)
			btreeType		- type of B*Tree
			keyDescPtr		- pointer to key descriptor (optional if key compare proc is used)

Output:		none

Result:		noErr		- success
			paramErr		- mandatory parameter was missing
			E_NoGetBlockProc		- FS Agent CB has no GetNodeProcPtr
			E_NoReleaseBlockProc	- FS Agent CB has no ReleaseNodeProcPtr
			E_NoSetEndOfForkProc	- FS Agent CB has no SetEndOfForkProcPtr
			E_NoSetBlockSizeProc	- FS Agent CB has no SetBlockSizeProcPtr
			fsBTrFileAlreadyOpenErr	- fork is already open as a B*Tree
			fsBTInvalidKeyLengthErr		- maximum key length is out of range
			E_BadNodeType			- node size is an illegal value
			fsBTUnknownVersionErr	- the B*Tree type is unknown by this module
			memFullErr			- not enough memory to initialize B*Tree
			!= noErr	- failure
-------------------------------------------------------------------------------*/
#if 0
OSStatus	BTInitialize		(FCB					*filePtr,
								 UInt16					 maxKeyLength,
								 UInt16					 nodeSize,
								 UInt8					 btreeType,
								 KeyDescriptorPtr		 keyDescPtr )
{
	OSStatus				err;
	FSForkControlBlockPtr	 	forkPtr;
	BTreeControlBlockPtr	btreePtr;
	BlockDescriptor			headerNode;
	HeaderPtr				header;
	Ptr						pos;
	FSSize					minEOF, maxEOF;
	SetEndOfForkProcPtr		setEndOfForkProc;
	SetBlockSizeProcPtr		setBlockSizeProc;

	////////////////////// Preliminary Error Checking ///////////////////////////

	headerNode.buffer	= NULL;

	if (pathPtr == NULL)	return  paramErr;

	setEndOfForkProc	= pathPtr->agentPtr->agent.setEndOfForkProc;
	setBlockSizeProc	= pathPtr->agentPtr->agent.setBlockSizeProc;

	if (pathPtr->agentPtr->agent.getBlockProc == NULL)	return  E_NoGetBlockProc;
	if (pathPtr->agentPtr->agent.releaseBlockProc == NULL)	return  E_NoReleaseBlockProc;
	if (setEndOfForkProc == NULL)	return  E_NoSetEndOfForkProc;
	if (setBlockSizeProc == NULL)	return  E_NoSetBlockSizeProc;

	forkPtr = pathPtr->path.forkPtr;

	if (forkPtr->fork.btreePtr != NULL) return	fsBTrFileAlreadyOpenErr;

	if ((maxKeyLength == 0) ||
		(maxKeyLength >  kMaxKeyLength))					return	fsBTInvalidKeyLengthErr;

	if ( M_IsEven (maxKeyLength))	++maxKeyLength;			// len byte + even bytes + pad byte

	switch (nodeSize)										// node size == 512*2^n
	{
		case   512:
		case  1024:
		case  2048:
		case  4096:
		case  8192:
		case 16384:
		case 32768:		break;
		default:		return	E_BadNodeType;
	}

	switch (btreeType)
	{
		case kHFSBTreeType:
		case kUserBTreeType:
		case kReservedBTreeType:	break;

		default:					return	fsBTUnknownVersionErr;		//�� right?
	}


	//////////////////////// Allocate Control Block /////////////////////////////

	M_RESIDENT_ALLOCATE_FIXED_CLEAR( &btreePtr, sizeof( BTreeControlBlock ), kFSBTreeControlBlockType );
	if (btreePtr == NULL)
	{
		err = memFullErr;
		goto ErrorExit;
	}

	btreePtr->version			= kBTreeVersion;			//�� what is the version?
	btreePtr->reserved1			= 0;
	btreePtr->flags				= 0;
	btreePtr->attributes		= 0;
	btreePtr->forkPtr			= forkPtr;
	btreePtr->keyCompareProc	= NULL;
	btreePtr->keyDescPtr		= keyDescPtr;
	btreePtr->btreeType			= btreeType;
	btreePtr->treeDepth			= 0;
	btreePtr->rootNode			= 0;
	btreePtr->leafRecords		= 0;
	btreePtr->firstLeafNode		= 0;
	btreePtr->lastLeafNode		= 0;
	btreePtr->nodeSize			= nodeSize;
	btreePtr->maxKeyLength		= maxKeyLength;
	btreePtr->totalNodes		= 1;			// so ExtendBTree adds maps nodes properly
	btreePtr->freeNodes			= 0;
	btreePtr->writeCount		= 1;			//	<CS10>, for BTree scanner

	// set block size = nodeSize
	err = setBlockSizeProc (forkPtr, nodeSize);
	M_ExitOnError (err);

	////////////////////////////// Check LEOF ///////////////////////////////////

	minEOF = nodeSize;
	if ( forkPtr->fork.logicalEOF < minEOF )
	{
		// allocate more space if necessary
		maxEOF 0xFFFFFFFFL;

		err = setEndOfForkProc (forkPtr, minEOF, maxEOF);
		M_ExitOnError (err);
	};


	//////////////////////// Initialize Header Node /////////////////////////////

	err = GetNewNode (btreePtr, kHeaderNodeNum, &headerNode);
	M_ExitOnError (err);

	header = headerNode.buffer;

	header->node.type			= kHeaderNode;
	header->node.numRecords		= 3;			// header rec, key desc, map rec

	header->nodeSize			= nodeSize;
	header->maxKeyLength		= maxKeyLength;
	header->btreeType			= btreeType;
	header->totalNodes			= btreePtr->totalNodes;
	header->freeNodes			= btreePtr->totalNodes - 1;
	// ignore					  header->clumpSize;	//�� rename this field?

	// mark header node allocated in map record
	pos		= ((Ptr)headerNode.buffer) + kHeaderMapRecOffset;
	*pos	= 0x80;

	// set node offsets ( nodeSize-8, F8, 78, 0E)
	pos	 = ((Ptr)headerNode.buffer) + nodeSize;
	pos	-= 2;		*((UInt16 *)pos) = kHeaderRecOffset;
	pos	-= 2;		*((UInt16 *)pos) = kKeyDescRecOffset;
	pos -= 2;		*((UInt16 *)pos) = kHeaderMapRecOffset;
	pos -= 2;		*((UInt16 *)pos) = nodeSize - 8;


	///////////////////// Copy Key Descriptor To Header /////////////////////////
#if SupportsKeyDescriptors
	if (keyDescPtr != NULL)
	{
		err = CheckKeyDescriptor (keyDescPtr, maxKeyLength);
		M_ExitOnError (err);

		// copy to header node
		pos = ((Ptr)headerNode.buffer) + kKeyDescRecOffset;
		CopyMemory (keyDescPtr, pos, keyDescPtr->length + 1);
	}
#endif

	// write header node
	err = UpdateNode (btreePtr, &headerNode);
	M_ExitOnError (err);


	////////////////////////// Allocate Map Nodes ///////////////////////////////

	err = ExtendBTree (btreePtr, forkPtr->fork.logicalEOF.lo / nodeSize);	// sets totalNodes
	M_ExitOnError (err);


	////////////////////////////// Close BTree //////////////////////////////////

	err = UpdateHeader (btreePtr);
	M_ExitOnError (err);

	pathPtr->path.forkPtr->fork.btreePtr = NULL;
	M_RESIDENT_DEALLOCATE_FIXED( btreePtr, sizeof( BTreeControlBlock ), kFSBTreeControlBlockType );

	return	noErr;


	/////////////////////// Error - Clean up and Exit ///////////////////////////

ErrorExit:

	(void) ReleaseNode (btreePtr, &headerNode);
	if (btreePtr != NULL)
		M_RESIDENT_DEALLOCATE_FIXED( btreePtr, sizeof( BTreeControlBlock ), kFSBTreeControlBlockType );

	return	err;
}
#endif


/*-------------------------------------------------------------------------------
Routine:	BTOpenPath	-	Open a file for access as a B*Tree.

Function:	Create BTree control block for a file, if necessary. Validates the
			file to be sure it looks like a BTree file.


Input:		filePtr				- pointer to file to open as a B-tree
			keyCompareProc		- pointer to client's KeyCompare function
			getBlockProc		- pointer to client's GetBlock function
			releaseBlockProc	- pointer to client's ReleaseBlock function
			setEndOfForkProc	- pointer to client's SetEOF function

Result:		noErr				- success
			paramErr			- required ptr was NULL
			fsBTInvalidFileErr				-
			memFullErr			-
			!= noErr			- failure
-------------------------------------------------------------------------------*/

OSStatus	BTOpenPath			(SFCB					*filePtr,
								 KeyCompareProcPtr		 keyCompareProc,
								 GetBlockProcPtr		 getBlockProc,
								 ReleaseBlockProcPtr	 releaseBlockProc,
								 SetEndOfForkProcPtr	 setEndOfForkProc,
								 SetBlockSizeProcPtr	 setBlockSizeProc )
{
	OSStatus				err;
	BTreeControlBlockPtr	btreePtr;
	BTHeaderRec				*header;
	NodeRec					nodeRec;

//	LogStartTime(kTraceOpenBTree);

	////////////////////// Preliminary Error Checking ///////////////////////////

	if (filePtr == NULL ||
		 getBlockProc == NULL ||
		 releaseBlockProc == NULL ||
		 setEndOfForkProc == NULL ||
		 setBlockSizeProc == NULL)
	{
		return  paramErr;
	}

	if (filePtr->fcbBtree != NULL)			// already has a BTreeCB
		return noErr;

												// is file large enough to contain header node?
	if ( filePtr->fcbLogicalSize < kMinNodeSize )
		return fsBTInvalidFileErr;							//�� or E_BadHeader?


	//////////////////////// Allocate Control Block /////////////////////////////

	btreePtr = (BTreeControlBlock*) AllocateClearMemory( sizeof( BTreeControlBlock ) );
	if (btreePtr == NULL)
	{
		Panic ("\pBTOpen: no memory for btreePtr.");
		return	memFullErr;
	}

	btreePtr->getBlockProc		= getBlockProc;
	btreePtr->releaseBlockProc	= releaseBlockProc;
	btreePtr->setEndOfForkProc	= setEndOfForkProc;
	btreePtr->keyCompareProc	= keyCompareProc;

	/////////////////////////// Read Header Node ////////////////////////////////

	nodeRec.buffer				= NULL;				// so we can call ReleaseNode
	
	btreePtr->fcbPtr			= filePtr;
	filePtr->fcbBtree			= (void *) btreePtr;	// attach btree cb to file

	// it is now safe to call M_ExitOnError (err)

	err = setBlockSizeProc (btreePtr->fcbPtr, kMinNodeSize);
	M_ExitOnError (err);


	err = getBlockProc (btreePtr->fcbPtr,
						kHeaderNodeNum,
						kGetBlock,
						&nodeRec );

	PanicIf (err != noErr, "\pBTOpen: getNodeProc returned error getting header node.");
	M_ExitOnError (err);

	header = (BTHeaderRec*) (nodeRec.buffer + sizeof(BTNodeDescriptor));


	///////////////////////////// verify header /////////////////////////////////

	err = VerifyHeader (filePtr, header);
	M_ExitOnError (err);


	///////////////////// Initalize fields from header //////////////////////////
	
	PanicIf ( (filePtr->fcbVolume->vcbSignature != 0x4244) && (btreePtr->nodeSize == 512), "\p BTOpenPath: wrong node size for HFS+ volume!");

	btreePtr->treeDepth			= header->treeDepth;
	btreePtr->rootNode			= header->rootNode;
	btreePtr->leafRecords		= header->leafRecords;
	btreePtr->firstLeafNode		= header->firstLeafNode;
	btreePtr->lastLeafNode		= header->lastLeafNode;
	btreePtr->nodeSize			= header->nodeSize;
	btreePtr->maxKeyLength		= header->maxKeyLength;
	btreePtr->totalNodes		= header->totalNodes;
	btreePtr->freeNodes			= header->freeNodes;
	// ignore					  header->clumpSize;	//�� rename this field?
	btreePtr->btreeType			= header->btreeType;

	btreePtr->attributes		= header->attributes;

	if ( btreePtr->maxKeyLength > 40 )
		btreePtr->attributes |= (kBTBigKeysMask + kBTVariableIndexKeysMask);	//�� we need a way to save these attributes

	/////////////////////// Initialize dynamic fields ///////////////////////////

	btreePtr->version			= kBTreeVersion;
	btreePtr->flags				= 0;
	btreePtr->writeCount		= 1;		//	<CS10>, for BTree scanner

	btreePtr->numGetNodes		= 1;		// for earlier call to getNodeProc

	/////////////////////////// Check Header Node ///////////////////////////////

	//�� set kBadClose attribute bit, and UpdateNode

	/*
	 * If the actual node size is different than the amount we read,
	 * then release and trash this block, and re-read with the correct
	 * node size.
	 */
	if ( btreePtr->nodeSize != kMinNodeSize )
	{
		err = setBlockSizeProc (btreePtr->fcbPtr, btreePtr->nodeSize);
		M_ExitOnError (err);

#if BSD
		/*
		 * Need to use kTrashBlock option to force the
		 * buffer cache to re-read the entire node
		 */
		err = releaseBlockProc(btreePtr->fcbPtr, &nodeRec, kTrashBlock);
#else
		err = ReleaseNode (btreePtr, &nodeRec);
#endif
	
		err = GetNode (btreePtr, kHeaderNodeNum, &nodeRec );		// calls CheckNode...
		M_ExitOnError (err);
	}

	//�� total nodes * node size <= LEOF?


	////////////////////////// Get Key Descriptor ///////////////////////////////
#if SupportsKeyDescriptors
	if (keyCompareProc == NULL)		// 	if no key compare proc then get key descriptor
	{
		err = GetKeyDescriptor (btreePtr, nodeRec.buffer);	//�� it should check amount of memory allocated...
		M_ExitOnError (err);

		err = CheckKeyDescriptor (btreePtr->keyDescPtr, btreePtr->maxKeyLength);
		M_ExitOnError (err);

	}
	else
#endif
	{
		btreePtr->keyDescPtr = NULL;			// clear it so we don't dispose garbage later
	}

	err = ReleaseNode (btreePtr, &nodeRec);
	M_ExitOnError (err);


#if BSD
	/*
	 * Under Mac OS, b-tree nodes can be non-contiguous on disk when the
	 * allocation block size is smaller than the b-tree node size.
	 */
	if ( !NodesAreContiguous(filePtr, btreePtr->nodeSize) )
		return fsBTInvalidNodeErr;
#endif

	//////////////////////////////// Success ////////////////////////////////////

	//�� align LEOF to multiple of node size?	- just on close

//	LogEndTime(kTraceOpenBTree, noErr);

	return noErr;


	/////////////////////// Error - Clean up and Exit ///////////////////////////

ErrorExit:

	filePtr->fcbBtree = NULL;
	(void) ReleaseNode (btreePtr, &nodeRec);
	DisposeMemory( btreePtr );

//	LogEndTime(kTraceOpenBTree, err);

	return err;
}



/*-------------------------------------------------------------------------------
Routine:	BTClosePath	-	Flush BTree Header and Deallocate Memory for BTree.

Function:	Flush the BTreeControlBlock fields to header node, and delete BTree control
			block and key descriptor associated with the file if filePtr is last
			path of type kBTreeType ('btre').


Input:		filePtr		- pointer to file to delete BTree control block for.

Result:		noErr			- success
			fsBTInvalidFileErr	-
			!= noErr		- failure
-------------------------------------------------------------------------------*/

OSStatus	BTClosePath			(SFCB					*filePtr)
{
	OSStatus				err;
	BTreeControlBlockPtr	btreePtr;
#if 0
	FSPathControlBlockPtr	tempPath;
	Boolean					otherBTreePathsOpen;
#endif

//	LogStartTime(kTraceCloseBTree);

	btreePtr = (BTreeControlBlockPtr) filePtr->fcbBtree;

	if (btreePtr == NULL)
		return fsBTInvalidFileErr;

	////////////////////// Check for other BTree Paths //////////////////////////

#if 0
//�� Need replacement field for pathType 
	otherBTreePathsOpen = false;
	tempPath = forkPtr->fork.pathList.head;
	while ( (tempPath != (FSPathControlBlockPtr) &forkPtr->fork.pathList) &&
			(otherBTreePathsOpen == false) )
	{
		if ((tempPath != pathPtr) && (tempPath->path.pathType == kBTreeType))
		{
			otherBTreePathsOpen = true;
			break;							// done with loop check
		}

		tempPath = tempPath->next;
	}

	////////////////////////// Update Header Node ///////////////////////////////


	if (otherBTreePathsOpen == true)
	{
		err = UpdateHeader (btreePtr);			// update header even if we aren't closing
		return err;								// we only clean up after the last user...
	}
#endif

	btreePtr->attributes &= ~kBTBadCloseMask;		// clear "bad close" attribute bit
	err = UpdateHeader (btreePtr);
	M_ExitOnError (err);

#if SupportsKeyDescriptors
	if (btreePtr->keyDescPtr != NULL)			// deallocate keyDescriptor, if any
	{
		DisposeMemory( btreePtr->keyDescPtr );
	}
#endif

	DisposeMemory( btreePtr );
	filePtr->fcbBtree = NULL;

//	LogEndTime(kTraceCloseBTree, noErr);

	return	noErr;

	/////////////////////// Error - Clean Up and Exit ///////////////////////////

ErrorExit:

//	LogEndTime(kTraceCloseBTree, err);

	return	err;
}



/*-------------------------------------------------------------------------------
Routine:	BTSearchRecord	-	Search BTree for a record with a matching key.

Function:	Search for position in B*Tree indicated by searchKey. If a valid node hint
			is provided, it will be searched first, then SearchTree will be called.
			If a BTreeIterator is provided, it will be set to the position found as
			a result of the search. If a record exists at that position, and a BufferDescriptor
			is supplied, the record will be copied to the buffer (as much as will fit),
			and recordLen will be set to the length of the record.

			If an error other than fsBTRecordNotFoundErr occurs, the BTreeIterator, if any,
			is invalidated, and recordLen is set to 0.


Input:		pathPtr			- pointer to path for BTree file.
			searchKey		- pointer to search key to match.
			hintPtr			- pointer to hint (may be NULL)

Output:		record			- pointer to BufferDescriptor containing record
			recordLen		- length of data at recordPtr
			iterator		- pointer to BTreeIterator indicating position result of search

Result:		noErr			- success, record contains copy of record found
			fsBTRecordNotFoundErr	- record was not found, no data copied
			fsBTInvalidFileErr	- no BTreeControlBlock is allocated for the fork
			fsBTInvalidKeyLengthErr		-
			!= noErr		- failure
-------------------------------------------------------------------------------*/

OSStatus	BTSearchRecord		(SFCB						*filePtr,
								 BTreeIterator				*searchIterator,
								 UInt32						heuristicHint,
								 FSBufferDescriptor			*record,
								 UInt16						*recordLen,
								 BTreeIterator				*resultIterator )
{
	OSStatus				err;
	BTreeControlBlockPtr	btreePtr;
	TreePathTable			treePathTable;
	UInt32					nodeNum;
	BlockDescriptor			node;
	UInt16					index;
	BTreeKeyPtr				keyPtr;
	RecordPtr				recordPtr;
	UInt16					len;
	Boolean					foundRecord;
	Boolean					validHint;


//	LogStartTime(kTraceSearchBTree);

	if (filePtr == NULL)		return	paramErr;
	if (searchIterator == NULL)	return	paramErr;

	btreePtr = (BTreeControlBlockPtr) filePtr->fcbBtree;
	if (btreePtr == NULL)		return	fsBTInvalidFileErr;

#if SupportsKeyDescriptors
	if (btreePtr->keyCompareProc == NULL)		// CheckKey if we using Key Descriptor
	{
		err = CheckKey (&searchIterator->key, btreePtr->keyDescPtr, btreePtr->maxKeyLength);
		M_ExitOnError (err);
	}
#endif

	foundRecord = false;

	////////////////////////////// Take A Hint //////////////////////////////////

	err = IsItAHint (btreePtr, searchIterator, &validHint);
	M_ExitOnError (err);

	if (validHint)
	{
		nodeNum = searchIterator->hint.nodeNum;
		
		err = GetNode (btreePtr, nodeNum, &node);
		if( err == noErr )
		{
			if ( ((BTNodeDescriptor*) node.buffer)->kind		== kBTLeafNode &&
				 ((BTNodeDescriptor*) node.buffer)->numRecords	>  0 )
			{
				foundRecord = SearchNode (btreePtr, node.buffer, &searchIterator->key, &index);

				//�� if !foundRecord, we could still skip tree search if ( 0 < index < numRecords )
			}

			if (foundRecord == false)
			{
				err = ReleaseNode (btreePtr, &node);
				M_ExitOnError (err);
			}
			else
			{
				++btreePtr->numValidHints;
			}
		}
		
		if( foundRecord == false )
			(void) BTInvalidateHint( searchIterator );
	}

	////////////////////////////// Try the heuristicHint //////////////////////////////////

	if ( (foundRecord == false) && (heuristicHint != kInvalidMRUCacheKey) && (nodeNum != heuristicHint) )
	{
	//	LogStartTime(kHeuristicHint);
		nodeNum = heuristicHint;
		
		err = GetNode (btreePtr, nodeNum, &node);
		if( err == noErr )
		{
			if ( ((BTNodeDescriptor*) node.buffer)->kind		== kBTLeafNode &&
				 ((BTNodeDescriptor*) node.buffer)->numRecords	>  0 )
			{
				foundRecord = SearchNode (btreePtr, node.buffer, &searchIterator->key, &index);
			}

			if (foundRecord == false)
			{
				err = ReleaseNode (btreePtr, &node);
				M_ExitOnError (err);
			}
		}
	//	LogEndTime(kHeuristicHint, (foundRecord == false));
	}

	//////////////////////////// Search The Tree ////////////////////////////////

	if (foundRecord == false)
	{
		err = SearchTree ( btreePtr, &searchIterator->key, treePathTable, &nodeNum, &node, &index);
		switch (err)
		{
			case noErr:			foundRecord = true;				break;
			case fsBTRecordNotFoundErr:									break;
			default:				goto ErrorExit;
		}
	}


	//////////////////////////// Get the Record /////////////////////////////////

	if (foundRecord == true)
	{
		//�� Should check for errors! Or BlockMove could choke on recordPtr!!!
		GetRecordByIndex (btreePtr, node.buffer, index, &keyPtr, &recordPtr, &len);

		if (recordLen != NULL)	*recordLen = len;

		if (record != NULL)
		{
			ByteCount recordSize;

			recordSize = record->itemCount * record->itemSize;
			
			PanicIf(len > recordSize, "\pBTSearchRecord: truncating record!");

			if (len > recordSize)	len = recordSize;

			CopyMemory (recordPtr, record->bufferAddress, len);
		}
	}


	/////////////////////// Success - Update Iterator ///////////////////////////

	if (resultIterator != NULL)
	{
		resultIterator->hint.writeCount	= btreePtr->writeCount;
		resultIterator->hint.nodeNum	= nodeNum;
		resultIterator->hint.index		= index;
		resultIterator->hint.reserved1	= 0;
		resultIterator->hint.reserved2	= 0;

		resultIterator->version			= 0;
		resultIterator->reserved		= 0;

		// copy the key in the BTree when found rather than searchIterator->key to get proper case/diacriticals
		if (foundRecord == true)
			CopyKey(btreePtr, keyPtr, &resultIterator->key);
		else
			CopyKey(btreePtr, &searchIterator->key, &resultIterator->key);
	}

	err = ReleaseNode (btreePtr, &node);
	M_ExitOnError (err);

//	LogEndTime(kTraceSearchBTree, (foundRecord == false));

	if (foundRecord == false)	return	fsBTRecordNotFoundErr;
	else						return	noErr;


	/////////////////////// Error - Clean Up and Exit ///////////////////////////

ErrorExit:

	if (recordLen != NULL)
		*recordLen = 0;

	if (resultIterator != NULL)
	{
		resultIterator->hint.writeCount	= 0;
		resultIterator->hint.nodeNum	= 0;
		resultIterator->hint.index		= 0;
		resultIterator->hint.reserved1	= 0;
		resultIterator->hint.reserved2	= 0;

		resultIterator->version			= 0;
		resultIterator->reserved		= 0;
		resultIterator->key.length16	= 0;	// zero out two bytes to cover both types of keys
	}

	if ( err == fsBTEmptyErr )
		err = fsBTRecordNotFoundErr;

//	LogEndTime(kTraceSearchBTree, err);

	return err;
}



/*-------------------------------------------------------------------------------
Routine:	BTIterateRecord	-	Find the first, next, previous, or last record.

Function:	Find the first, next, previous, or last record in the BTree

Input:		pathPtr			- pointer to path iterate records for.
			operation		- iteration operation (first,next,prev,last)
			iterator		- pointer to iterator indicating start position

Output:		iterator		- iterator is updated to indicate new position
			newKeyPtr		- pointer to buffer to copy key found by iteration
			record			- pointer to buffer to copy record found by iteration
			recordLen		- length of record

Result:		noErr			- success
			!= noErr		- failure
-------------------------------------------------------------------------------*/

OSStatus	BTIterateRecord		(SFCB						*filePtr,
								 BTreeIterationOperation	 operation,
								 BTreeIterator				*iterator,
								 FSBufferDescriptor			*record,
								 UInt16						*recordLen )
{
	OSStatus					err;
	BTreeControlBlockPtr		btreePtr;
	BTreeKeyPtr					keyPtr;
	RecordPtr					recordPtr;
	UInt16						len;

	Boolean						foundRecord;
	UInt32						nodeNum;

	BlockDescriptor				left,		node,		right;
	UInt16						index;


//	LogStartTime(kTraceGetBTreeRecord);

	////////////////////////// Priliminary Checks ///////////////////////////////

	left.buffer		= NULL;
	right.buffer	= NULL;
	node.buffer		= NULL;


	if (filePtr == NULL)
	{
		return	paramErr;
	}

	btreePtr = (BTreeControlBlockPtr) filePtr->fcbBtree;
	if (btreePtr == NULL)
	{
		return	fsBTInvalidFileErr;			//�� handle properly
	}

	if ((operation != kBTreeFirstRecord)	&&
		(operation != kBTreeNextRecord)		&&
		(operation != kBTreeCurrentRecord)	&&
		(operation != kBTreePrevRecord)		&&
		(operation != kBTreeLastRecord))
	{
		err = fsInvalidIterationMovmentErr;
		goto ErrorExit;
	}

	/////////////////////// Find First or Last Record ///////////////////////////

	if ((operation == kBTreeFirstRecord) || (operation == kBTreeLastRecord))
	{
		if (operation == kBTreeFirstRecord)		nodeNum = btreePtr->firstLeafNode;
		else									nodeNum = btreePtr->lastLeafNode;

		if (nodeNum == 0)
		{
			err = fsBTEmptyErr;
			goto ErrorExit;
		}

		err = GetNode (btreePtr, nodeNum, &node);
		M_ExitOnError (err);

		if ( ((NodeDescPtr) node.buffer)->kind			!= kBTLeafNode ||
			 ((NodeDescPtr) node.buffer)->numRecords	<=  0 )
		{
			err = ReleaseNode (btreePtr, &node);
			M_ExitOnError (err);

			err = fsBTInvalidNodeErr;
			goto ErrorExit;
		}

		if (operation == kBTreeFirstRecord)		index = 0;
		else									index = ((BTNodeDescriptor*) node.buffer)->numRecords - 1;

		goto CopyData;						//�� is there a cleaner way?
	}


	//////////////////////// Find Iterator Position /////////////////////////////

	err = FindIteratorPosition (btreePtr, iterator,
								&left, &node, &right, &nodeNum, &index, &foundRecord);
	M_ExitOnError (err);


	///////////////////// Find Next Or Previous Record //////////////////////////

	if (operation == kBTreePrevRecord)
	{
		if (index > 0)
		{
			--index;
		}
		else
		{
			if (left.buffer == NULL)
			{
				nodeNum = ((NodeDescPtr) node.buffer)->bLink;
				if ( nodeNum > 0)
				{
					err = GetNode (btreePtr, nodeNum, &left);
					M_ExitOnError (err);
				} else {
					err = fsBTStartOfIterationErr;
					goto ErrorExit;
				}
			}
			//	Before we stomp on "right", we'd better release it if needed
			if (right.buffer != NULL) {
				err = ReleaseNode(btreePtr, &right);
				M_ExitOnError(err);
			}
			right		= node;
			node		= left;
			left.buffer	= NULL;
			index 		= ((NodeDescPtr) node.buffer)->numRecords -1;
		}
	}
	else if (operation == kBTreeNextRecord)
	{
		if ((foundRecord != true) &&
			(((NodeDescPtr) node.buffer)->fLink == 0) &&
			(index == ((NodeDescPtr) node.buffer)->numRecords))
		{
			err = fsBTEndOfIterationErr;
			goto ErrorExit;
		} 
	
		// we did not find the record but the index is already positioned correctly
		if ((foundRecord == false) && (index != ((NodeDescPtr) node.buffer)->numRecords)) 
			goto CopyData;

		// we found the record OR we have to look in the next node
		if (index < ((NodeDescPtr) node.buffer)->numRecords -1)
		{
			++index;
		}
		else
		{
			if (right.buffer == NULL)
			{
				nodeNum = ((NodeDescPtr) node.buffer)->fLink;
				if ( nodeNum > 0)
				{
					err = GetNode (btreePtr, nodeNum, &right);
					M_ExitOnError (err);
				} else {
					err = fsBTEndOfIterationErr;
					goto ErrorExit;
				}
			}
			//	Before we stomp on "left", we'd better release it if needed
			if (left.buffer != NULL) {
				err = ReleaseNode(btreePtr, &left);
				M_ExitOnError(err);
			}
			left		 = node;
			node		 = right;
			right.buffer = NULL;
			index		 = 0;
		}
	}
	else // operation == kBTreeCurrentRecord
	{
		// make sure we have something... <CS9>
		if ((foundRecord != true) &&
			(index >= ((NodeDescPtr) node.buffer)->numRecords))
		{
			err = fsBTEndOfIterationErr;
			goto ErrorExit;
		} 
	}

	//////////////////// Copy Record And Update Iterator ////////////////////////

CopyData:

	// added check for errors <CS9>
	err = GetRecordByIndex (btreePtr, node.buffer, index, &keyPtr, &recordPtr, &len);
	M_ExitOnError (err);

	if (recordLen != NULL)			*recordLen = len;

	if (record != NULL)
	{
		ByteCount recordSize;

		recordSize = record->itemCount * record->itemSize;

		PanicIf(len > recordSize, "\pBTIterateRecord: truncating record!");
	
		if (len > recordSize)	len = recordSize;

		CopyMemory (recordPtr, record->bufferAddress, len);
	}

	if (iterator != NULL)						// first & last do not require iterator
	{
		iterator->hint.writeCount	= btreePtr->writeCount;
		iterator->hint.nodeNum		= nodeNum;
		iterator->hint.index		= index;
		iterator->hint.reserved1	= 0;
		iterator->hint.reserved2	= 0;

		iterator->version			= 0;
		iterator->reserved			= 0;

		CopyKey(btreePtr, keyPtr, &iterator->key);
	}


	///////////////////////////// Release Nodes /////////////////////////////////

	err = ReleaseNode (btreePtr, &node);
	M_ExitOnError (err);

	if (left.buffer != NULL)
	{
		err = ReleaseNode (btreePtr, &left);
		M_ExitOnError (err);
	}

	if (right.buffer != NULL)
	{
		err = ReleaseNode (btreePtr, &right);
		M_ExitOnError (err);
	}

//	LogEndTime(kTraceGetBTreeRecord, noErr);

	return noErr;

	/////////////////////// Error - Clean Up and Exit ///////////////////////////

ErrorExit:

	(void)	ReleaseNode (btreePtr, &left);
	(void)	ReleaseNode (btreePtr, &node);
	(void)	ReleaseNode (btreePtr, &right);

	if (recordLen != NULL)
		*recordLen = 0;

	if (iterator != NULL)
	{
		iterator->hint.writeCount	= 0;
		iterator->hint.nodeNum		= 0;
		iterator->hint.index		= 0;
		iterator->hint.reserved1	= 0;
		iterator->hint.reserved2	= 0;

		iterator->version			= 0;
		iterator->reserved			= 0;
		iterator->key.length16		= 0;
	}

	if ( err == fsBTEmptyErr || err == fsBTEndOfIterationErr )
		err = fsBTRecordNotFoundErr;

//	LogEndTime(kTraceGetBTreeRecord, err);

	return err;
}


//////////////////////////////// BTInsertRecord /////////////////////////////////

OSStatus	BTInsertRecord		(SFCB						*filePtr,
								 BTreeIterator				*iterator,
								 FSBufferDescriptor			*record,
								 UInt16						 recordLen )
{
	OSStatus				err;
	BTreeControlBlockPtr	btreePtr;
	TreePathTable			treePathTable;
	SInt32					nodesNeeded;
	BlockDescriptor			nodeRec;
	UInt32					insertNodeNum;
	UInt16					index;
	Boolean					recordFit;


	////////////////////////// Priliminary Checks ///////////////////////////////

	nodeRec.buffer = NULL;					// so we can call ReleaseNode

	err = CheckInsertParams (filePtr, iterator, record, recordLen);
	if (err != noErr)
		return	err;

//	LogStartTime(kTraceInsertBTreeRecord);

	btreePtr = (BTreeControlBlockPtr) filePtr->fcbBtree;

	///////////////////////// Find Insert Position //////////////////////////////

	// always call SearchTree for Insert
	err = SearchTree (btreePtr, &iterator->key, treePathTable, &insertNodeNum, &nodeRec, &index);

	switch (err)				// set/replace/insert decision point
	{
		case noErr:			err = fsBTDuplicateRecordErr;
							goto ErrorExit;

		case fsBTRecordNotFoundErr:	break;

		case fsBTEmptyErr:	// if tree empty add 1st leaf node

			if (btreePtr->freeNodes == 0)
			{
				err = ExtendBTree (btreePtr, btreePtr->totalNodes + 1);
				M_ExitOnError (err);
			}

			err = AllocateNode (btreePtr, &insertNodeNum);
			M_ExitOnError (err);

			err = GetNewNode (btreePtr, insertNodeNum, &nodeRec);
			M_ExitOnError (err);

			((NodeDescPtr)nodeRec.buffer)->kind		= kBTLeafNode;
			((NodeDescPtr)nodeRec.buffer)->height	= 1;

			recordFit = InsertKeyRecord (btreePtr, nodeRec.buffer, 0,
										 &iterator->key, KeyLength(btreePtr, &iterator->key),
										 record->bufferAddress, recordLen );
			if (recordFit != true)
			{
				err = fsBTRecordTooLargeErr;
				goto ErrorExit;
			}

			err = UpdateNode (btreePtr, &nodeRec);
			M_ExitOnError (err);

			// update BTreeControlBlock
			btreePtr->treeDepth	 		= 1;
			btreePtr->rootNode	 		= insertNodeNum;
			btreePtr->firstLeafNode		= insertNodeNum;
			btreePtr->lastLeafNode		= insertNodeNum;
			M_BTreeHeaderDirty (btreePtr);

			goto Success;

		default:				
			goto ErrorExit;
	}

	if (index > 0) 
	{
		recordFit = InsertKeyRecord (btreePtr, nodeRec.buffer, index,
										&iterator->key, KeyLength(btreePtr, &iterator->key),
										record->bufferAddress, recordLen);
		if (recordFit == true)
		{
			err = UpdateNode (btreePtr, &nodeRec);
			M_ExitOnError (err);

			goto Success;
		}
	}

	/////////////////////// Extend File If Necessary ////////////////////////////

	nodesNeeded =  btreePtr->treeDepth + 1 - btreePtr->freeNodes;	//�� math limit
	if (nodesNeeded > 0)
	{
		nodesNeeded += btreePtr->totalNodes;
		if (nodesNeeded > CalcMapBits (btreePtr))	// we'll need to add a map node too!
			++nodesNeeded;

		err = ExtendBTree (btreePtr, nodesNeeded);
		M_ExitOnError (err);
	}

	// no need to delete existing record

	err = InsertTree (btreePtr, treePathTable, &iterator->key, record->bufferAddress,
					  recordLen, &nodeRec, index, 1, kInsertRecord, &insertNodeNum);
	M_ExitOnError (err);


	//////////////////////////////// Success ////////////////////////////////////

Success:
	++btreePtr->writeCount;				//	<CS10>
	++btreePtr->leafRecords;
	M_BTreeHeaderDirty (btreePtr);

	// create hint
	iterator->hint.writeCount 	= btreePtr->writeCount;		//	unused until <CS10>
	iterator->hint.nodeNum		= insertNodeNum;
	iterator->hint.index		= 0;						// unused
	iterator->hint.reserved1	= 0;
	iterator->hint.reserved2	= 0;

//	LogEndTime(kTraceInsertBTreeRecord, noErr);

	return noErr;


	////////////////////////////// Error Exit ///////////////////////////////////

ErrorExit:
	(void) ReleaseNode (btreePtr, &nodeRec);

	iterator->hint.writeCount 	= 0;
	iterator->hint.nodeNum		= 0;
	iterator->hint.index		= 0;
	iterator->hint.reserved1	= 0;
	iterator->hint.reserved2	= 0;
	
	if (err == fsBTEmptyErr)
		err = fsBTRecordNotFoundErr;

//	LogEndTime(kTraceInsertBTreeRecord, err);

	return err;
}



////////////////////////////////// BTSetRecord //////////////////////////////////
#if 0
OSStatus	BTSetRecord			(SFCB						*filePtr,
								 BTreeIterator				*iterator,
								 FSBufferDescriptor			*record,
								 UInt16						 recordLen )
{
	OSStatus				err;
	BTreeControlBlockPtr	btreePtr;
	TreePathTable			treePathTable;
	SInt32					nodesNeeded;
	BlockDescriptor			nodeRec;
	UInt32					insertNodeNum;
	UInt16					index;
	Boolean					recordFound = false;
	Boolean					recordFit;
	Boolean					operation;
	Boolean					validHint;


	////////////////////////// Priliminary Checks ///////////////////////////////

	nodeRec.buffer = NULL;					// so we can call ReleaseNode

	err = CheckInsertParams (filePtr, iterator, record, recordLen);
	if (err != noErr)
		return	err;

	btreePtr = (BTreeControlBlockPtr) filePtr->fcbBtree;


	///////////////////////// Find Insert Position //////////////////////////////

	err = IsItAHint (btreePtr, iterator, &validHint);
	M_ExitOnError (err);

	if (validHint)
	{
		insertNodeNum = iterator->hint.nodeNum;

		err = GetNode (btreePtr, insertNodeNum, &nodeRec);
		if( err == noErr )
		{
			err = TrySimpleReplace (btreePtr, nodeRec.buffer, iterator, record, recordLen, &recordFit);
			M_ExitOnError (err);

			if (recordFit)
			{
				err = UpdateNode (btreePtr, &nodeRec);
				M_ExitOnError (err);
				
				recordFound = true;
				++btreePtr->numValidHints;
				goto Success;
			} 											// else
			else
			{
				(void) BTInvalidateHint( iterator );
			}
			
			err = ReleaseNode (btreePtr, &nodeRec);
			M_ExitOnError (err);
		}
	}

	err = SearchTree (btreePtr, &iterator->key, treePathTable, &insertNodeNum, &nodeRec, &index);

	switch (err)				// set/replace/insert decision point
	{
		case noErr:			recordFound = true;
								break;

		case fsBTRecordNotFoundErr:	break;

		case fsBTEmptyErr:	// if tree empty add 1st leaf node

								if (btreePtr->freeNodes == 0)
								{
									err = ExtendBTree (btreePtr, btreePtr->totalNodes + 1);
									M_ExitOnError (err);
								}

								err = AllocateNode (btreePtr, &insertNodeNum);
								M_ExitOnError (err);

								err = GetNewNode (btreePtr, insertNodeNum, &nodeRec);
								M_ExitOnError (err);

								((NodeDescPtr)nodeRec.buffer)->kind		= kBTLeafNode;
								((NodeDescPtr)nodeRec.buffer)->height	= 1;

								recordFit = InsertKeyRecord (btreePtr, nodeRec.buffer, 0,
															 &iterator->key, KeyLength(btreePtr, &iterator->key),
															 record->bufferAddress, recordLen );
								if (recordFit != true)
								{
									err = fsBTRecordTooLargeErr;
									goto ErrorExit;
								}

								err = UpdateNode (btreePtr, &nodeRec);
								M_ExitOnError (err);

								// update BTreeControlBlock
								btreePtr->rootNode	 = insertNodeNum;
								btreePtr->treeDepth	 = 1;
								btreePtr->flags		|= kBTHeaderDirty;

								goto Success;

		default:				goto ErrorExit;
	}


	if (recordFound == true)		// Simple Replace - optimization avoids unecessary ExtendBTree
	{
		err = TrySimpleReplace (btreePtr, nodeRec.buffer, iterator, record, recordLen, &recordFit);
		M_ExitOnError (err);

		if (recordFit)
		{
			err = UpdateNode (btreePtr, &nodeRec);
			M_ExitOnError (err);

			goto Success;
		}
	}


	/////////////////////// Extend File If Necessary ////////////////////////////

	nodesNeeded =  btreePtr->treeDepth + 1 - btreePtr->freeNodes;	//�� math limit
	if (nodesNeeded > 0)
	{
		nodesNeeded += btreePtr->totalNodes;
		if (nodesNeeded > CalcMapBits (btreePtr))	// we'll need to add a map node too!
			++nodesNeeded;

		err = ExtendBTree (btreePtr, nodesNeeded);
		M_ExitOnError (err);
	}


	if (recordFound == true)							// Delete existing record
	{
		DeleteRecord (btreePtr, nodeRec.buffer, index);
		operation = kReplaceRecord;
	} else {
		operation = kInsertRecord;
	}

	err = InsertTree (btreePtr, treePathTable, &iterator->key, record->bufferAddress,
					  recordLen, &nodeRec, index, 1, operation, &insertNodeNum);
	M_ExitOnError (err);

	++btreePtr->writeCount;				//	<CS10> writeCount changes only if the tree structure changed

Success:
	if (recordFound == false)
	{
		++btreePtr->leafRecords;
		M_BTreeHeaderDirty (btreePtr);
	}

	// create hint
	iterator->hint.writeCount 	= btreePtr->writeCount;		//	unused until <CS10>
	iterator->hint.nodeNum		= insertNodeNum;
	iterator->hint.index		= 0;						// unused
	iterator->hint.reserved1	= 0;
	iterator->hint.reserved2	= 0;

	return noErr;


	////////////////////////////// Error Exit ///////////////////////////////////

ErrorExit:

	(void) ReleaseNode (btreePtr, &nodeRec);

	iterator->hint.writeCount 	= 0;
	iterator->hint.nodeNum		= 0;
	iterator->hint.index		= 0;
	iterator->hint.reserved1	= 0;
	iterator->hint.reserved2	= 0;

	return err;
}
#endif


//////////////////////////////// BTReplaceRecord ////////////////////////////////

OSStatus	BTReplaceRecord		(SFCB						*filePtr,
								 BTreeIterator				*iterator,
								 FSBufferDescriptor			*record,
								 UInt16						 recordLen )
{
	OSStatus				err;
	BTreeControlBlockPtr	btreePtr;
	TreePathTable			treePathTable;
	SInt32					nodesNeeded;
	BlockDescriptor			nodeRec;
	UInt32					insertNodeNum;
	UInt16					index;
	Boolean					recordFit;
	Boolean					validHint;


	////////////////////////// Priliminary Checks ///////////////////////////////

	nodeRec.buffer = NULL;					// so we can call ReleaseNode

	err = CheckInsertParams (filePtr, iterator, record, recordLen);
	if (err != noErr)
		return err;

//	LogStartTime(kTraceReplaceBTreeRecord);

	btreePtr = (BTreeControlBlockPtr) filePtr->fcbBtree;

	////////////////////////////// Take A Hint //////////////////////////////////

	err = IsItAHint (btreePtr, iterator, &validHint);
	M_ExitOnError (err);

	if (validHint)
	{
		insertNodeNum = iterator->hint.nodeNum;

		err = GetNode (btreePtr, insertNodeNum, &nodeRec);
		if( err == noErr )
		{
			err = TrySimpleReplace (btreePtr, nodeRec.buffer, iterator, record, recordLen, &recordFit);
			M_ExitOnError (err);

			if (recordFit)
			{
				err = UpdateNode (btreePtr, &nodeRec);
				M_ExitOnError (err);

				++btreePtr->numValidHints;

				goto Success;
			}
			else
			{
				(void) BTInvalidateHint( iterator );
			}
			
			err = ReleaseNode (btreePtr, &nodeRec);
			M_ExitOnError (err);
		}
		else
		{
			(void) BTInvalidateHint( iterator );
		}
	}


	////////////////////////////// Get A Clue ///////////////////////////////////

	err = SearchTree (btreePtr, &iterator->key, treePathTable, &insertNodeNum, &nodeRec, &index);
	M_ExitOnError (err);					// record must exit for Replace

	// optimization - if simple replace will work then don't extend btree
	// �� if we tried this before, and failed because it wouldn't fit then we shouldn't try this again...

	err = TrySimpleReplace (btreePtr, nodeRec.buffer, iterator, record, recordLen, &recordFit);
	M_ExitOnError (err);

	if (recordFit)
	{
		err = UpdateNode (btreePtr, &nodeRec);
		M_ExitOnError (err);

		goto Success;
	}


	//////////////////////////// Make Some Room /////////////////////////////////

	nodesNeeded =  btreePtr->treeDepth + 1 - btreePtr->freeNodes;	//�� math limit
	if (nodesNeeded > 0)
	{
		nodesNeeded += btreePtr->totalNodes;
		if (nodesNeeded > CalcMapBits (btreePtr))	// we'll need to add a map node too!
			++nodesNeeded;

		err = ExtendBTree (btreePtr, nodesNeeded);
		M_ExitOnError (err);
	}


	DeleteRecord (btreePtr, nodeRec.buffer, index);	// delete existing key/record

	err = InsertTree (btreePtr, treePathTable, &iterator->key, record->bufferAddress,
					  recordLen, &nodeRec, index, 1, kReplaceRecord, &insertNodeNum);
	M_ExitOnError (err);

	++btreePtr->writeCount;				//	<CS10> writeCount changes only if the tree structure changed

Success:
	// create hint
	iterator->hint.writeCount 	= btreePtr->writeCount;		//	unused until <CS10>
	iterator->hint.nodeNum		= insertNodeNum;
	iterator->hint.index		= 0;						// unused
	iterator->hint.reserved1	= 0;
	iterator->hint.reserved2	= 0;

//	LogEndTime(kTraceReplaceBTreeRecord, noErr);

	return noErr;


	////////////////////////////// Error Exit ///////////////////////////////////

ErrorExit:

	(void) ReleaseNode (btreePtr, &nodeRec);

	iterator->hint.writeCount 	= 0;
	iterator->hint.nodeNum		= 0;
	iterator->hint.index		= 0;
	iterator->hint.reserved1	= 0;
	iterator->hint.reserved2	= 0;

//	LogEndTime(kTraceReplaceBTreeRecord, err);

	return err;
}



//////////////////////////////// BTDeleteRecord /////////////////////////////////

OSStatus	BTDeleteRecord		(SFCB						*filePtr,
								 BTreeIterator				*iterator )
{
	OSStatus				err;
	BTreeControlBlockPtr	btreePtr;
	TreePathTable			treePathTable;
	BlockDescriptor			nodeRec;
	UInt32					nodeNum;
	UInt16					index;

//	LogStartTime(kTraceDeleteBTreeRecord);

	////////////////////////// Priliminary Checks ///////////////////////////////

	nodeRec.buffer = NULL;					// so we can call ReleaseNode

	M_ReturnErrorIf (filePtr == NULL, 	paramErr);
	M_ReturnErrorIf (iterator == NULL,	paramErr);

	btreePtr = (BTreeControlBlockPtr) filePtr->fcbBtree;
	if (btreePtr == NULL)
	{
		err = fsBTInvalidFileErr;
		goto ErrorExit;
	}

#if SupportsKeyDescriptors
	if (btreePtr->keyDescPtr != NULL)
	{
		err = CheckKey (&iterator->key, btreePtr->keyDescPtr, btreePtr->maxKeyLength);
		M_ExitOnError (err);
	}
#endif

	/////////////////////////////// Find Key ////////////////////////////////////

	//�� check hint for simple delete case (index > 0, numRecords > 2)

	err = SearchTree (btreePtr, &iterator->key, treePathTable, &nodeNum, &nodeRec, &index);
	M_ExitOnError (err);					// record must exit for Delete


	///////////////////////////// Delete Record /////////////////////////////////

	err = DeleteTree (btreePtr, treePathTable, &nodeRec, index, 1);
	M_ExitOnError (err);

//Success:
	++btreePtr->writeCount;				//	<CS10>
	--btreePtr->leafRecords;
	M_BTreeHeaderDirty (btreePtr);

	iterator->hint.nodeNum	= 0;

//	LogEndTime(kTraceDeleteBTreeRecord, noErr);

	return noErr;

	////////////////////////////// Error Exit ///////////////////////////////////

ErrorExit:
	(void) ReleaseNode (btreePtr, &nodeRec);

//	LogEndTime(kTraceDeleteBTreeRecord, err);

	return	err;
}



OSStatus	BTGetInformation	(SFCB					*filePtr,
								 UInt16					 version,
								 BTreeInfoRec			*info )
{
#if !LINUX
#pragma unused (version)
#endif

	BTreeControlBlockPtr	btreePtr;


	M_ReturnErrorIf (filePtr == NULL, 	paramErr);

	btreePtr = (BTreeControlBlockPtr) filePtr->fcbBtree;

	M_ReturnErrorIf (btreePtr == NULL,	fsBTInvalidFileErr);
	M_ReturnErrorIf (info == NULL,		paramErr);

	//�� check version?

	info->nodeSize		= btreePtr->nodeSize;
	info->maxKeyLength	= btreePtr->maxKeyLength;
	info->treeDepth		= btreePtr->treeDepth;
	info->numRecords	= btreePtr->leafRecords;
	info->numNodes		= btreePtr->totalNodes;
	info->numFreeNodes	= btreePtr->freeNodes;
	info->keyDescriptor	= btreePtr->keyDescPtr;	//�� this won't do at all...
	info->reserved		= 0;

	if (btreePtr->keyDescPtr == NULL)
		info->keyDescLength	= 0;
	else
		info->keyDescLength	= (UInt32) btreePtr->keyDescPtr->length;

	return noErr;
}



/*-------------------------------------------------------------------------------
Routine:	BTFlushPath	-	Flush BTreeControlBlock to Header Node.

Function:	Brief_description_of_the_function_and_any_side_effects


Input:		pathPtr		- pointer to path control block for B*Tree file to flush

Output:		none

Result:		noErr		- success
			!= noErr	- failure
-------------------------------------------------------------------------------*/

OSStatus	BTFlushPath				(SFCB					*filePtr)
{
	OSStatus				err;
	BTreeControlBlockPtr	btreePtr;


//	LogStartTime(kTraceFlushBTree);

	M_ReturnErrorIf (filePtr == NULL, 	paramErr);

	btreePtr = (BTreeControlBlockPtr) filePtr->fcbBtree;

	M_ReturnErrorIf (btreePtr == NULL,	fsBTInvalidFileErr);

	err = UpdateHeader (btreePtr);

//	LogEndTime(kTraceFlushBTree, err);

	return	err;
}



/*-------------------------------------------------------------------------------
Routine:	BTInvalidateHint	-	Invalidates the hint within a BTreeInterator.

Function:	Invalidates the hint within a BTreeInterator.


Input:		iterator	- pointer to BTreeIterator

Output:		iterator	- iterator with the hint.nodeNum cleared

Result:		noErr			- success
			paramErr	- iterator == NULL
-------------------------------------------------------------------------------*/


OSStatus	BTInvalidateHint	(BTreeIterator				*iterator )
{
	if (iterator == NULL)
		return	paramErr;

	iterator->hint.nodeNum = 0;

	return	noErr;
}