File: SRepair.c

package info (click to toggle)
hfsprogs 332.25-11
  • links: PTS
  • area: main
  • in suites: buster, jessie, jessie-kfreebsd, sid, stretch
  • size: 6,440 kB
  • ctags: 7,805
  • sloc: ansic: 58,120; makefile: 25
file content (5216 lines) | stat: -rw-r--r-- 166,066 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
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
/*
 * Copyright (c) 1999-2006 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:		SRepair.c

	Contains:	This file contains the Scavenger repair routines.
	
	Written by:	Bill Bruffey

	Copyright:	� 1986, 1990, 1992-1999 by Apple Computer, Inc., all rights reserved.

*/

#include "Scavenger.h"
#include <unistd.h>
#include <sys/stat.h>
#include <stdlib.h>
#include "../cache.h"

enum {
	clearBlocks,
	addBitmapBit,
	deleteExtents
};

/* internal routine prototypes */

static 	int MRepair( SGlobPtr GPtr );
void	SetOffset (void *buffer, UInt16 btNodeSize, SInt16 recOffset, SInt16 vecOffset);
#define SetOffset(buffer,nodesize,offset,record)		(*(SInt16 *) ((Byte *) (buffer) + (nodesize) + (-2 * (record))) = (offset))
static	OSErr	UpdateBTreeHeader( SFCB * fcbPtr );
static	OSErr	FixBTreeHeaderReservedFields( SGlobPtr GPtr, short refNum );
static	OSErr	UpdBTM( SGlobPtr GPtr, short refNum);
static	OSErr	UpdateVolumeBitMap( SGlobPtr GPtr, Boolean preAllocateOverlappedExtents );
static	OSErr	DoMinorOrders( SGlobPtr GPtr );
static	OSErr	UpdVal( SGlobPtr GPtr, RepairOrderPtr rP );
static	int		DelFThd( SGlobPtr GPtr, UInt32 fid );
static	OSErr	FixDirThread( SGlobPtr GPtr, UInt32 did );
static	OSErr	FixOrphanedFiles ( SGlobPtr GPtr );
static	OSErr	RepairReservedBTreeFields ( SGlobPtr GPtr );
static 	OSErr   GetCatalogRecord(SGlobPtr GPtr, UInt32 fileID, Boolean isHFSPlus, CatalogKey *catKey, CatalogRecord *catRecord, UInt16 *recordSize); 
static 	OSErr   RepairAttributesCheckABT(SGlobPtr GPtr, Boolean isHFSPlus);
static 	OSErr   RepairAttributesCheckCBT(SGlobPtr GPtr, Boolean isHFSPlus);
static	OSErr	RepairAttributes( SGlobPtr GPtr );
static	OSErr	FixFinderFlags( SGlobPtr GPtr, RepairOrderPtr p );
static	OSErr	FixLinkCount( SGlobPtr GPtr, RepairOrderPtr p );
static	OSErr	FixBSDInfo( SGlobPtr GPtr, RepairOrderPtr p );
static	OSErr	DeleteUnlinkedFile( SGlobPtr GPtr, RepairOrderPtr p );
static	OSErr	FixOrphanedExtent( SGlobPtr GPtr );
static 	OSErr	FixFileSize(SGlobPtr GPtr, RepairOrderPtr p);
static  OSErr 	VolumeObjectFixVHBorMDB( Boolean * fixedIt );
static 	OSErr 	VolumeObjectRestoreWrapper( void );
static	OSErr	FixBloatedThreadRecords( SGlob *GPtr );
static	OSErr	FixMissingThreadRecords( SGlob *GPtr );
static	OSErr	FixEmbededVolDescription( SGlobPtr GPtr, RepairOrderPtr p );
static	OSErr	FixWrapperExtents( SGlobPtr GPtr, RepairOrderPtr p );
static  OSErr	FixIllegalNames( SGlobPtr GPtr, RepairOrderPtr roPtr );
static HFSCatalogNodeID GetObjectID( CatalogRecord * theRecPtr );
static 	OSErr	FixMissingDirectory( SGlob *GPtr, UInt32 theObjID, UInt32 theParID );
static 	OSErr 	FixAttrSize(SGlobPtr GPtr, RepairOrderPtr p);
static 	OSErr 	FixOrphanAttrRecord(SGlobPtr GPtr);
static 	OSErr 	FixBadExtent(SGlobPtr GPtr, RepairOrderPtr p);

/* Functions to fix overlapping extents */
static	OSErr	FixOverlappingExtents(SGlobPtr GPtr);
static 	int 	CompareExtentBlockCount(const void *first, const void *second);
static 	OSErr 	MoveExtent(SGlobPtr GPtr, ExtentInfo *extentInfo);
static 	OSErr 	CreateCorruptFileSymlink(SGlobPtr GPtr, UInt32 fileID);
static 	OSErr 	SearchExtentInAttributeBT(SGlobPtr GPtr, ExtentInfo *extentInfo, HFSPlusAttrKey *attrKey, HFSPlusAttrRecord *attrRecord, UInt16 *recordSize, UInt32 *foundExtentIndex);
static 	OSErr 	UpdateExtentInAttributeBT (SGlobPtr GPtr, ExtentInfo *extentInfo, HFSPlusAttrKey *attrKey, HFSPlusAttrRecord *attrRecord, UInt16 *recordSize, UInt32 foundInExtentIndex);
static 	OSErr 	SearchExtentInVH(SGlobPtr GPtr, ExtentInfo *extentInfo, UInt32 *foundExtentIndex, Boolean *noMoreExtents);
static 	OSErr 	UpdateExtentInVH (SGlobPtr GPtr, ExtentInfo *extentInfo, UInt32 foundExtentIndex);
static 	OSErr 	SearchExtentInCatalogBT(SGlobPtr GPtr, ExtentInfo *extentInfo, CatalogKey *catKey, CatalogRecord *catRecord, UInt16 *recordSize, UInt32 *foundExtentIndex, Boolean *noMoreExtents);
static 	OSErr 	UpdateExtentInCatalogBT (SGlobPtr GPtr, ExtentInfo *extentInfo, CatalogKey *catKey, CatalogRecord *catRecord, UInt16 *recordSize, UInt32 foundExtentIndex);
static 	OSErr 	SearchExtentInExtentBT(SGlobPtr GPtr, ExtentInfo *extentInfo, HFSPlusExtentKey *extentKey, HFSPlusExtentRecord *extentRecord, UInt16 *recordSize, UInt32 *foundExtentIndex);
static 	OSErr 	FindExtentInExtentRec (Boolean isHFSPlus, UInt32 startBlock, UInt32 blockCount, const HFSPlusExtentRecord extentData, UInt32 *foundExtentIndex, Boolean *noMoreExtents);

/* Functions to copy disk blocks or data buffer to disk */
static 	OSErr 	CopyDiskBlocks(SGlobPtr GPtr, const UInt32 startAllocationBlock, const UInt32 blockCount, const UInt32 newStartAllocationBlock );
static 	OSErr 	WriteDiskBlocks(SGlobPtr GPtr, UInt32 startBlock, UInt32 blockCount, u_char *buffer, int buflen);

/* Functions to create file and directory by name */
static 	OSErr 	CreateFileByName(SGlobPtr GPtr, UInt32 parentID, UInt16 fileType, u_char *fileName, unsigned int filenameLen, u_char *data, unsigned int dataLen);
static 	UInt32 	CreateDirByName(SGlob *GPtr , const u_char *dirName, const UInt32 parentID);

static 	int		BuildFolderRec( u_int16_t theMode, UInt32 theObjID, Boolean isHFSPlus, CatalogRecord * theRecPtr );
static 	int		BuildThreadRec( CatalogKey * theKeyPtr, CatalogRecord * theRecPtr, Boolean isHFSPlus, Boolean isDirectory );
static 	int 	BuildFileRec(UInt16 fileType, UInt16 fileMode, UInt32 fileID, Boolean isHFSPlus, CatalogRecord *catRecord);
static 	void 	BuildAttributeKey(u_int32_t fileID, u_int32_t startBlock, unsigned char *attrName, u_int16_t attrNameLen, HFSPlusAttrKey *key);


OSErr	RepairVolume( SGlobPtr GPtr )
{
	OSErr			err;
	
	SetDFAStage( kAboutToRepairStage );											//	Notify callers repair is starting...
 	err = CheckForStop( GPtr ); ReturnIfError( err );							//	Permit the user to interrupt
	
	//
	//	Do the repair
	//
	SetDFAStage( kRepairStage );									//	Stops GNE from being called, and changes behavior of MountCheck

	err = MRepair( GPtr );
	
	return( err );
}


/*------------------------------------------------------------------------------
Routine:	MRepair		- (Minor Repair)
Function:	Performs minor repair operations.
Input:		GPtr		-	pointer to scavenger global area
Output:		MRepair		-	function result:			
------------------------------------------------------------------------------*/

static int MRepair( SGlobPtr GPtr )
{
	OSErr			err;
	SVCB			*calculatedVCB	= GPtr->calculatedVCB;
	Boolean			isHFSPlus;

	isHFSPlus = VolumeObjectIsHFSPlus( );

	if ( GPtr->CBTStat & S_RebuildBTree )
	{
		/* we currently only support rebuilding the catalog B-Tree file.  */
		/* once we do the rebuild we will force another verify since the */
		/* first verify was aborted when we determined a rebuild was necessary */
		err = RebuildCatalogBTree( GPtr );
		return( err );
	}
 
	//  Handle repair orders.  Note that these must be done *BEFORE* the MDB is updated.
	err = DoMinorOrders( GPtr );
	ReturnIfError( err );
  	err = CheckForStop( GPtr ); ReturnIfError( err );

	/* Clear Catalog status for things repaired by DoMinorOrders */
	GPtr->CatStat &= ~(S_FileAllocation | S_Permissions | S_UnlinkedFile | S_LinkCount | S_IllName | S_BadExtent);

	/*
	 * Fix missing thread records
	 */
	if (GPtr->CatStat & S_MissingThread) {
		err = FixMissingThreadRecords(GPtr);
		ReturnIfError(err);
		
		GPtr->CatStat &= ~S_MissingThread;
		GPtr->CBTStat |= S_BTH;  /* leaf record count changed */
	}

	//	2210409, in System 8.1, moving file or folder would cause HFS+ thread records to be
	//	520 bytes in size.  We only shrink the threads if other repairs are needed.
	if ( GPtr->VeryMinorErrorsStat & S_BloatedThreadRecordFound )
	{
		(void) FixBloatedThreadRecords( GPtr );
		GPtr->VeryMinorErrorsStat &= ~S_BloatedThreadRecordFound;
	}

	//
	//	we will update the following data structures regardless of whether we have done
	//	major or minor repairs, so we might end up doing this multiple times. Look into this.
	//
	
	//
	//	Isolate and fix Overlapping Extents
	//
 	err = CheckForStop( GPtr ); ReturnIfError( err );				//	Permit the user to interrupt

	if ( (GPtr->VIStat & S_OverlappingExtents) != 0 )
	{
		err = FixOverlappingExtents( GPtr );						//	Isolate and fix Overlapping Extents
		ReturnIfError( err );
		
		GPtr->VIStat &= ~S_OverlappingExtents;
		GPtr->VIStat |= S_VBM;										//	Now that we changed the extents, we need to rebuild the bitmap
		InvalidateCalculatedVolumeBitMap( GPtr );					//	Invalidate our BitMap
	}
	
	//
	//	FixOrphanedFiles
	//
 	err = CheckForStop( GPtr ); ReturnIfError( err );				//	Permit the user to interrupt
				
	if ( (GPtr->CBTStat & S_Orphan) != 0 )
	{
		err = FixOrphanedFiles ( GPtr );							//	Orphaned file were found
		ReturnIfError( err );
		GPtr->CBTStat |= S_BTH;  									// leaf record count may change - 2913311
	}

	//
	//	FixOrphanedExtent records
	//
	if ( (GPtr->EBTStat & S_OrphanedExtent) != 0 )					//	Orphaned extents were found
	{
		err = FixOrphanedExtent( GPtr );
		GPtr->EBTStat &= ~S_OrphanedExtent;
	//	if ( err == errRebuildBtree )
	//		goto RebuildBtrees;
		ReturnIfError( err );
	}

 	err = CheckForStop( GPtr ); ReturnIfError( err );				//	Permit the user to interrupt

	//
	//	Update the extent BTree header and bit map
	//
 	err = CheckForStop( GPtr ); ReturnIfError( err );				//	Permit the user to interrupt

	if ( (GPtr->EBTStat & S_BTH) || (GPtr->EBTStat & S_ReservedBTH) )
	{
		err = UpdateBTreeHeader( GPtr->calculatedExtentsFCB );	//	update extent file BTH

		if ( (err == noErr) && (GPtr->EBTStat & S_ReservedBTH) )
		{
			err = FixBTreeHeaderReservedFields( GPtr, kCalculatedExtentRefNum );
		}

		ReturnIfError( err );
	}


	if ( (GPtr->EBTStat & S_BTM) != 0 )
	{
		err = UpdBTM( GPtr, kCalculatedExtentRefNum );				//	update extent file BTM
		ReturnIfError( err );
	}
	
	//
	//	Update the catalog BTree header and bit map
	//

 	err = CheckForStop( GPtr ); ReturnIfError( err );				//	Permit the user to interrupt

	if ( (GPtr->CBTStat & S_BTH) || (GPtr->CBTStat & S_ReservedBTH) )
	{
		err = UpdateBTreeHeader( GPtr->calculatedCatalogFCB );	//	update catalog BTH

		if ( (err == noErr) && (GPtr->CBTStat & S_ReservedBTH) )
		{
			err = FixBTreeHeaderReservedFields( GPtr, kCalculatedCatalogRefNum );
		}

		ReturnIfError( err );
	}

	if ( GPtr->CBTStat & S_BTM )
	{
		err = UpdBTM( GPtr, kCalculatedCatalogRefNum );				//	update catalog BTM
		ReturnIfError( err );
	}

	if ( (GPtr->CBTStat & S_ReservedNotZero) != 0 )
	{
		err = RepairReservedBTreeFields( GPtr );					//	update catalog fields
		ReturnIfError( err );
	}

	// Repair orphaned/invalid attribute records 
	if (  (GPtr->ABTStat & S_AttrRec) ) 
	{
		err = FixOrphanAttrRecord( GPtr );
		ReturnIfError( err );
	}

	// Repair inconsistency of attribute btree and corresponding bits in
	// catalog btree 
	if ( (GPtr->ABTStat & S_AttributeCount) || 
	     (GPtr->ABTStat & S_SecurityCount)) 
	{
		err = RepairAttributes( GPtr );
		ReturnIfError( err );
	}
	
	// Update the attribute BTree header and bit map 
	if ( (GPtr->ABTStat & S_BTH) )
	{
		err = UpdateBTreeHeader( GPtr->calculatedAttributesFCB );	//	update attribute BTH
		ReturnIfError( err );
	}

	if ( GPtr->ABTStat & S_BTM )
	{
		err = UpdBTM( GPtr, kCalculatedAttributesRefNum );		//	update attribute BTM
		ReturnIfError( err );
	}

	//
	//	Update the volume bit map
	//
	// Note, moved volume bit map update to end after other repairs
	// (except the MDB / VolumeHeader) have been completed
	//
 	err = CheckForStop( GPtr ); ReturnIfError( err );				//	Permit the user to interrupt

	if ( (GPtr->VIStat & S_VBM) != 0 )
	{
		err = UpdateVolumeBitMap( GPtr, false );					//	update VolumeBitMap
		ReturnIfError( err );
		InvalidateCalculatedVolumeBitMap( GPtr );					//	Invalidate our BitMap
	}

	//
	//	Fix missing Primary or Alternate VHB or MDB
	//

 	err = CheckForStop( GPtr ); ReturnIfError( err );				//	Permit the user to interrupt
				
	if ( (GPtr->VIStat & S_MDB) != 0 )		//	fix MDB / VolumeHeader
	{
		Boolean		fixedIt = false;
		err = VolumeObjectFixVHBorMDB( &fixedIt );
		ReturnIfError( err );
		// don't call FlushAlternateVolumeControlBlock if we fixed it since that would 
		// mean our calculated VCB has not been completely set up.
		if ( fixedIt ) {
			GPtr->VIStat &= ~S_MDB; 
			MarkVCBClean( calculatedVCB );
		}
	}

 	err = CheckForStop( GPtr ); ReturnIfError( err );				//	Permit the user to interrupt
				
	if ( (GPtr->VIStat & S_WMDB) != 0  )		//	fix wrapper MDB
	{
		err = VolumeObjectRestoreWrapper();
		ReturnIfError( err );
	}

	//
	//	Update the MDB / VolumeHeader
	//
	// Note, moved MDB / VolumeHeader update to end 
	// after all other repairs have been completed.
	//

 	err = CheckForStop( GPtr ); ReturnIfError( err );				//	Permit the user to interrupt
				
	if ( (GPtr->VIStat & S_MDB) != 0 || IsVCBDirty(calculatedVCB) ) //	update MDB / VolumeHeader
	{
		MarkVCBDirty(calculatedVCB);								// make sure its dirty
		calculatedVCB->vcbAttributes |= kHFSVolumeUnmountedMask;
		err = FlushAlternateVolumeControlBlock( calculatedVCB, isHFSPlus );	//	Writes real & alt blocks
		ReturnIfError( err );
	}

 	err = CheckForStop( GPtr ); ReturnIfError( err );				//	Permit the user to interrupt
 
 	// if we had minor repairs that failed we still want to fix as much as possible
 	// so we wait until now to indicate the volume still has problems
 	if ( GPtr->minorRepairErrors )
 		err = R_RFail;
	
	return( err );													//	all done
}



//
//	Internal Routines
//

//�������������������������������������������������������������������������������
//	Routine:	VolumeObjectFixVHBorMDB
//
//	Function:	When the primary or alternate Volume Header Block or Master 
//				Directory Block is damaged or missing use the undamaged one to 
//				restore the other.
//�������������������������������������������������������������������������������

static OSErr VolumeObjectFixVHBorMDB( Boolean* fixedItPtr )
{
	OSErr				err;
	OSErr				err2;
	VolumeObjectPtr		myVOPtr;
	BlockDescriptor  	myPrimary;
	BlockDescriptor  	myAlternate;

	myVOPtr = GetVolumeObjectPtr( );
	myPrimary.buffer = NULL;
	myAlternate.buffer = NULL;
	err = noErr;
	
	// bail if both are OK
	if ( VolumeObjectIsHFS() ) {
		if ( (myVOPtr->flags & kVO_PriMDBOK) != 0 &&
			 (myVOPtr->flags & kVO_AltMDBOK) != 0 )
			goto ExitThisRoutine;
	}
	else {
		if ( (myVOPtr->flags & kVO_PriVHBOK) != 0 &&
			 (myVOPtr->flags & kVO_AltVHBOK) != 0 )
			goto ExitThisRoutine;
	}
			
	// it's OK if one of the primary or alternate is invalid
	err = GetVolumeObjectPrimaryBlock( &myPrimary );
	if ( !(err == noErr || err == badMDBErr || err == noMacDskErr) )
		goto ExitThisRoutine;

	// invalidate if we have not marked the primary as OK
	if ( VolumeObjectIsHFS( ) ) {
		if ( (myVOPtr->flags & kVO_PriMDBOK) == 0 )
			err = badMDBErr;
	}
	else if ( (myVOPtr->flags & kVO_PriVHBOK) == 0 ) {
		err = badMDBErr;
	}

	err2 = GetVolumeObjectAlternateBlock( &myAlternate );
	if ( !(err2 == noErr || err2 == badMDBErr || err2 == noMacDskErr) )
		goto ExitThisRoutine;

	// invalidate if we have not marked the alternate as OK
	if ( VolumeObjectIsHFS( ) ) {
		if ( (myVOPtr->flags & kVO_AltMDBOK) == 0 )
			err2 = badMDBErr;
	}
	else if ( (myVOPtr->flags & kVO_AltVHBOK) == 0 ) {
		err2 = badMDBErr;
	}
		
	// primary is OK so use it to restore alternate
	if ( err == noErr ) {
		CopyMemory( myPrimary.buffer, myAlternate.buffer, Blk_Size );
		(void) ReleaseVolumeBlock( myVOPtr->vcbPtr, &myAlternate, kForceWriteBlock );		
		myAlternate.buffer = NULL;
		*fixedItPtr = true;
		if ( VolumeObjectIsHFS( ) )
			myVOPtr->flags |= kVO_AltMDBOK;
		else
			myVOPtr->flags |= kVO_AltVHBOK;
	}
	// alternate is OK so use it to restore the primary
	else if ( err2 == noErr ) {
		CopyMemory( myAlternate.buffer, myPrimary.buffer, Blk_Size );
		(void) ReleaseVolumeBlock( myVOPtr->vcbPtr, &myPrimary, kForceWriteBlock );		
		myPrimary.buffer = NULL;
		*fixedItPtr = true;
		if ( VolumeObjectIsHFS( ) )
			myVOPtr->flags |= kVO_PriMDBOK;
		else
			myVOPtr->flags |= kVO_PriVHBOK;
		err = noErr;
	}
	else
		err = noMacDskErr;

ExitThisRoutine:
	if ( myPrimary.buffer != NULL )
		(void) ReleaseVolumeBlock( myVOPtr->vcbPtr, &myPrimary, kReleaseBlock );
	if ( myAlternate.buffer != NULL )
		(void) ReleaseVolumeBlock( myVOPtr->vcbPtr, &myAlternate, kReleaseBlock );

	return( err );
	
} /* VolumeObjectFixVHBorMDB */
		

//�������������������������������������������������������������������������������
//	Routine:	VolumeObjectRestoreWrapper
//
//	Function:	When the primary or alternate Master Directory Block is damaged 
//				or missing use the undamaged one to restore the other.
//�������������������������������������������������������������������������������

static OSErr VolumeObjectRestoreWrapper( void )
{
	OSErr				err;
	OSErr				err2;
	VolumeObjectPtr		myVOPtr;
	BlockDescriptor  	myPrimary;
	BlockDescriptor  	myAlternate;

	myVOPtr = GetVolumeObjectPtr( );
	myPrimary.buffer = NULL;
	myAlternate.buffer = NULL;
				
	// it's OK if one of the MDB is invalid
	err = GetVolumeObjectPrimaryMDB( &myPrimary );
	if ( !(err == noErr || err == badMDBErr || err == noMacDskErr) )
		goto ExitThisRoutine;
	err2 = GetVolumeObjectAlternateMDB( &myAlternate );
	if ( !(err2 == noErr || err2 == badMDBErr || err2 == noMacDskErr) )
		goto ExitThisRoutine;

	// primary is OK so use it to restore alternate
	if ( err == noErr && (myVOPtr->flags & kVO_PriMDBOK) != 0 ) {
		CopyMemory( myPrimary.buffer, myAlternate.buffer, Blk_Size );
		(void) ReleaseVolumeBlock( myVOPtr->vcbPtr, &myAlternate, kForceWriteBlock );		
		myAlternate.buffer = NULL;
		myVOPtr->flags |= kVO_AltMDBOK;
	}
	// alternate is OK so use it to restore the primary
	else if ( err2 == noErr && (myVOPtr->flags & kVO_AltMDBOK) != 0 ) {
		CopyMemory( myAlternate.buffer, myPrimary.buffer, Blk_Size );
		(void) ReleaseVolumeBlock( myVOPtr->vcbPtr, &myPrimary, kForceWriteBlock );		
		myPrimary.buffer = NULL;
		myVOPtr->flags |= kVO_PriMDBOK;
		err = noErr;
	}
	else
		err = noMacDskErr;

ExitThisRoutine:
	if ( myPrimary.buffer != NULL )
		(void) ReleaseVolumeBlock( myVOPtr->vcbPtr, &myPrimary, kReleaseBlock );
	if ( myAlternate.buffer != NULL )
		(void) ReleaseVolumeBlock( myVOPtr->vcbPtr, &myAlternate, kReleaseBlock );

	return( err );
	
} /* VolumeObjectRestoreWrapper */
		

/*------------------------------------------------------------------------------
Routine:	UpdateBTreeHeader - (Update BTree Header)

Function:	Replaces a BTH on disk with info from a scavenger BTCB.
			
Input:		GPtr		-	pointer to scavenger global area
			refNum		-	file refnum

Output:		UpdateBTreeHeader	-	function result:			
								0	= no error
								n 	= error
------------------------------------------------------------------------------*/

static	OSErr	UpdateBTreeHeader( SFCB * fcbPtr )
{
	OSErr err;

	M_BTreeHeaderDirty( ((BTreeControlBlockPtr) fcbPtr->fcbBtree) );	
	err = BTFlushPath( fcbPtr );
	
	return( err );

} /* End UpdateBTreeHeader */


		
/*------------------------------------------------------------------------------
Routine:	FixBTreeHeaderReservedFields

Function:	Fix reserved fields in BTree Header
			
Input:		GPtr		-	pointer to scavenger global area
			refNum		-	file refnum

Output:		0	= no error
			n 	= error
------------------------------------------------------------------------------*/

static	OSErr	FixBTreeHeaderReservedFields( SGlobPtr GPtr, short refNum )
{
	OSErr        err;
	BTHeaderRec  header;

	err = GetBTreeHeader(GPtr, ResolveFCB(refNum), &header);
	ReturnIfError( err );
	
	if ( (header.clumpSize % GPtr->calculatedVCB->vcbBlockSize) != 0 )
		header.clumpSize = GPtr->calculatedVCB->vcbBlockSize;
		
	header.reserved1	= 0;
	header.btreeType	= kHFSBTreeType;  //	control file
/*
 * TBD - we'll need to repair an invlid keyCompareType field.
 */
#if 0
	if (-->TBD<--)
		header.keyCompareType = kHFSBinaryCompare;
#endif
	ClearMemory( header.reserved3, sizeof(header.reserved3) );

	return( err );
}


		

/*------------------------------------------------------------------------------

Routine:	UpdBTM - (Update BTree Map)

Function:	Replaces a BTM on disk with a scavenger BTM.
			
Input:		GPtr		-	pointer to scavenger global area
			refNum		-	file refnum

Output:		UpdBTM	-	function result:			
								0	= no error
								n 	= error
------------------------------------------------------------------------------*/

static	OSErr	UpdBTM( SGlobPtr GPtr, short refNum )
{
	OSErr				err;
	UInt16				recSize;
	SInt32				mapSize;
	SInt16				size;
	SInt16				recIndx;
	Ptr					p;
	Ptr					btmP;
	Ptr					sbtmP;
	UInt32				nodeNum;
	NodeRec				node;
	UInt32				fLink;
	BTreeControlBlock	*calculatedBTCB	= GetBTreeControlBlock( refNum );

	//	Set up
	mapSize			= ((BTreeExtensionsRec*)calculatedBTCB->refCon)->BTCBMSize;

	//
	//	update the map records
	//
	if ( mapSize > 0 )
	{
		nodeNum	= 0;
		recIndx	= 2;
		sbtmP	= ((BTreeExtensionsRec*)calculatedBTCB->refCon)->BTCBMPtr;
		
		do
		{
			GPtr->TarBlock = nodeNum;								//	set target node number
				
			err = GetNode( calculatedBTCB, nodeNum, &node );
			ReturnIfError( err );									//	could't get map node
	
			//	Locate the map record
			recSize = GetRecordSize( calculatedBTCB, (BTNodeDescriptor *)node.buffer, recIndx );
			btmP = (Ptr)GetRecordAddress( calculatedBTCB, (BTNodeDescriptor *)node.buffer, recIndx );
			fLink	= ((NodeDescPtr)node.buffer)->fLink;
			size	= ( recSize  > mapSize ) ? mapSize : recSize;
				
			CopyMemory( sbtmP, btmP, size );						//	update it
			
			err = UpdateNode( calculatedBTCB, &node );				//	write it, and unlock buffer
			
			mapSize	-= size;										//	move to next map record
			if ( mapSize == 0 )										//	more to go?
				break;												//	no, zero remainder of record
			if ( fLink == 0 )										//	out of bitmap blocks in file?
			{
				RcdError( GPtr, E_ShortBTM );
				(void) ReleaseNode(calculatedBTCB, &node);
				return( E_ShortBTM );
			}
				
			nodeNum	= fLink;
			sbtmP	+= size;
			recIndx	= 0;
			
		} while ( mapSize > 0 );

		//	clear the unused portion of the map record
		for ( p = btmP + size ; p < btmP + recSize ; p++ )
			*p = 0; 

		err = UpdateNode( calculatedBTCB, &node );					//	Write it, and unlock buffer
	}
	
	return( noErr );												//	All done
}	//	end UpdBTM


		

/*------------------------------------------------------------------------------

Routine:	UpdateVolumeBitMap - (Update Volume Bit Map)

Function:	Replaces the VBM on disk with the scavenger VBM.
			
Input:		GPtr			-	pointer to scavenger global area

Output:		UpdateVolumeBitMap			- 	function result:
									0 = no error
									n = error
			GPtr->VIStat	-	S_VBM flag set if VBM is damaged.
------------------------------------------------------------------------------*/

static	OSErr	UpdateVolumeBitMap( SGlobPtr GPtr, Boolean preAllocateOverlappedExtents )
{
	GPtr->TarID = VBM_FNum;

	return ( CheckVolumeBitMap(GPtr, true) );
}


/*------------------------------------------------------------------------------

Routine:	DoMinorOrders

Function:	Execute minor repair orders.

Input:		GPtr	- ptr to scavenger global data

Outut:		function result:
				0 - no error
				n - error
------------------------------------------------------------------------------*/

static	OSErr	DoMinorOrders( SGlobPtr GPtr )				//	the globals
{
	RepairOrderPtr		p;
	OSErr				err	= noErr;						//	initialize to "no error"
	
	while( (p = GPtr->MinorRepairsP) && (err == noErr) )	//	loop over each repair order
	{
		GPtr->MinorRepairsP = p->link;						//	unlink next from list
		
		switch( p->type )									//	branch on repair type
		{
			case E_RtDirCnt:								//	the valence errors
			case E_RtFilCnt:								//	(of which there are several)
			case E_DirCnt:
			case E_FilCnt:
			case E_DirVal:
				err = UpdVal( GPtr, p );					//	handle a valence error
				break;
			
			case E_LockedDirName:
				err = FixFinderFlags( GPtr, p );
				break;

			case E_UnlinkedFile:
				err = DeleteUnlinkedFile( GPtr, p );
				break;

			case E_InvalidLinkCount:
				err = FixLinkCount( GPtr, p );
				break;
			
			case E_InvalidPermissions:
			case E_InvalidUID:
				err = FixBSDInfo( GPtr, p );
				break;
			
			case E_NoFile:									//	dangling file thread
				err = DelFThd( GPtr, p->parid );			//	delete the dangling thread
				break;

			//��	E_NoFile case is never hit since VLockedChk() registers the error, 
			//��	and returns the error causing the verification to quit.
			case E_EntryNotFound:
				GPtr->EBTStat |= S_OrphanedExtent;
				break;

			//��	Same with E_NoDir
			case E_NoDir:									//	missing directory record
				err = FixDirThread( GPtr, p->parid );		//	fix the directory thread record
				break;
			
			case E_InvalidMDBdrAlBlSt:
				err = FixEmbededVolDescription( GPtr, p );
				break;
			
			case E_InvalidWrapperExtents:
				err = FixWrapperExtents(GPtr, p);
				break;

            case E_IllegalName:
                err = FixIllegalNames( GPtr, p );
				break;

			case E_PEOF:
			case E_LEOF:
				err = FixFileSize(GPtr, p);
				break;

			case E_PEOAttr:
			case E_LEOAttr:
				err = FixAttrSize(GPtr, p);
				break;
			
			case E_ExtEnt:
				err = FixBadExtent(GPtr, p);
				break;

			default:										//	unknown repair type
				err = IntError( GPtr, R_IntErr );			//	treat as an internal error
				break;
		}
		
		DisposeMemory( p );								//	free the node
	}
	
	return( err );											//	return error code to our caller
}



/*------------------------------------------------------------------------------

Routine:	DelFThd - (delete file thread)

Function:	Executes the delete dangling file thread repair orders.  These are typically
			threads left after system 6 deletes an aliased file, since system 6 is not
			aware of aliases and thus will not delete the thread along with the file.

Input:		GPtr	- global data
			fid		- the thread record's key's parent-ID

Output:		0 - no error
			n - deletion failed
Modification History:
	29Oct90		KST		CBTDelete was using "k" as key which points to cache buffer.
-------------------------------------------------------------------------------*/

static	int	DelFThd( SGlobPtr GPtr, UInt32 fid )				//	the file ID
{
	CatalogRecord		record;
	CatalogKey			foundKey;
	CatalogKey			key;
	UInt32				hint;								//	as returned by CBTSearch
	OSErr				result;								//	status return
	UInt16				recSize;
	Boolean				isHFSPlus;
	ExtentRecord		zeroExtents;

	isHFSPlus = VolumeObjectIsHFSPlus( );
	
	BuildCatalogKey(fid, NULL, isHFSPlus, &key);
	result = SearchBTreeRecord( GPtr->calculatedCatalogFCB, &key, kNoHint, &foundKey, &record, &recSize, &hint );
	
	if ( result )	return ( IntError( GPtr, result ) );
	
	if ( (record.recordType != kHFSFileThreadRecord) && (record.recordType != kHFSPlusFileThreadRecord) )	//	quit if not a file thread
		return ( IntError( GPtr, R_IntErr ) );
	
	//	Zero the record on disk
	ClearMemory( (Ptr)&zeroExtents, sizeof(ExtentRecord) );
	result	= ReplaceBTreeRecord( GPtr->calculatedCatalogFCB, &key, hint, &zeroExtents, recSize, &hint );
	if ( result )	return ( IntError( GPtr, result ) );
	
	result	= DeleteBTreeRecord( GPtr->calculatedCatalogFCB, &key );
	if ( result )	return ( IntError( GPtr, result ) );
	
	//	After deleting a record, we'll need to write back the BT header and map,
	//	to reflect the updated record count etc.
	   
	GPtr->CBTStat |= S_BTH + S_BTM;							//	set flags to write back hdr and map

	return( noErr );										//	successful return
}
	

/*------------------------------------------------------------------------------

Routine:	FixDirThread - (fix directory thread record's parent ID info)

Function:	Executes the missing directory record repair orders most likely caused by 
			disappearing folder bug.  This bug causes some folders to jump to Desktop 
			from the root window.  The catalog directory record for such a folder has 
			the Desktop folder as the parent but its thread record still the root 
			directory as its parent.

Input:		GPtr	- global data
			did		- the thread record's key's parent-ID

Output:		0 - no error
			n - deletion failed
-------------------------------------------------------------------------------*/

static	OSErr	FixDirThread( SGlobPtr GPtr, UInt32 did )	//	the dir ID
{
	UInt8				*dataPtr;
	UInt32				hint;							//	as returned by CBTSearch
	OSErr				result;							//	status return
	UInt16				recSize;
	CatalogName			catalogName;					//	temporary name record
	CatalogName			*keyName;						//	temporary name record
	register short 		index;							//	loop index for all records in the node
	UInt32  			curLeafNode;					//	current leaf node being checked
	CatalogRecord		record;
	CatalogKey			foundKey;
	CatalogKey			key;
	CatalogKey		 	*keyP;
	SInt16				recordType;
	UInt32				folderID;
	NodeRec				node;
	NodeDescPtr			nodeDescP;
	UInt32				newParDirID		= 0;			//	the parent ID where the dir record is really located
	Boolean				isHFSPlus;
	BTreeControlBlock	*calculatedBTCB	= GetBTreeControlBlock( kCalculatedCatalogRefNum );

	isHFSPlus = VolumeObjectIsHFSPlus( );

	BuildCatalogKey(did, NULL, isHFSPlus, &key);
	result = SearchBTreeRecord( GPtr->calculatedCatalogFCB, &key, kNoHint, &foundKey, &record, &recSize, &hint );
	
	if ( result )
		return( IntError( GPtr, result ) );
	if ( (record.recordType != kHFSFolderThreadRecord) && (record.recordType != kHFSPlusFolderThreadRecord) )			//	quit if not a directory thread
		return ( IntError( GPtr, R_IntErr ) );
		
	curLeafNode = calculatedBTCB->freeNodes;
	
	while ( curLeafNode )
	{
		result = GetNode( calculatedBTCB, curLeafNode, &node );
		if ( result != noErr ) return( IntError( GPtr, result ) );
		
		nodeDescP = node.buffer;

		// loop on number of records in node
		for ( index = 0 ; index < nodeDescP->numRecords ; index++ )
		{
			GetRecordByIndex( calculatedBTCB, (NodeDescPtr)nodeDescP, index, (BTreeKey **)&keyP, &dataPtr, &recSize );
			
			recordType	= ((CatalogRecord *)dataPtr)->recordType;
			folderID	= recordType == kHFSPlusFolderRecord ? ((HFSPlusCatalogFolder *)dataPtr)->folderID : ((HFSCatalogFolder *)dataPtr)->folderID;
			
			// did we locate a directory record whode dirID match the the thread's key's parent dir ID?
			if ( (folderID == did) && ( recordType == kHFSPlusFolderRecord || recordType == kHFSFolderRecord ) )
			{
				newParDirID	= recordType == kHFSPlusFolderRecord ? keyP->hfsPlus.parentID : keyP->hfs.parentID;
				keyName		= recordType == kHFSPlusFolderRecord ? (CatalogName *)&keyP->hfsPlus.nodeName : (CatalogName *)&keyP->hfs.nodeName;
				CopyCatalogName( keyName, &catalogName, isHFSPlus );
				break;
			}
		}

		if ( newParDirID ) {
			(void) ReleaseNode(calculatedBTCB, &node);
			break;
		}

		curLeafNode = nodeDescP->fLink;	 // sibling of this leaf node
		
		(void) ReleaseNode(calculatedBTCB, &node);
	}
		
	if ( newParDirID == 0 )
	{
		return ( IntError( GPtr, R_IntErr ) ); // ��  Try fixing by creating a new directory record?
	}
	else
	{
		(void) SearchBTreeRecord( GPtr->calculatedCatalogFCB, &key, kNoHint, &foundKey, &record, &recSize, &hint );

		if ( isHFSPlus )
		{
			HFSPlusCatalogThread	*largeCatalogThreadP	= (HFSPlusCatalogThread *) &record;
			
			largeCatalogThreadP->parentID = newParDirID;
			CopyCatalogName( &catalogName, (CatalogName *) &largeCatalogThreadP->nodeName, isHFSPlus );
		}
		else
		{
			HFSCatalogThread	*smallCatalogThreadP	= (HFSCatalogThread *) &record;
			
			smallCatalogThreadP->parentID = newParDirID;
			CopyCatalogName( &catalogName, (CatalogName *)&smallCatalogThreadP->nodeName, isHFSPlus );
		}
		
		result = ReplaceBTreeRecord( GPtr->calculatedCatalogFCB, &foundKey, hint, &record, recSize, &hint );
	}

	return( noErr );										//	successful return
}
	

/*------------------------------------------------------------------------------

Routine:	UpdVal - (Update Valence)

Function:	Replaces out of date valences with correct vals computed during scavenge.
			
Input:		GPtr			-	pointer to scavenger global area
			p				- 	pointer to the repair order

Output:		UpdVal			- 	function result:
									0 = no error
									n = error
------------------------------------------------------------------------------*/

static	OSErr	UpdVal( SGlobPtr GPtr, RepairOrderPtr p )					//	the valence repair order
{
	OSErr				result;						//	status return
	Boolean				isHFSPlus;
	UInt32				hint;						//	as returned by CBTSearch
	UInt16				recSize;
	CatalogRecord		record;
	CatalogKey			foundKey;
	CatalogKey			key;
	SVCB				*calculatedVCB = GPtr->calculatedVCB;

	isHFSPlus = VolumeObjectIsHFSPlus( );

	switch( p->type )
	{
		case E_RtDirCnt: //	invalid count of Dirs in Root
			if ( (UInt16)p->incorrect != calculatedVCB->vcbNmRtDirs )
				return ( IntError( GPtr, R_IntErr ) );
			calculatedVCB->vcbNmRtDirs = (UInt16)p->correct;
			GPtr->VIStat |= S_MDB;
			break;
			
		case E_RtFilCnt:
			if ( (UInt16)p->incorrect != calculatedVCB->vcbNmFls )
				return ( IntError( GPtr, R_IntErr ) );
			calculatedVCB->vcbNmFls = (UInt16)p->correct;
			GPtr->VIStat |= S_MDB;
			break;
			
		case E_DirCnt:
			if ( (UInt32)p->incorrect != calculatedVCB->vcbFolderCount )
				return ( IntError( GPtr, R_IntErr ) );
			calculatedVCB->vcbFolderCount = (UInt32)p->correct;
			GPtr->VIStat |= S_MDB;
			break;
			
		case E_FilCnt:
			if ( (UInt32)p->incorrect != calculatedVCB->vcbFileCount )
				return ( IntError( GPtr, R_IntErr ) );
			calculatedVCB->vcbFileCount = (UInt32)p->correct;
			GPtr->VIStat |= S_MDB;
			break;
	
		case E_DirVal:
			BuildCatalogKey( p->parid, (CatalogName *)&p->name, isHFSPlus, &key );
			result = SearchBTreeRecord( GPtr->calculatedCatalogFCB, &key, kNoHint,
					&foundKey, &record, &recSize, &hint );
			if ( result )
				return ( IntError( GPtr, result ) );
				
			if ( record.recordType == kHFSPlusFolderRecord )
			{
				if ( (UInt32)p->incorrect != record.hfsPlusFolder.valence)
					return ( IntError( GPtr, R_IntErr ) );
				record.hfsPlusFolder.valence = (UInt32)p->correct;
			}
			else
			{
				if ( (UInt16)p->incorrect != record.hfsFolder.valence )
					return ( IntError( GPtr, R_IntErr ) );
				record.hfsFolder.valence = (UInt16)p->correct;
			}
				
			result = ReplaceBTreeRecord( GPtr->calculatedCatalogFCB, &key, hint,\
						&record, recSize, &hint );
			if ( result )
				return ( IntError( GPtr, result ) );
			break;
	}
		
	return( noErr );														//	no error
}

/*------------------------------------------------------------------------------

Routine:	FixFinderFlags

Function:	Changes some of the Finder flag bits for directories.
			
Input:		GPtr			-	pointer to scavenger global area
			p				- 	pointer to the repair order

Output:		FixFinderFlags	- 	function result:
									0 = no error
									n = error
------------------------------------------------------------------------------*/

static	OSErr	FixFinderFlags( SGlobPtr GPtr, RepairOrderPtr p )				//	the repair order
{
	CatalogRecord		record;
	CatalogKey			foundKey;
	CatalogKey			key;
	UInt32				hint;												//	as returned by CBTSearch
	OSErr				result;												//	status return
	UInt16				recSize;
	Boolean				isHFSPlus;

	isHFSPlus = VolumeObjectIsHFSPlus( );

	BuildCatalogKey( p->parid, (CatalogName *)&p->name, isHFSPlus, &key );

	result = SearchBTreeRecord( GPtr->calculatedCatalogFCB, &key, kNoHint, &foundKey, &record, &recSize, &hint );
	if ( result )
		return ( IntError( GPtr, result ) );

	if ( record.recordType == kHFSPlusFolderRecord )
	{
		HFSPlusCatalogFolder	*largeCatalogFolderP	= (HFSPlusCatalogFolder *) &record;	
		if ( (UInt16) p->incorrect != SWAP_BE16(largeCatalogFolderP->userInfo.frFlags) )
		{
			//	Another repar order may have affected the flags
			if ( p->correct < p->incorrect )
				largeCatalogFolderP->userInfo.frFlags &= SWAP_BE16(~((UInt16)p->maskBit));
			else
				largeCatalogFolderP->userInfo.frFlags |= SWAP_BE16((UInt16)p->maskBit);
		}
		else
		{
			largeCatalogFolderP->userInfo.frFlags = SWAP_BE16((UInt16)p->correct);
		}
	//	largeCatalogFolderP->contentModDate = timeStamp;
	}
	else
	{
		HFSCatalogFolder	*smallCatalogFolderP	= (HFSCatalogFolder *) &record;	
		if ( p->incorrect != SWAP_BE16(smallCatalogFolderP->userInfo.frFlags) )		//	do we know what we're doing?
		{
			//	Another repar order may have affected the flags
			if ( p->correct < p->incorrect )
				smallCatalogFolderP->userInfo.frFlags &= SWAP_BE16(~((UInt16)p->maskBit));
			else
				smallCatalogFolderP->userInfo.frFlags |= SWAP_BE16((UInt16)p->maskBit);
		}
		else
		{
			smallCatalogFolderP->userInfo.frFlags = SWAP_BE16((UInt16)p->correct);
		}
		
	//	smallCatalogFolderP->modifyDate = timeStamp;						// also update the modify date! -DJB
	}

	result = ReplaceBTreeRecord( GPtr->calculatedCatalogFCB, &foundKey, hint, &record, recSize, &hint );	//	write the node back to the file
	if ( result )
		return( IntError( GPtr, result ) );
		
	return( noErr );														//	no error
}


/*------------------------------------------------------------------------------
FixLinkCount:  Adjust a data node link count (BSD hard link)
               (HFS Plus volumes only)
------------------------------------------------------------------------------*/
static OSErr
FixLinkCount(SGlobPtr GPtr, RepairOrderPtr p)
{
	SFCB *fcb;
	CatalogRecord rec;
	HFSPlusCatalogKey * keyp;
	FSBufferDescriptor btRecord;
	BTreeIterator btIterator;
	size_t len;
	OSErr result;
	UInt16 recSize;
	Boolean				isHFSPlus;

	isHFSPlus = VolumeObjectIsHFSPlus( );
	if (!isHFSPlus)
		return (0);
	fcb = GPtr->calculatedCatalogFCB;

	ClearMemory(&btIterator, sizeof(btIterator));
	btIterator.hint.nodeNum = p->hint;
	keyp = (HFSPlusCatalogKey*)&btIterator.key;
	keyp->parentID = p->parid;
	/* name was stored in UTF-8 */
	(void) utf_decodestr(&p->name[1], p->name[0], keyp->nodeName.unicode, &len);
	keyp->nodeName.length = len / 2;
	keyp->keyLength = kHFSPlusCatalogKeyMinimumLength + len;

	btRecord.bufferAddress = &rec;
	btRecord.itemCount = 1;
	btRecord.itemSize = sizeof(rec);
	
	result = BTSearchRecord(fcb, &btIterator, kInvalidMRUCacheKey,
			&btRecord, &recSize, &btIterator);
	if (result)
		return (IntError(GPtr, result));

	if (rec.recordType != kHFSPlusFileRecord)
		return (noErr);

	if ((UInt32)p->correct != rec.hfsPlusFile.bsdInfo.special.linkCount) {
		if (GPtr->logLevel >= kDebugLog)
		    printf("\t%s: fixing link count from %d to %d\n",
		        &p->name[1], rec.hfsPlusFile.bsdInfo.special.linkCount, (int)p->correct);

		rec.hfsPlusFile.bsdInfo.special.linkCount = (UInt32)p->correct;
		result = BTReplaceRecord(fcb, &btIterator, &btRecord, recSize);
		if (result)
			return (IntError(GPtr, result));
	}
		
	return (noErr);
}


/*------------------------------------------------------------------------------
FixIllegalNames:  Fix catalog enties that have illegal names.
    RepairOrder.name[] holds the old (illegal) name followed by the new name.
    The new name has been checked to make sure it is unique within the target
    directory.  The names will look like this:
        2 byte length of old name (in unicode characters not bytes)
        unicode characters for old name
        2 byte length of new name (in unicode characters not bytes)
        unicode characters for new name
------------------------------------------------------------------------------*/
static OSErr
FixIllegalNames( SGlobPtr GPtr, RepairOrderPtr roPtr )
{
	OSErr 				result;
	Boolean				isHFSPlus;
	Boolean				isDirectory;
	UInt16				recSize;
	SFCB *				fcbPtr;
    CatalogName *		oldNamePtr;
    CatalogName *		newNamePtr;
	UInt32				hint;				
	CatalogRecord		record;
	CatalogKey			key;
	CatalogKey			newKey;

	isHFSPlus = VolumeObjectIsHFSPlus( );
 	fcbPtr = GPtr->calculatedCatalogFCB;
    
	oldNamePtr = (CatalogName *) &roPtr->name;
    if ( isHFSPlus )
    {
        int					myLength;
        u_int16_t *			myPtr = (u_int16_t *) oldNamePtr;
        myLength = *myPtr; // get length of old name
        myPtr += (1 + myLength);  // bump past length of old name and old name
        newNamePtr = (CatalogName *) myPtr;
    }
    else
    {
        int					myLength;
        u_char *			myPtr = (u_char *) oldNamePtr;
        myLength = *myPtr; // get length of old name
        myPtr += (1 + myLength);  // bump past length of old name and old name
        newNamePtr = (CatalogName *) myPtr;
    }

	// make sure new name isn't already there
	BuildCatalogKey( roPtr->parid, newNamePtr, isHFSPlus, &newKey );
	result = SearchBTreeRecord( fcbPtr, &newKey, kNoHint, NULL, &record, &recSize, NULL );
	if ( result == noErr ) {
		if ( GPtr->logLevel >= kDebugLog ) {
        	printf( "\treplacement name already exists \n" );
			printf( "\tduplicate name is 0x" );
			PrintName( newNamePtr->ustr.length, (UInt8 *) &newNamePtr->ustr.unicode, true );
		}
        goto ErrorExit;
    }
    
    // get catalog record for object with the illegal name.  We will restore this
    // info with our new (valid) name. 
	BuildCatalogKey( roPtr->parid, oldNamePtr, isHFSPlus, &key );
	result = SearchBTreeRecord( fcbPtr, &key, kNoHint, NULL, &record, &recSize, &hint );
	if ( result != noErr ) {
        goto ErrorExit;
    }
 
    result	= DeleteBTreeRecord( fcbPtr, &key );
	if ( result != noErr ) {
        goto ErrorExit;
    }
 
    // insert record back into the catalog using the new name
    result	= InsertBTreeRecord( fcbPtr, &newKey, &record, recSize, &hint );
	if ( result != noErr ) {
        goto ErrorExit;
    }

	isDirectory = false;
    switch( record.recordType )
    {
        case kHFSFolderRecord:
        case kHFSPlusFolderRecord:	
			isDirectory = true;	 break;
    }
 
    // now we need to remove the old thread record and create a new one with
    // our new name.
	BuildCatalogKey( GetObjectID( &record ), NULL, isHFSPlus, &key );
	result = SearchBTreeRecord( fcbPtr, &key, kNoHint, NULL, &record, &recSize, &hint );
	if ( result != noErr ) {
        goto ErrorExit;
    }
 
    result	= DeleteBTreeRecord( fcbPtr, &key );
	if ( result != noErr ) {
        goto ErrorExit;
    }

    // insert thread record with new name as thread data
	recSize = BuildThreadRec( &newKey, &record, isHFSPlus, isDirectory );
 	result = InsertBTreeRecord( fcbPtr, &key, &record, recSize, &hint );
	if ( result != noErr ) {
        goto ErrorExit;
	}

    return( noErr );
 
ErrorExit:
	GPtr->minorRepairErrors = true;
    if ( GPtr->logLevel >= kDebugLog )
        printf( "\t%s - repair failed for type 0x%02X %d \n", __FUNCTION__, roPtr->type, roPtr->type );
    return( noErr );  // errors in this routine should not be fatal
    
} /* FixIllegalNames */


/*------------------------------------------------------------------------------
FixBSDInfo:  Reset or repair BSD info
                 (HFS Plus volumes only)
------------------------------------------------------------------------------*/
static OSErr
FixBSDInfo(SGlobPtr GPtr, RepairOrderPtr p)
{
	SFCB 						*fcb;
	CatalogRecord 				rec;
	FSBufferDescriptor 			btRecord;
	BTreeIterator 				btIterator;
	Boolean						isHFSPlus;
	OSErr 						result;
	UInt16 						recSize;
	size_t 						namelen;
	unsigned char 				filename[256];

	isHFSPlus = VolumeObjectIsHFSPlus( );
	if (!isHFSPlus)
		return (0);
	fcb = GPtr->calculatedCatalogFCB;

	ClearMemory(&btIterator, sizeof(btIterator));
	btIterator.hint.nodeNum = p->hint;
	BuildCatalogKey(p->parid, (CatalogName *)&p->name, true,
		(CatalogKey*)&btIterator.key);
	btRecord.bufferAddress = &rec;
	btRecord.itemCount = 1;
	btRecord.itemSize = sizeof(rec);
	
	result = BTSearchRecord(fcb, &btIterator, kInvalidMRUCacheKey,
			&btRecord, &recSize, &btIterator);
	if (result)
		return (IntError(GPtr, result));

	if (rec.recordType != kHFSPlusFileRecord &&
	    rec.recordType != kHFSPlusFolderRecord)
		return (noErr);

	utf_encodestr(((HFSUniStr255 *)&p->name)->unicode,
		((HFSUniStr255 *)&p->name)->length << 1, filename, &namelen);
	filename[namelen] = '\0';

	if (p->type == E_InvalidPermissions &&
	    ((UInt16)p->incorrect == rec.hfsPlusFile.bsdInfo.fileMode)) {
		if (GPtr->logLevel >= kDebugLog)
		    printf("\t\"%s\": fixing mode from %07o to %07o\n",
			   filename, (int)p->incorrect, (int)p->correct);

		rec.hfsPlusFile.bsdInfo.fileMode = (UInt16)p->correct;
		result = BTReplaceRecord(fcb, &btIterator, &btRecord, recSize);
	}

	if (p->type == E_InvalidUID) {
		if ((UInt32)p->incorrect == rec.hfsPlusFile.bsdInfo.ownerID) {
			if (GPtr->logLevel >= kDebugLog) {
				printf("\t\"%s\": replacing UID %d with %d\n",
				filename, (int)p->incorrect, (int)p->correct);
			}
			rec.hfsPlusFile.bsdInfo.ownerID = (UInt32)p->correct;
		}
		/* Fix group ID if neccessary */
		if ((UInt32)p->incorrect == rec.hfsPlusFile.bsdInfo.groupID)
			rec.hfsPlusFile.bsdInfo.groupID = (UInt32)p->correct;
		result = BTReplaceRecord(fcb, &btIterator, &btRecord, recSize);
	}

	if (result)
		return (IntError(GPtr, result));
	else	
		return (noErr);
}


/*------------------------------------------------------------------------------
DeleteUnlinkedFile:  Delete orphaned data node (BSD unlinked file)
		     Also used to delete empty "HFS+ Private Data" directories
                     (HFS Plus volumes only)
------------------------------------------------------------------------------*/
static OSErr
DeleteUnlinkedFile(SGlobPtr GPtr, RepairOrderPtr p)
{
	CatalogName 		name;
	CatalogName 		*cNameP;
	Boolean				isHFSPlus;
	size_t 				len;

	isHFSPlus = VolumeObjectIsHFSPlus( );
	if (!isHFSPlus)
		return (0);

	if (p->name[0] > 0) {
		/* name was stored in UTF-8 */
		(void) utf_decodestr(&p->name[1], p->name[0], name.ustr.unicode, &len);
		name.ustr.length = len / 2;
		cNameP = &name;
	} else {
		cNameP = NULL;
	}

	(void) DeleteCatalogNode(GPtr->calculatedVCB, p->parid, cNameP, p->hint);

	GPtr->VIStat |= S_MDB;
	GPtr->VIStat |= S_VBM;

	return (noErr);
}

/*
 * Fix a file's PEOF or LEOF (truncate)
 * (HFS Plus volumes only)
 */
static OSErr
FixFileSize(SGlobPtr GPtr, RepairOrderPtr p)
{
	SFCB *fcb;
	CatalogRecord rec;
	HFSPlusCatalogKey * keyp;
	FSBufferDescriptor btRecord;
	BTreeIterator btIterator;
	size_t len;
	Boolean	isHFSPlus;
	Boolean replace;
	OSErr result;
	UInt16 recSize;
	UInt64 bytes;

	isHFSPlus = VolumeObjectIsHFSPlus( );
	if (!isHFSPlus)
		return (0);
	fcb = GPtr->calculatedCatalogFCB;
	replace = false;

	ClearMemory(&btIterator, sizeof(btIterator));
	btIterator.hint.nodeNum = p->hint;
	keyp = (HFSPlusCatalogKey*)&btIterator.key;
	keyp->parentID = p->parid;

	/* name was stored in UTF-8 */
	(void) utf_decodestr(&p->name[1], p->name[0], keyp->nodeName.unicode, &len);
	keyp->nodeName.length = len / 2;
	keyp->keyLength = kHFSPlusCatalogKeyMinimumLength + len;

	btRecord.bufferAddress = &rec;
	btRecord.itemCount = 1;
	btRecord.itemSize = sizeof(rec);
	
	result = BTSearchRecord(fcb, &btIterator, kInvalidMRUCacheKey,
			&btRecord, &recSize, &btIterator);
	if (result)
		return (IntError(GPtr, result));

	if (rec.recordType != kHFSPlusFileRecord)
		return (noErr);

	if (p->type == E_PEOF) {
		bytes = p->correct * (UInt64)GPtr->calculatedVCB->vcbBlockSize;
		if ((p->forkType == kRsrcFork) &&
		    ((UInt32)p->incorrect == rec.hfsPlusFile.resourceFork.totalBlocks)) {

			rec.hfsPlusFile.resourceFork.totalBlocks = (UInt32)p->correct;
			replace = true;
			/*
			 * Make sure our new block count is large
			 * enough to cover the current LEOF.  If
			 * its not we must truncate the fork.
			 */
			if (rec.hfsPlusFile.resourceFork.logicalSize > bytes) {
				rec.hfsPlusFile.resourceFork.logicalSize = bytes;
			}
		} else if ((p->forkType == kDataFork) &&
		           ((UInt32)p->incorrect == rec.hfsPlusFile.dataFork.totalBlocks)) {

			rec.hfsPlusFile.dataFork.totalBlocks = (UInt32)p->correct;
			replace = true;
			/*
			 * Make sure our new block count is large
			 * enough to cover the current LEOF.  If
			 * its not we must truncate the fork.
			 */
			if (rec.hfsPlusFile.dataFork.logicalSize > bytes) {
				rec.hfsPlusFile.dataFork.logicalSize = bytes;
			}
		}
	} else /* E_LEOF */ {
		if ((p->forkType == kRsrcFork) &&
		    (p->incorrect == rec.hfsPlusFile.resourceFork.logicalSize)) {

			rec.hfsPlusFile.resourceFork.logicalSize = p->correct;
			replace = true;

		} else if ((p->forkType == kDataFork) &&
		           (p->incorrect == rec.hfsPlusFile.dataFork.logicalSize)) {

			rec.hfsPlusFile.dataFork.logicalSize = p->correct;
			replace = true;
		}
	}

	if (replace) {
		result = BTReplaceRecord(fcb, &btIterator, &btRecord, recSize);
		if (result)
			return (IntError(GPtr, result));
	}
		
	return (noErr);
}

/*------------------------------------------------------------------------------

Routine:	FixEmbededVolDescription

Function:	If the "mdb->drAlBlSt" field has been modified, i.e. Norton Disk Doctor
			3.5 tried to "Fix" an HFS+ volume, it reduces the value in the 
			"mdb->drAlBlSt" field.  If this field is changed, the file system can 
			no longer find the VolumeHeader or AltVolumeHeader.
			
Input:		GPtr			-	pointer to scavenger global area
			p				- 	pointer to the repair order

Output:		FixMDBdrAlBlSt	- 	function result:
									0 = no error
									n = error
------------------------------------------------------------------------------*/

static	OSErr	FixEmbededVolDescription( SGlobPtr GPtr, RepairOrderPtr p )
{
	OSErr					err;
	HFSMasterDirectoryBlock	*mdb;
	EmbededVolDescription	*desc;
	SVCB					*vcb = GPtr->calculatedVCB;
	BlockDescriptor  		block;

	desc = (EmbededVolDescription *) &(p->name);
	block.buffer = NULL;
	
	/* Fix the Alternate MDB */
	err = GetVolumeObjectAlternateMDB( &block );
	if ( err != noErr )
		goto ExitThisRoutine;
	mdb = (HFSMasterDirectoryBlock *) block.buffer;
	
	mdb->drAlBlSt			= desc->drAlBlSt;
	mdb->drEmbedSigWord		= desc->drEmbedSigWord;
	mdb->drEmbedExtent.startBlock	= desc->drEmbedExtent.startBlock;
	mdb->drEmbedExtent.blockCount	= desc->drEmbedExtent.blockCount;
	
	err = ReleaseVolumeBlock( vcb, &block, kForceWriteBlock );
	block.buffer = NULL;
	if ( err != noErr )
		goto ExitThisRoutine;
	
	/* Fix the MDB */
	err = GetVolumeObjectPrimaryMDB( &block );
	if ( err != noErr )
		goto ExitThisRoutine;
	mdb = (HFSMasterDirectoryBlock *) block.buffer;
	
	mdb->drAlBlSt			= desc->drAlBlSt;
	mdb->drEmbedSigWord		= desc->drEmbedSigWord;
	mdb->drEmbedExtent.startBlock	= desc->drEmbedExtent.startBlock;
	mdb->drEmbedExtent.blockCount	= desc->drEmbedExtent.blockCount;
	err = ReleaseVolumeBlock( vcb, &block, kForceWriteBlock );
	block.buffer = NULL;
	
ExitThisRoutine:
	if ( block.buffer != NULL )
		err = ReleaseVolumeBlock( vcb, &block, kReleaseBlock );
	
	return( err );
}




/*------------------------------------------------------------------------------

Routine:	FixWrapperExtents

Function:	When Norton Disk Doctor 2.0 tries to repair an HFS Plus volume, it
			assumes that the first catalog extent must be a fixed number of
			allocation blocks after the start of the first extents extent (in the
			wrapper).  In reality, the first catalog extent should start immediately
			after the first extents extent.
			
Input:		GPtr			-	pointer to scavenger global area
			p				- 	pointer to the repair order

Output:
			0 = no error
			n = error
------------------------------------------------------------------------------*/

static	OSErr	FixWrapperExtents( SGlobPtr GPtr, RepairOrderPtr p )
{
#if !LINUX
#pragma unused (p)
#endif

	OSErr						err;
	HFSMasterDirectoryBlock		*mdb;
	SVCB						*vcb = GPtr->calculatedVCB;
	BlockDescriptor  			block;

	/* Get the Alternate MDB */
	block.buffer = NULL;
	err = GetVolumeObjectAlternateMDB( &block );
	if ( err != noErr )
		goto ExitThisRoutine;
	mdb = (HFSMasterDirectoryBlock	*) block.buffer;

	/* Fix the wrapper catalog's first (and only) extent */
	mdb->drCTExtRec[0].startBlock = mdb->drXTExtRec[0].startBlock +
	                                mdb->drXTExtRec[0].blockCount;
	
	err = ReleaseVolumeBlock(vcb, &block, kForceWriteBlock);
	block.buffer = NULL;
	if ( err != noErr )
		goto ExitThisRoutine;
	
	/* Fix the MDB */
	err = GetVolumeObjectPrimaryMDB( &block );
	if ( err != noErr )
		goto ExitThisRoutine;
	mdb = (HFSMasterDirectoryBlock	*) block.buffer;
	
	mdb->drCTExtRec[0].startBlock = mdb->drXTExtRec[0].startBlock +
	                                mdb->drXTExtRec[0].blockCount;
	
	err = ReleaseVolumeBlock(vcb, &block, kForceWriteBlock);
	block.buffer = NULL;

ExitThisRoutine:
	if ( block.buffer != NULL )
		(void) ReleaseVolumeBlock( vcb, &block, kReleaseBlock );
	
	return( err );
}


//
//	Entries in the extents BTree which do not have a corresponding catalog entry get fixed here
//	This routine will run slowly if the extents file is large because we require a Catalog BTree
//	search for each extent record.
//
static	OSErr	FixOrphanedExtent( SGlobPtr GPtr )
{
#if 0
	OSErr				err;
	UInt32				hint;
	UInt32				recordSize;
	UInt32				maxRecords;
	UInt32				numberOfFilesInList;
	ExtentKey			*extentKeyPtr;
	ExtentRecord		*extentDataPtr;
	ExtentRecord		extents;
	ExtentRecord		zeroExtents;
	CatalogKey			foundExtentKey;
	CatalogRecord		catalogData;
	CatalogRecord		threadData;
	HFSCatalogNodeID	fileID;
	BTScanState			scanState;

	HFSCatalogNodeID	lastFileID			= -1;
	UInt32			recordsFound		= 0;
	Boolean			mustRebuildBTree	= false;
	Boolean			isHFSPlus;
	SVCB			*calculatedVCB		= GPtr->calculatedVCB;
	UInt32			**dataHandle		= GPtr->validFilesList;
	SFCB *			fcb = GPtr->calculatedExtentsFCB;

	//	Set Up
	isHFSPlus = VolumeObjectIsHFSPlus( );
	//
	//	Use the BTree scanner since we use MountCheck to find orphaned extents, and MountCheck uses the scanner
	err = BTScanInitialize( fcb, 0, 0, 0, gFSBufferPtr, gFSBufferSize, &scanState );
	if ( err != noErr )	return( badMDBErr );

	ClearMemory( (Ptr)&zeroExtents, sizeof(ExtentRecord) );

	if ( isHFSPlus )
	{
		maxRecords = fcb->fcbLogicalSize / sizeof(HFSPlusExtentRecord);
	}
	else
	{
		maxRecords = fcb->fcbLogicalSize / sizeof(HFSExtentRecord);
		numberOfFilesInList = GetHandleSize((Handle) dataHandle) / sizeof(UInt32);
		qsort( *dataHandle, numberOfFilesInList, sizeof (UInt32), cmpLongs );	// Sort the list of found file IDs
	}


	while ( recordsFound < maxRecords )
	{
		err = BTScanNextRecord( &scanState, false, (void **) &extentKeyPtr, (void **) &extentDataPtr, &recordSize );

		if ( err != noErr )
		{
			if ( err == btNotFound )
				err	= noErr;
			break;
		}

		++recordsFound;
		fileID = (isHFSPlus == true) ? extentKeyPtr->hfsPlus.fileID : extentKeyPtr->hfs.fileID;
		
		if ( (fileID > kHFSBadBlockFileID) && (lastFileID != fileID) )	// Keep us out of reserved file trouble
		{
			lastFileID	= fileID;
			
			if ( isHFSPlus )
			{
				err = LocateCatalogThread( calculatedVCB, fileID, &threadData, (UInt16*)&recordSize, &hint );	//	This call returns nodeName as either Str31 or HFSUniStr255, no need to call PrepareInputName()
				
				if ( err == noErr )									//	Thread is found, just verify actual record exists.
				{
					err = LocateCatalogNode( calculatedVCB, threadData.hfsPlusThread.parentID, (const CatalogName *) &(threadData.hfsPlusThread.nodeName), kNoHint, &foundExtentKey, &catalogData, &hint );
				}
				else if ( err == cmNotFound )
				{
					err = SearchBTreeRecord( GPtr->calculatedExtentsFCB, extentKeyPtr, kNoHint, &foundExtentKey, &extents, (UInt16*)&recordSize, &hint );
					if ( err == noErr )
					{	//�� can't we just delete btree record?
						err = ReplaceBTreeRecord( GPtr->calculatedExtentsFCB, &foundExtentKey, hint, &zeroExtents, recordSize, &hint );
						err	= DeleteBTreeRecord( GPtr->calculatedExtentsFCB, &foundExtentKey );	//	Delete the orphaned extent
					}
				}
					
				if ( err != noErr )
					mustRebuildBTree	= true;						//	if we have errors here we should rebuild the extents btree
			}
			else
			{
				if ( ! bsearch( &fileID, *dataHandle, numberOfFilesInList, sizeof(UInt32), cmpLongs ) )
				{
					err = SearchBTreeRecord( GPtr->calculatedExtentsFCB, extentKeyPtr, kNoHint, &foundExtentKey, &extents, (UInt16*)&recordSize, &hint );
					if ( err == noErr )
					{	//�� can't we just delete btree record?
						err = ReplaceBTreeRecord( GPtr->calculatedExtentsFCB, &foundExtentKey, hint, &zeroExtents, recordSize, &hint );
						err = DeleteBTreeRecord( GPtr->calculatedExtentsFCB, &foundExtentKey );	//	Delete the orphaned extent
					}
					
					if ( err != noErr )
						mustRebuildBTree	= true;						//	if we have errors here we should rebuild the extents btree
				}
			}
		}
	}

	if ( mustRebuildBTree == true )
	{
		GPtr->EBTStat |= S_RebuildBTree;
		err	= errRebuildBtree;
	}

	return( err );
#else
	return (0);
#endif
}

/* Function: FixAttrSize
 *
 * Description: 
 * Fixes the incorrect block count or attribute size for extended attribute 
 * detected during verify stage.  This is a minor repair order function 
 * i.e. it depends on previously created repair order to repair the disk.
 *
 * Input:
 *	GPtr - global scavenger structure pointer
 *	p - current repair order
 *
 * Output:
 *	result - zero indicates success, non-zero failure.
 */
static OSErr FixAttrSize(SGlobPtr GPtr, RepairOrderPtr p)
{
	OSErr result = noErr;
	HFSPlusAttrKey *key;
	HFSPlusAttrRecord record;
	BTreeIterator iterator;
	FSBufferDescriptor btRecord;
	u_int16_t recSize;
	u_int64_t bytes;
	Boolean doReplace = false;

	/* Initialize the iterator, attribute key, and attribute record */
	ClearMemory(&iterator, sizeof(iterator));
	key = (HFSPlusAttrKey *)&iterator.key;
	BuildAttributeKey(p->parid, 0, &p->name[1], p->name[0], key);

	btRecord.bufferAddress = &record;
	btRecord.itemCount = 1;
	btRecord.itemSize = sizeof(record);

	/* Search for the attribute record.
	 * Warning: Attribute record of type kHFSPlusAttrInlineData may be 
	 * truncated on read! (4425232).  This function only uses recordType 
	 * field from inline attribute record.
	 */
	result = BTSearchRecord(GPtr->calculatedAttributesFCB, &iterator, 
				kInvalidMRUCacheKey, &btRecord, &recSize, &iterator);
	if (result) {
		dbg_printf (d_error|d_xattr, "%s: Cannot find attribute record (err = %d)\n", __FUNCTION__, result);
		goto out;
	}

	/* We should only get record of type kHFSPlusAttrForkData */
	if (record.recordType != kHFSPlusAttrForkData) {
		dbg_printf (d_error|d_xattr, "%s: Record found is not attribute fork data\n", __FUNCTION__);
		result = btNotFound;
		goto out;
	}

	/* Manipulate necessary fields in the attribute record */
	if (p->type == E_PEOAttr) {
		if ((u_int32_t)p->incorrect == record.forkData.theFork.totalBlocks) {
			record.forkData.theFork.totalBlocks = (u_int32_t)p->correct;	
			doReplace = true;

			/* Make sure that new block count is large enough to 
			 * cover the current LEOAttr.  If not, truncate it. 
			 */
			bytes = p->correct * (u_int64_t)GPtr->calculatedVCB->vcbBlockSize;
			if (record.forkData.theFork.logicalSize > bytes) {
				record.forkData.theFork.logicalSize = bytes;
			}
		}
	} else if (p->type == E_LEOAttr) {
		if (p->incorrect == record.forkData.theFork.logicalSize) {
			record.forkData.theFork.logicalSize = p->correct;
			doReplace = true;
		}
	}

	/* Replace the attribute record, if required */
	if (doReplace == true) {
		result = BTReplaceRecord(GPtr->calculatedAttributesFCB, &iterator,
					&btRecord, recSize);
		if (result) {
			dbg_printf (d_error|d_xattr, "%s: Cannot replace attribute record (err=%d)\n", __FUNCTION__, result);
			goto out;
		}
	}

out:
	return(result);
}

/* Function: FixBadExtent
 *
 * Description:  The function repairs bad extent entry by zeroing out the
 * bad extent entry and truncating all extent information found after the
 * bad extent entry.
 *
 *	1. The information for repair is retrieved from the repair order passed
 *	   as parameter.
 *	2. If the start block of bad extent is zero, bad extent existed in 
 *	   catalog record extent information.  Lookup the catalog record, zero
 *	   out bad extent entry and all entries after it and update the catalog
 *	   record.
 *	3. If the start block of bad extent is non-zero, bad extent existed
 *	   in overflow extent.  If the index of bad extent is zero, we want
 *	   to delete the record completely.  If the index is non-zero, search
 *	   the extent record, zero out bad extent entry and all entries after it
 *	   and update the extent record.
 *	4. Search for any extent record in the overflow extent after the 
 *	   the bad extent entry.  If found, delete the record.
 *	5. If the file was truncated, create symlink in DamagedFiles folder
 * 	   and display message to the user.
 *
 * Input:
 *	GPtr - global scavenger structure pointer
 *	p - current repair order
 *
 * Output:
 *	result - zero indicates success, non-zero failure.
 */
static OSErr FixBadExtent(SGlobPtr GPtr, RepairOrderPtr p)
{	
	OSErr err = noErr;
	UInt32 badExtentIndex;
	UInt32 extentStartBlock, foundStartBlock;
	UInt32 fileID;
	int i;
	UInt8 forkType;

	UInt16 recordSize;
	ExtentRecord extentRecord;
	ExtentKey extentKey;
	UInt32 hint;
	Boolean isHFSPlus;
	Boolean didRepair;

	fileID = p->parid;
	badExtentIndex = p->correct;
	extentStartBlock = p->hint;
	forkType = p->forkType;

	isHFSPlus = VolumeObjectIsHFSPlus();
	didRepair = false;

	assert (forkType != kEAData);

	/* extentStartBlock = 0, the bad extent exists in catalog record */
	if (extentStartBlock == 0) {

		CatalogRecord catRecord; 
		CatalogKey catKey;
		HFSPlusExtentDescriptor *hfsPlusExtent;
		HFSExtentDescriptor *hfsExtent;

		/* Lookup record in catalog BTree */
		err = GetCatalogRecord(GPtr, fileID, isHFSPlus, &catKey, &catRecord, &recordSize);
		if (err) {
			goto out;
		}

		/* Check record type */
		assert ((catRecord.recordType == kHFSPlusFileRecord) || 
				(catRecord.recordType == kHFSFileRecord));

		/* Zero out the bad extent entry and all entries after it */
		if (isHFSPlus) {
			if (forkType == kDataFork) {
				hfsPlusExtent = catRecord.hfsPlusFile.dataFork.extents;
			} else {
				hfsPlusExtent = catRecord.hfsPlusFile.resourceFork.extents;
			}
				
			for (i = badExtentIndex; i < GPtr->numExtents; i++) {
				hfsPlusExtent[i].startBlock = 0;
				hfsPlusExtent[i].blockCount = 0;
			}
		} else {
			if (forkType == kDataFork) {
				hfsExtent = catRecord.hfsFile.dataExtents;
			} else {
				hfsExtent = catRecord.hfsFile.rsrcExtents;
			}
			for (i = badExtentIndex; i < GPtr->numExtents; i++) {
				hfsExtent[i].startBlock = 0;
				hfsExtent[i].blockCount = 0;
			}
		}

		/* Write the catalog record back */
		err = ReplaceBTreeRecord(GPtr->calculatedCatalogFCB, &catKey, kNoHint, 
								&catRecord, recordSize, &hint);
		if (err) {
			goto out;
		}
		didRepair = true;

	} else { /* bad extent exists in overflow extent record */

		/* First entry in overflow extent record is bad, delete entire record */
		if (badExtentIndex == 0) {
			goto del_overflow_extents;
		}

		/* Lookup record in extents overflow BTree */ 
		BuildExtentKey (isHFSPlus, forkType, fileID, extentStartBlock, &extentKey);
		err = SearchBTreeRecord (GPtr->calculatedExtentsFCB, &extentKey, kNoHint, 
								 &extentKey, &extentRecord, &recordSize, &hint);
		if (err) {
			goto out;
		}

		/* Zero out the bad extent entry and all entries after it */
		if (isHFSPlus) {
			for (i = badExtentIndex; i < GPtr->numExtents; i++) {
				extentRecord.hfsPlus[i].startBlock = 0;
				extentRecord.hfsPlus[i].blockCount = 0;
			}
		} else {
			for (i = badExtentIndex; i < GPtr->numExtents; i++) {
				extentRecord.hfs[i].startBlock = 0;
				extentRecord.hfs[i].blockCount = 0;
			}
		}

		/* Write the extent record back */
		err = ReplaceBTreeRecord(GPtr->calculatedExtentsFCB, &extentKey, hint,
								&extentRecord, recordSize, &hint);
		if (err) {
			goto out;
		}
		didRepair = true;

		/* The startBlock for extent record with bad extent entry is updated
		 * because we use this startBlock later to lookup next extent record 
		 * for this file and forktype in overflow extent btree which should
		 * be deleted.  By incrementing the startBlock by one, we ensure that
		 * we find the next record, if any, that should be deleted instead of 
		 * finding the same record that was updated above.
		 */
		extentStartBlock++;
	}
	
del_overflow_extents:
	/* Search for overflow extent records.  We should get a valid record only 
	 * if the bad extent entry was the the first entry in the extent overflow 
	 * record.  For all other cases, the search record will return an error 
	 */
	BuildExtentKey (isHFSPlus, forkType, fileID, extentStartBlock, &extentKey);
	err = SearchBTreeRecord (GPtr->calculatedExtentsFCB, &extentKey, kNoHint, 
							&extentKey, &extentRecord, &recordSize, &hint);
	if ((err != noErr) && (err != btNotFound)) {
		goto create_symlink;
	}

	/* If we got error, check the next record */
	if (err == btNotFound) {
		err = GetBTreeRecord(GPtr->calculatedExtentsFCB, 1, &extentKey, &extentRecord, 
							&recordSize, &hint);
	}

	while (err == noErr) {
		/* Check if the record has correct fileID, forkType */
		if (isHFSPlus) {
			if ((fileID != extentKey.hfsPlus.fileID) ||
				(forkType != extentKey.hfsPlus.forkType)) {
				break;
			}
			foundStartBlock = extentKey.hfsPlus.startBlock;
		} else {
			if ((fileID != extentKey.hfs.fileID) ||
				(forkType != extentKey.hfs.forkType)) {
				break;
			}
			foundStartBlock = extentKey.hfs.startBlock;
		}

		/* Delete the extent record */ 
		err = DeleteBTreeRecord(GPtr->calculatedExtentsFCB, &extentKey);
		dbg_printf (d_info, "%s: Deleting extent overflow for fileID=%u, forkType=%u, startBlock=%u\n", __FUNCTION__, fileID, forkType, foundStartBlock);
		if (err) {
			goto create_symlink;
		}
		didRepair = true;

		/* Get the next extent record */
		err = GetBTreeRecord(GPtr->calculatedExtentsFCB, 1, &extentKey, &extentRecord, 
							&recordSize, &hint);
	}

	if (err == btNotFound) {
		err = noErr;
	}

	UpdateBTreeHeader(GPtr->calculatedExtentsFCB);

create_symlink:
	/* Create symlink for repaired files in damaged files folder */
	if (didRepair == true) {
		/* Create symlink for damaged files */
		(void) CreateCorruptFileSymlink(GPtr, fileID);
	}

out:
	return err;
}

/* Function: FixOrphanedFiles
 *
 * Description:
 *	Incorrect number of thread records get fixed in this function.
 *
 *	The function traverses the entire catalog Btree.  
 *
 *	For a file/folder record, it tries to lookup its corresponding thread
 *	record.  If the thread record does not exist, or is not correct, a new 
 *	thread record is created.  The parent ID and the name of the file/folder 
 *	are compared for correctness. 
 *	For plain HFS, a thread record is only looked-up if kHFSThreadExistsMask is set.
 *
 *	For a thread record, it tries to lookup its corresponding file/folder 
 *	record.  If its does not exist or is not correct, the thread record
 *	is deleted.  The file/folder ID is compared for correctness.
 *
 * Input:	1. GPtr - pointer to global scavenger area
 * 
 * Return value:	
 * 		      zero means success
 *		      non-zero means failure
 */
static	OSErr	FixOrphanedFiles ( SGlobPtr GPtr )
{
	CatalogKey			key;
	CatalogKey			foundKey;
	CatalogKey			tempKey;
	CatalogRecord		record;
	CatalogRecord		threadRecord;
	CatalogRecord		record2;
	HFSCatalogNodeID	parentID;
	HFSCatalogNodeID	cNodeID = 0;
	BTreeIterator		savedIterator;
	UInt32				hint;
	UInt32				hint2;
	UInt32				threadHint;
	OSErr				err;
	UInt16				recordSize;
	SInt16				recordType;
	SInt16				selCode				= 0x8001;	/* Get first record */
	Boolean				isHFSPlus;
	BTreeControlBlock	*btcb				= GetBTreeControlBlock( kCalculatedCatalogRefNum );

	isHFSPlus = VolumeObjectIsHFSPlus( );
	CopyMemory( &btcb->lastIterator, &savedIterator, sizeof(BTreeIterator) );

	do
	{
		//	Save/Restore Iterator around calls to GetBTreeRecord
		CopyMemory( &savedIterator, &btcb->lastIterator, sizeof(BTreeIterator) );
		err = GetBTreeRecord( GPtr->calculatedCatalogFCB, selCode, &foundKey, &record, &recordSize, &hint );
		if ( err != noErr ) break;
		CopyMemory( &btcb->lastIterator, &savedIterator, sizeof(BTreeIterator) );
	
		selCode		= 1;	//	 kNextRecord			
		recordType	= record.recordType;
		
		switch( recordType )
		{
			case kHFSFileRecord:
				//	If the small file is not supposed to have a thread, just break
				if ( ( record.hfsFile.flags & kHFSThreadExistsMask ) == 0 )
					break;
			
			case kHFSFolderRecord:
			case kHFSPlusFolderRecord:
			case kHFSPlusFileRecord:
				
				//	Locate the thread associated with this record
				
				(void) CheckForStop( GPtr );		//	rotate cursor

				parentID	= isHFSPlus == true ? foundKey.hfsPlus.parentID : foundKey.hfs.parentID;
				threadHint	= hint;
				
				switch( recordType )
				{
					case kHFSFolderRecord:		cNodeID		= record.hfsFolder.folderID;		break;
					case kHFSFileRecord:		cNodeID		= record.hfsFile.fileID;			break;
					case kHFSPlusFolderRecord:	cNodeID		= record.hfsPlusFolder.folderID;	break;
					case kHFSPlusFileRecord:	cNodeID		= record.hfsPlusFile.fileID;		break;
				}

				//-- Build the key for the file thread
				BuildCatalogKey(cNodeID, NULL, isHFSPlus, &key);

				err = SearchBTreeRecord( GPtr->calculatedCatalogFCB, &key, kNoHint, 
										 &tempKey, &threadRecord, &recordSize, &hint2 );

				/* We found a thread record for this file/folder record. */
				if (err == noErr) {
					/* Check if the parent ID and nodeName are same.  If not, we are 
					 * missing a correct thread record.  Force btNotFound in such case.
					 */
					if (isHFSPlus) {
						/* Compare parent ID */
						if (parentID != threadRecord.hfsPlusThread.parentID) {
							(void) DeleteBTreeRecord(GPtr->calculatedCatalogFCB, &tempKey);
							err = btNotFound;
							if (GPtr->logLevel >= kDebugLog) {
								printf ("\t%s: parentID for id=%u do not match (fileKey=%u threadRecord=%u)\n", __FUNCTION__, cNodeID, parentID, threadRecord.hfsPlusThread.parentID);
							}
						}

						/* Compare nodeName from file/folder key and thread record */
						if (!((foundKey.hfsPlus.nodeName.length == threadRecord.hfsPlusThread.nodeName.length) 
						    && (!bcmp(foundKey.hfsPlus.nodeName.unicode, 
								      threadRecord.hfsPlusThread.nodeName.unicode,
									  foundKey.hfsPlus.nodeName.length * 2)))) {
							(void) DeleteBTreeRecord(GPtr->calculatedCatalogFCB, &tempKey);
							err = btNotFound;
							if (GPtr->logLevel >= kDebugLog) {
								printf ("\t%s: nodeName for id=%u do not match\n", __FUNCTION__, cNodeID);
							}
						}
					} else {
						/* Compare parent ID */
						if (parentID != threadRecord.hfsThread.parentID) {
							(void) DeleteBTreeRecord(GPtr->calculatedCatalogFCB, &tempKey);
							err = btNotFound;
							if (GPtr->logLevel >= kDebugLog) {
								printf ("\t%s: parentID for id=%u do not match (fileKey=%u threadRecord=%u)\n", __FUNCTION__, cNodeID, parentID, threadRecord.hfsThread.parentID);
							}
						}

						/* Compare nodeName from file/folder key and thread record */
						if (!((foundKey.hfs.nodeName[0] == threadRecord.hfsThread.nodeName[0]) 
						    && (!bcmp(&foundKey.hfs.nodeName[1], 
								      &threadRecord.hfsThread.nodeName[1],
									  foundKey.hfs.nodeName[0])))) {
							(void) DeleteBTreeRecord(GPtr->calculatedCatalogFCB, &tempKey);
							err = btNotFound;
							if (GPtr->logLevel >= kDebugLog) {
								printf ("\t%s: nodeName for id=%u do not match\n", __FUNCTION__, cNodeID);
							}
						}
					}
				} /* err == noErr */ 

				//	For missing thread records, just create the thread
				if ( err == btNotFound )
				{
					//	Create the missing thread record.
					Boolean		isDirectory;
					
					isDirectory = false;
					switch( recordType )
					{
						case kHFSFolderRecord:
						case kHFSPlusFolderRecord:	
							isDirectory = true;		
							break;
					}

					//-- Fill out the data for the new file thread from the key 
					// of catalog file/folder record
					recordSize = BuildThreadRec( &foundKey, &threadRecord, isHFSPlus, 
												 isDirectory );
					err = InsertBTreeRecord( GPtr->calculatedCatalogFCB, &key,
											 &threadRecord, recordSize, &threadHint );
					if (GPtr->logLevel >= kDebugLog) {
						printf ("\t%s: Created thread record for id=%u (err=%u)\n", __FUNCTION__, cNodeID, err);
					}
				}
			
				break;
			
			
			case kHFSFolderThreadRecord:
			case kHFSFileThreadRecord:
			case kHFSPlusFolderThreadRecord:
			case kHFSPlusFileThreadRecord:
				
				//	Find the catalog record, if it does not exist, delete the existing thread.
				if ( isHFSPlus )
					BuildCatalogKey( record.hfsPlusThread.parentID, (const CatalogName *)&record.hfsPlusThread.nodeName, isHFSPlus, &key );
				else
					BuildCatalogKey( record.hfsThread.parentID, (const CatalogName *)&record.hfsThread.nodeName, isHFSPlus, &key );
				
				err = SearchBTreeRecord ( GPtr->calculatedCatalogFCB, &key, kNoHint, &tempKey, &record2, &recordSize, &hint2 );

				/* We found a file/folder record for this thread record. */
				if (err == noErr) {
					/* Check if the file/folder ID are same.  If not, we are missing a 
					 * correct file/folder record.  Delete the extra thread record
					 */
					if (isHFSPlus) {
						/* Compare file/folder ID */
						if (foundKey.hfsPlus.parentID != record2.hfsPlusFile.fileID) {
							err = btNotFound;
							if (GPtr->logLevel >= kDebugLog) {
								printf ("\t%s: fileID do not match (threadKey=%u fileRecord=%u), parentID=%u\n", __FUNCTION__, foundKey.hfsPlus.parentID, record2.hfsPlusFile.fileID, record.hfsPlusThread.parentID);
							}
						}
					} else {
						/* Compare file/folder ID */
						if (foundKey.hfs.parentID != record2.hfsFile.fileID) {
							err = btNotFound;
							if (GPtr->logLevel >= kDebugLog) {
								if (recordType == kHFSFolderThreadRecord) {
									printf ("\t%s: fileID do not match (threadKey=%u fileRecord=%u), parentID=%u\n", __FUNCTION__, foundKey.hfs.parentID, record2.hfsFolder.folderID, record.hfsThread.parentID);
								} else {
									printf ("\t%s: fileID do not match (threadKey=%u fileRecord=%u), parentID=%u\n", __FUNCTION__, foundKey.hfs.parentID, record2.hfsFile.fileID, record.hfsThread.parentID);
								}
							}
						}
					}
				} /* if (err == noErr) */

				if ( err != noErr )
				{
					err = DeleteBTreeRecord( GPtr->calculatedCatalogFCB, &foundKey );
					if (GPtr->logLevel >= kDebugLog) {
						if (isHFSPlus) {
							printf ("\t%s: Deleted thread record for id=%d (err=%d)\n", __FUNCTION__, foundKey.hfsPlus.parentID, err);
						} else {
							printf ("\t%s: Deleted thread record for id=%d (err=%d)\n", __FUNCTION__, foundKey.hfs.parentID, err);
						}
					}
				}
				
				break;
				
			default:
				if (GPtr->logLevel >= kDebugLog) {
					printf ("\t%s: Unknown record type.\n", __FUNCTION__);
				}
				break;

		}
	} while ( err == noErr );

	if ( err == btNotFound )
		err = noErr;				 						//	all done, no more catalog records

//	if (err == noErr)
//		err = BTFlushPath( GPtr->calculatedCatalogFCB );

	return( err );
}


static	OSErr	RepairReservedBTreeFields ( SGlobPtr GPtr )
{
	CatalogRecord		record;
	CatalogKey			foundKey;
	UInt16 				recordSize;
	SInt16				selCode;
	UInt32				hint;
	UInt32				*reserved;
	OSErr				err;

	selCode = 0x8001;															//	 start with 1st record			

	err = GetBTreeRecord( GPtr->calculatedCatalogFCB, selCode, &foundKey, &record, &recordSize, &hint );
	if ( err != noErr ) goto EXIT;

	selCode = 1;																//	 get next record from now on		
	
	do
	{
		switch( record.recordType )
		{
			case kHFSPlusFolderRecord:
				if ( record.hfsPlusFolder.flags != 0 )
				{
					record.hfsPlusFolder.flags = 0;
					err = ReplaceBTreeRecord( GPtr->calculatedCatalogFCB, &foundKey, hint, &record, recordSize, &hint );
				}
				break;
				
			case kHFSPlusFileRecord:
				//	Note: bit 7 (mask 0x80) of flags is unused in HFS or HFS Plus.  However, Inside Macintosh: Files
				//	describes it as meaning the file record is in use.  Some non-Apple implementations end up setting
				//	this bit, so we just ignore it.
				if ( ( record.hfsPlusFile.flags  & (UInt16) ~(0X83) ) != 0 )
				{
					record.hfsPlusFile.flags &= 0X83;
					err = ReplaceBTreeRecord( GPtr->calculatedCatalogFCB, &foundKey, hint, &record, recordSize, &hint );
				}
				break;

			case kHFSFolderRecord:
				if ( record.hfsFolder.flags != 0 )
				{
					record.hfsFolder.flags = 0;
					err = ReplaceBTreeRecord( GPtr->calculatedCatalogFCB, &foundKey, hint, &record, recordSize, &hint );
				}
				break;

			case kHFSFolderThreadRecord:
			case kHFSFileThreadRecord:
				reserved = (UInt32*) &(record.hfsThread.reserved);
				if ( reserved[0] || reserved[1] )
				{
					reserved[0]	= 0;
					reserved[1]	= 0;
					err = ReplaceBTreeRecord( GPtr->calculatedCatalogFCB, &foundKey, hint, &record, recordSize, &hint );
				}
				break;

			case kHFSFileRecord:
				//	Note: bit 7 (mask 0x80) of flags is unused in HFS or HFS Plus.  However, Inside Macintosh: Files
				//	describes it as meaning the file record is in use.  Some non-Apple implementations end up setting
				//	this bit, so we just ignore it.
				if ( 	( ( record.hfsFile.flags  & (UInt8) ~(0X83) ) != 0 )
					||	( record.hfsFile.dataStartBlock != 0 )	
					||	( record.hfsFile.rsrcStartBlock != 0 )	
					||	( record.hfsFile.reserved != 0 )			)
				{
					record.hfsFile.flags			&= 0X83;
					record.hfsFile.dataStartBlock	= 0;
					record.hfsFile.rsrcStartBlock	= 0;
					record.hfsFile.reserved		= 0;
					err = ReplaceBTreeRecord( GPtr->calculatedCatalogFCB, &foundKey, hint, &record, recordSize, &hint );
				}
				break;
				
			default:
				break;
		}

		if ( err != noErr ) goto EXIT;
		
		err = GetBTreeRecord( GPtr->calculatedCatalogFCB, selCode, &foundKey, &record, &recordSize, &hint );
	
	} while ( err == noErr );

	if ( err == btNotFound )
		err = noErr;				 						//	all done, no more catalog records

EXIT:
	return( err );
}


/* Function: FixOrphanAttrRecord
 *
 * Description:
 * The function traverses the attribute BTree completely and for every 
 * leaf record, calls CheckAttributeRecord.  CheckAttributeRecord function
 * is common function for verify and repair stage.  CheckAttributeRecord 
 * deletes invalid/orphaned extended attribute records under following 
 * conditions - 
 *	1. record is overflow extents with no valid fork data or overflow extents
 *	preceeding it.
 *	2. record type is unknown.
 *
 * Input:
 * 	GPtr - global scavenger structure pointer
 *
 * Output:
 *	error code - zero on success, non-zero on failure.
 */
static OSErr FixOrphanAttrRecord(SGlobPtr GPtr)
{
	OSErr err = noErr;
	UInt16 selCode;
	UInt32 hint;

	HFSPlusAttrRecord record;
	HFSPlusAttrKey key;
	UInt16 recordSize;

	/* Zero out last attribute information from global scavenger structure */
	bzero (&(GPtr->lastAttrInfo), sizeof(GPtr->lastAttrInfo));

	/* Warning: Attribute record of type kHFSPlusAttrInlineData may be 
	 * truncated on read! (4425232).  CheckAttributeRecord only uses recordType 
	 * field from inline attribute record.
	 */
	selCode = 0x8001;
	err = GetBTreeRecord(GPtr->calculatedAttributesFCB, selCode, &key, 
			&record, &recordSize, &hint);
	if (err != noErr) {
		goto out;
	}

	selCode = 1;
	do {
		err = CheckAttributeRecord(GPtr, &key, &record, recordSize);
		if (err) {
			break;
		}

		/* Access the next record.
		 * Warning: Attribute record of type kHFSPlusAttrInlineData may be 
	 	 * truncated on read! (4425232).  CheckAttributeRecord only uses recordType 
		 * field from inline attribute record.
	 	 */
		err = GetBTreeRecord(GPtr->calculatedAttributesFCB, selCode, &key, 
				&record, &recordSize, &hint);
	} while (err == noErr);

	if (err == btNotFound) {
		err = noErr;
	}

out:
	return(err);
}

/* Function:	GetCatalogRecord
 *
 * Description:
 * This function returns a catalog file/folder record for a given
 * file/folder ID from the catalog BTree.
 *
 * Input:	1. GPtr - pointer to global scavenger area
 *        	2. fileID - file ID to search the file/folder record  
 *      	3. isHFSPlus - boolean value to indicate if volume is HFSPlus 
 *
 * Output:	1. catKey - catalog key
 *        	2. catRecord - catalog record for given ID
 *         	3. recordSize - size of catalog record return back 
 *
 * Return value:	
 * 		      zero means success
 *		      non-zero means failure
 */
static OSErr GetCatalogRecord(SGlobPtr GPtr, UInt32 fileID, Boolean isHFSPlus, CatalogKey *catKey, CatalogRecord *catRecord, UInt16 *recordSize) 
{
	OSErr err = noErr;
	CatalogKey catThreadKey;
	CatalogName catalogName;
	UInt32 hint;

	/* Look up for catalog thread record for the file that owns attribute */
	BuildCatalogKey(fileID, NULL, isHFSPlus, &catThreadKey);
	err = SearchBTreeRecord(GPtr->calculatedCatalogFCB, &catThreadKey, kNoHint, catKey, catRecord, recordSize, &hint);
	if (err) {
#if DEBUG_XATTR
		printf ("%s: No matching catalog thread record found\n", __FUNCTION__);
#endif
		goto out;
	}

#if DEBUG_XATTR
	printf ("%s(%s,%d):1 recordType=%x, flags=%x\n", __FUNCTION__, __FILE__, __LINE__, 
				catRecord->hfsPlusFile.recordType, 
				catRecord->hfsPlusFile.flags);
#endif

	/* We were expecting a thread record.  The recordType says it is a file 
	 * record or folder record.  Return error.
	 */
	if ((catRecord->hfsPlusFile.recordType == kHFSPlusFolderRecord) ||
	    (catRecord->hfsPlusFile.recordType == kHFSPlusFileRecord)) {
		err = fsBTRecordNotFoundErr; 
		goto out;
	}
	
	/* It is either a file thread record or folder thread record.
	 * Look up for catalog record for the file that owns attribute */
	CopyCatalogName((CatalogName *)&(catRecord->hfsPlusThread.nodeName), &catalogName, isHFSPlus);
	BuildCatalogKey(catRecord->hfsPlusThread.parentID, &catalogName, isHFSPlus, catKey); 
	err = SearchBTreeRecord(GPtr->calculatedCatalogFCB, catKey, kNoHint, catKey, catRecord, recordSize, &hint);
	if (err) {
#if DEBUG_XATTR	
		printf ("%s: No matching catalog record found\n", __FUNCTION__);
#endif
		goto out;
	}
	
#if DEBUG_XATTR
	printf ("%s(%s,%d):2 recordType=%x, flags=%x\n", __FUNCTION__, __FILE__, __LINE__, 
				catRecord->hfsPlusFile.recordType, 
				catRecord->hfsPlusFile.flags);
#endif

out:
	return err;
}

/* Function:	RepairAttributesCheckABT
 *
 * Description:
 * This function is called from RepairAttributes (to repair extended 
 * attributes) during repair stage of fsck_hfs.
 *
 * 1. Make full pass through attribute BTree.
 * 2. For every unique fileID, lookup its catalog record in Catalog BTree.
 * 3. If found, check the attributes/security bit in catalog record.
 *              If not set correctly, set it and replace the catalog record.
 * 4. If not found, return error 
 * 
 * Input:	1. GPtr - pointer to global scavenger area
 *      	2. isHFSPlus - boolean value to indicate if volume is HFSPlus 
 *
 * Output:	err - Function result 
 * 		      zero means success
 *		      non-zero means failure
 */
static OSErr RepairAttributesCheckABT(SGlobPtr GPtr, Boolean isHFSPlus) 
{
	OSErr err = noErr;
	UInt16 selCode;		/* select access pattern for BTree */
	UInt32 hint;

	HFSPlusAttrRecord attrRecord;
	HFSPlusAttrKey attrKey;
	UInt16 attrRecordSize;
	CatalogRecord catRecord; 
	CatalogKey catKey;
	UInt16 catRecordSize;

	attributeInfo lastID;	/* fileID for the last attribute searched */
	Boolean didRecordChange = false; 	/* whether catalog record was changed after checks */

#if DEBUG_XATTR
	char attrName[XATTR_MAXNAMELEN];
	size_t len;
#endif

	lastID.fileID = 0;
	lastID.hasSecurity = false;
	
	selCode = 0x8001;	/* Get first record from BTree */
	/* Warning: Attribute record of type kHFSPlusAttrInlineData may be 
	 * truncated on read! (4425232).  This function only uses recordType 
	 * field from inline attribute record.
	 */
	err = GetBTreeRecord(GPtr->calculatedAttributesFCB, selCode, &attrKey, &attrRecord, &attrRecordSize, &hint);
	if (err != noErr) goto out; 

	selCode = 1;	/* Get next record */
	do {
#if DEBUG_XATTR
		/* Convert unicode attribute name to char for ACL check */
		(void) utf_encodestr(attrKey.attrName, attrKey.attrNameLen * 2, attrName, &len);
		attrName[len] = '\0';
		printf ("%s(%s,%d): Found attrName=%s for fileID=%d\n", __FUNCTION__, __FILE__, __LINE__, attrName, attrKey.fileID);
#endif
	
		if (attrKey.fileID != lastID.fileID) {
			/* We found an attribute with new file ID */
			
			/* Replace the previous catalog record only if we updated the flags */
			if (didRecordChange == true) {
				err = ReplaceBTreeRecord(GPtr->calculatedCatalogFCB, &catKey , kNoHint, &catRecord, catRecordSize, &hint);
				if (err) {
#if DEBUG_XATTR
					printf ("%s: Error in replacing Catalog Record\n", __FUNCTION__);
#endif		
					goto out;
				}
			}
			
			didRecordChange = false; /* reset to indicate new record has not changed */

			/* Get the catalog record for the new fileID */
			err = GetCatalogRecord(GPtr, attrKey.fileID, isHFSPlus, &catKey, &catRecord, &catRecordSize);
			if (err) {
				/* No catalog record was found for this fileID. */
#if DEBUG_XATTR
				printf ("%s: No matching catalog record found\n", __FUNCTION__);
#endif
				/* 3984119 - Do not delete extended attributes for file IDs less
	 			 * kHFSFirstUserCatalogNodeID but not equal to kHFSRootFolderID 
	 			 * in prime modulus checksum.  These file IDs do not have 
	 			 * any catalog record
	 			 */
				if ((attrKey.fileID < kHFSFirstUserCatalogNodeID) && 
	    			    (attrKey.fileID != kHFSRootFolderID)) { 
#if DEBUG_XATTR
					printf ("%s: Ignore catalog check for fileID=%d for attribute=%s\n", __FUNCTION__, attrKey.fileID, attrName); 
#endif
					goto getnext;
				}

				/* Delete this orphan extended attribute */
				err = DeleteBTreeRecord(GPtr->calculatedAttributesFCB, &attrKey);
				if (err) {
#if DEBUG_XATTR
					printf ("%s: Error in deleting attribute record\n", __FUNCTION__);
#endif
					goto out;
				}
#if DEBUG_XATTR
				printf ("%s: Deleted attribute=%s for fileID=%d\n", __FUNCTION__, attrName, attrKey.fileID);
#endif
				/* set flags to write back header and map */
				GPtr->ABTStat |= S_BTH + S_BTM;	
				goto getnext;
			} 

			lastID.fileID = attrKey.fileID;	/* set last fileID to the new ID */
			lastID.hasSecurity = false; /* reset to indicate new fileID does not have security */
				
			/* Check the Attribute bit */
			if (!(catRecord.hfsPlusFile.flags & kHFSHasAttributesMask)) {
				/* kHFSHasAttributeBit should be set */
				catRecord.hfsPlusFile.flags |= kHFSHasAttributesMask;
				didRecordChange = true;
			}

			/* Check if attribute is ACL */
			if (!bcmp(attrKey.attrName, GPtr->securityAttrName, GPtr->securityAttrLen)) {
				lastID.hasSecurity = true;
				/* Check the security bit */
				if (!(catRecord.hfsPlusFile.flags & kHFSHasSecurityMask)) {
					/* kHFSHasSecurityBit should be set */
					catRecord.hfsPlusFile.flags |= kHFSHasSecurityMask;
					didRecordChange = true;
				}
			}
		} else {
			/* We have seen attribute for fileID in past */

			/* If last time we saw this fileID did not have an ACL and this 
			 * extended attribute is an ACL, ONLY check consistency of 
			 * security bit from Catalog record 
			 */
			if ((lastID.hasSecurity == false) && !bcmp(attrKey.attrName, GPtr->securityAttrName, GPtr->securityAttrLen)) {
				lastID.hasSecurity = true;
				/* Check the security bit */
				if (!(catRecord.hfsPlusFile.flags & kHFSHasSecurityMask)) {
					/* kHFSHasSecurityBit should be set */
					catRecord.hfsPlusFile.flags |= kHFSHasSecurityMask;
					didRecordChange = true;
				}
			}
		}
		
getnext:
		/* Access the next record
		 * Warning: Attribute record of type kHFSPlusAttrInlineData may be 
		 * truncated on read! (4425232).  This function only uses recordType 
		 * field from inline attribute record.
	 	 */
		err = GetBTreeRecord(GPtr->calculatedAttributesFCB, selCode, &attrKey, &attrRecord, &attrRecordSize, &hint);
	} while (err == noErr);

	err = noErr;

	/* Replace the catalog record for last extended attribute in the attributes BTree
	 * only if we updated the flags
	 */
	if (didRecordChange == true) {
		err = ReplaceBTreeRecord(GPtr->calculatedCatalogFCB, &catKey , kNoHint, &catRecord, catRecordSize, &hint);
		if (err) {
#if DEBUG_XATTR
			printf ("%s: Error in replacing Catalog Record\n", __FUNCTION__);
#endif		
			goto out;
		}
	}

out:
	return err;
}

/* Function:	RepairAttributesCheckCBT
 *
 * Description:
 * This function is called from RepairAttributes (to repair extended 
 * attributes) during repair stage of fsck_hfs.
 *
 * NOTE: The case where attribute exists and bit is not set is being taken care in 
 * RepairAttributesCheckABT.  This function determines relationship from catalog
 * Btree to attribute Btree, and not vice-versa. 

 * 1. Make full pass through catalog BTree.
 * 2. For every fileID, if the attributes/security bit is set, 
 *    lookup all the extended attributes in the attributes BTree.
 * 3. If found, check that if bits are set correctly.
 * 4. If not found, clear the bits.
 * 
 * Input:	1. GPtr - pointer to global scavenger area
 *      	2. isHFSPlus - boolean value to indicate if volume is HFSPlus 
 *
 * Output:	err - Function result 
 * 		      zero means success
 *		      non-zero means failure
 */
static OSErr RepairAttributesCheckCBT(SGlobPtr GPtr, Boolean isHFSPlus)
{
	OSErr err = noErr;
	UInt16 selCode;		/* select access pattern for BTree */
	UInt16 recordSize;
	UInt32 hint;

	HFSPlusAttrKey *attrKey;
	CatalogRecord catRecord; 
	CatalogKey catKey;

	Boolean didRecordChange = false; 	/* whether catalog record was changed after checks */

	BTreeIterator iterator;

	UInt32 curFileID;
	Boolean curRecordHasAttributes = false;
	Boolean curRecordHasSecurity = false;

	selCode = 0x8001;	/* Get first record from BTree */
	err = GetBTreeRecord(GPtr->calculatedCatalogFCB, selCode, &catKey, &catRecord, &recordSize, &hint);
	if ( err != noErr ) goto out;

	selCode = 1;	/* Get next record */
	do {
		/* Check only file record and folder record, else skip to next record */
		if ( (catRecord.hfsPlusFile.recordType != kHFSPlusFileRecord) && 
		     (catRecord.hfsPlusFile.recordType != kHFSPlusFolderRecord)) {
			goto getnext;
		}

		/* Check if catalog record has attribute and/or security bit set, else
		 * skip to next record 
		 */
		if ( ((catRecord.hfsPlusFile.flags & kHFSHasAttributesMask) == 0) && 
		   	 ((catRecord.hfsPlusFile.flags & kHFSHasSecurityMask) == 0) ) {
			 goto getnext;
		}

		/* Initialize some flags */
		didRecordChange = false;
		curRecordHasSecurity = false;
		curRecordHasAttributes = false;

		/* Access all extended attributes for this fileID */ 
		curFileID = catRecord.hfsPlusFile.fileID;

		/* Initialize the iterator and attribute key */
		ClearMemory(&iterator, sizeof(BTreeIterator));
		attrKey = (HFSPlusAttrKey *)&iterator.key;
		attrKey->keyLength = kHFSPlusAttrKeyMinimumLength;
		attrKey->fileID = curFileID;

		/* Search for attribute with NULL name.  This will place the iterator at correct fileID location in BTree */	
		err = BTSearchRecord(GPtr->calculatedAttributesFCB, &iterator, kInvalidMRUCacheKey, NULL, NULL, &iterator);
		if (err && (err != btNotFound)) {
#if DEBUG_XATTR
			printf ("%s: No matching attribute record found\n", __FUNCTION__);
#endif
			goto out;
		}

		/* Iterate over to all extended attributes for given fileID */
		err = BTIterateRecord(GPtr->calculatedAttributesFCB, kBTreeNextRecord, &iterator, NULL, NULL);

		/* Check only if we did _find_ an attribute record for the current fileID */
		while ((err == noErr) && (attrKey->fileID == curFileID)) {
			/* Current record should have attribute bit set */
			curRecordHasAttributes = true;

			/* Current record should have security bit set */
			if (!bcmp(attrKey->attrName, GPtr->securityAttrName, GPtr->securityAttrLen)) {
				curRecordHasSecurity = true;
			}

			/* Get the next record */
			err = BTIterateRecord(GPtr->calculatedAttributesFCB, kBTreeNextRecord, &iterator, NULL, NULL);
		}

		/* Determine if we need to update the catalog record */
		if ((curRecordHasAttributes == false) && (catRecord.hfsPlusFile.flags & kHFSHasAttributesMask)) {
			/* If no attribute exists and attributes bit is set, clear it */
			catRecord.hfsPlusFile.flags &= ~kHFSHasAttributesMask;		
			didRecordChange = true;
		}
				
		if ((curRecordHasSecurity == false) && (catRecord.hfsPlusFile.flags & kHFSHasSecurityMask)) {
			/* If no security attribute exists and security bit is set, clear it */
			catRecord.hfsPlusFile.flags &= ~kHFSHasSecurityMask;		
			didRecordChange = true;
		}
			 
		/* If there was any change in catalog record, write it back to disk */
		if (didRecordChange == true) {
			err = ReplaceBTreeRecord( GPtr->calculatedCatalogFCB, &catKey , kNoHint, &catRecord, recordSize, &hint );
			if (err) {
#if DEBUG_XATTR
				printf ("%s: Error writing catalog record\n", __FUNCTION__);
#endif
				goto out;
			}
		}

getnext:
		/* Access the next record */
		err = GetBTreeRecord( GPtr->calculatedCatalogFCB, selCode, &catKey, &catRecord, &recordSize, &hint );
	} while (err == noErr); 

	err = noErr;

out:
	return err;
}

/* Function:	RepairAttributes
 *
 * Description:
 * This function fixes the extended attributes consistency by
 * calling two functions:
 * 1. RepairAttributesCheckABT:  Traverses attributes Btree and
 * checks if each attribute has correct bits set in its corresponding 
 * catalog record.
 * 2. RepairAttributesCheckCBT:  Traverses catalog Btree and checks
 * if each catalog record that has attribute/security bit set have
 * corresponding extended attributes. 
 * 
 * Input:	1. GPtr - pointer to global scavenger area
 *
 * Output:	err - Function result 
 * 		      zero means success
 *		      non-zero means failure
 */
static OSErr RepairAttributes(SGlobPtr GPtr)
{
	OSErr err = noErr;
	Boolean isHFSPlus;
	
	/* Check if the volume is HFS Plus volume */
	isHFSPlus = VolumeObjectIsHFSPlus();
	if (!isHFSPlus) {
		goto out;
	}

	/* Traverse Attributes BTree and access required records in Catalog BTree */
	err = RepairAttributesCheckABT(GPtr, isHFSPlus);
	if (err) {
		goto out;
	}

	/* Traverse Catalog BTree and access required records in Attributes BTree */
	err = RepairAttributesCheckCBT(GPtr, isHFSPlus);
	if (err) {
		goto out;
	}

out:
	return err;
}

/*------------------------------------------------------------------------------

Function:	cmpLongs

Function:	compares two longs.
			
Input:		*a:  pointer to first number
			*b:  pointer to second number

Output:		<0 if *a < *b
			0 if a == b
			>0 if a > b
------------------------------------------------------------------------------*/

int cmpLongs ( const void *a, const void *b )
{
	return( *(long*)a - *(long*)b );
}

/* Function: FixOverlappingExtents
 *
 * Description: Fix overlapping extents problem.  The implementation copies all
 * the extents existing in overlapping extents to a new location and updates the
 * extent record to point to the new extent.  At the end of repair, symlinks are
 * created with name "fileID filename" to point to the file involved in
 * overlapping extents problem.  Note that currently only HFS Plus volumes are 
 * repaired.
 *
 * PARTIAL SUCCESS: This function handles partial success in the following
 * two ways:
 *		a. The function pre-allocates space for the all the extents.  If the
 *		allocation fails, it proceeds to allocate space for other extents
 *		instead of returning error.  
 *		b. If moving an extent succeeds and symlink creation fails, the function
 *		proceeds to another extent.
 * If the repair encounters either a or b condition, appropriate message is
 * printed at the end of the function.  
 * If even a single repair operation succeeds (moving of extent), the function 
 * returns zero.
 *
 * Current limitations:
 *	1. A regular file instead of symlink is created under following conditions:
 *		a. The volume is plain HFS volume.  HFS does not support symlink
 *		creation.
 *		b. The path the new symlink points to is greater than PATH_MAX bytes.
 *		c. The path the new symlink points has some intermediate component
 *		greater than NAME_MAX bytes.
 *	2. Contiguous disk space for every new extent is expected.  The extent is
 *	not broken into multiple extents if contiguous space is not available on the
 *	disk.
 *	3. The current fix for overlapping extent only works for HFS Plus volumes. 
 *  Plain HFS volumes have problem in accessing the catalog record by fileID.
 *	4. Plain HFS volumes might have encoding issues with the newly created
 *	symlink and its data.
 *
 * Input:
 *	GPtr - global scavenger pointer
 *
 * Output:
 *	returns zero on success/partial success (moving of one extent succeeds),
 *			non-zero on failure.
 */
static OSErr FixOverlappingExtents(SGlobPtr GPtr)
{
	OSErr err = noErr;
	Boolean isHFSPlus;
	unsigned int i;
	unsigned int numOverlapExtents = 0;
	ExtentInfo *extentInfo;
	ExtentsTable **extentsTableH = GPtr->overlappedExtents;

	unsigned int status = 0;
#define S_DISKFULL			0x01	/* error due to disk full */
#define	S_MOVEEXTENT		0x02	/* moving extent succeeded */

	isHFSPlus = VolumeObjectIsHFSPlus();
	if (isHFSPlus == false) {
		/* Do not repair plain HFS volumes */
		err = R_RFail;
		goto out;
	}

	if (extentsTableH == NULL) {
		/* No overlapping extents exist */
		goto out;
	}

	numOverlapExtents = (**extentsTableH).count;

	/* Optimization - sort the overlap extent list based on blockCount to 
	 * start allocating contiguous space for largest number of blocks first
	 */
	qsort((**extentsTableH).extentInfo, numOverlapExtents, sizeof(ExtentInfo), 
		  CompareExtentBlockCount);

#if DEBUG_OVERLAP
	/* Print all overlapping extents structure */
	for (i=0; i<numOverlapExtents; i++) {
		extentInfo	= &((**extentsTableH).extentInfo[i]);
		printf ("%d: fileID = %d, startBlock = %d, blockCount = %d\n", i, extentInfo->fileID, extentInfo->startBlock, extentInfo->blockCount);
	}
#endif

	/* Pre-allocate free space for all overlapping extents */
	for (i=0; i<numOverlapExtents; i++) {
		extentInfo	= &((**extentsTableH).extentInfo[i]);
		err = AllocateContigBitmapBits (GPtr->calculatedVCB, extentInfo->blockCount, &(extentInfo->newStartBlock));
		if ((err != noErr)) {
			/* Not enough disk space */
			status |= S_DISKFULL;
#if DEBUG_OVERLAP
			printf ("%s: Not enough disk space to allocate extent for fileID = %d (start=%d, count=%d)\n", __FUNCTION__, extentInfo->fileID, extentInfo->startBlock, extentInfo->blockCount);
#endif
		}
	}

	/* For every extent info, copy the extent into new location and create symlink */
	for (i=0; i<numOverlapExtents; i++) {
		extentInfo	= &((**extentsTableH).extentInfo[i]);

		/* Do not repair this extent as no new extent was allocated */
		if (extentInfo->newStartBlock == 0) {
			continue;
		}

		/* Move extent data to new location */
		err	= MoveExtent(GPtr, extentInfo);
		if (err != noErr) {
			extentInfo->didRepair = false;
#if DEBUG_OVERLAP
			printf ("%s: Extent move failed for extent for fileID = %u (old=%u, new=%u, count=%u) (err=%d)\n", __FUNCTION__, extentInfo->fileID, extentInfo->startBlock, extentInfo->newStartBlock, extentInfo->blockCount, err);
#endif
		} else {
			/* Mark the overlapping extent as repaired */
			extentInfo->didRepair = true;
			status |= S_MOVEEXTENT;
#if DEBUG_OVERLAP
			printf ("%s: Extent move success for extent for fileID = %u (old=%u, new=%u, count=%u)\n", __FUNCTION__, extentInfo->fileID, extentInfo->startBlock, extentInfo->newStartBlock, extentInfo->blockCount);
#endif
		}

		/* Create symlink for the corrupt file */
		err = CreateCorruptFileSymlink(GPtr, extentInfo->fileID);
		if (err != noErr) {
#if DEBUG_OVERLAP
			printf ("%s: Error in creating symlink for fileID = %d (err=%d)\n", __FUNCTION__, extentInfo->fileID, err);
#endif
		} else {
#if DEBUG_OVERLAP
			printf ("%s: Created symlink for fileID = %u (old=%u, new=%u, count=%u)\n", __FUNCTION__, extentInfo->fileID, extentInfo->startBlock, extentInfo->newStartBlock, extentInfo->blockCount);
#endif
		}
	}

out:
	/* Release all blocks used by overlap extents that are repaired */
	for (i=0; i<numOverlapExtents; i++) {
		extentInfo	= &((**extentsTableH).extentInfo[i]);
		if (extentInfo->didRepair == true) {
			ReleaseBitmapBits (extentInfo->startBlock, extentInfo->blockCount);
		}
	}

	/* For all un-repaired extents, 
	 *	1. Release all blocks allocated for new extent.
	 *	2. Mark all blocks used for the old extent (since the overlapping region
	 *	have been marked free in the for loop above.
	 */
	for (i=0; i<numOverlapExtents; i++) {
		extentInfo	= &((**extentsTableH).extentInfo[i]);
		if (extentInfo->didRepair == false) {
			CaptureBitmapBits (extentInfo->startBlock, extentInfo->blockCount);

			if (extentInfo->newStartBlock != 0) {
				ReleaseBitmapBits (extentInfo->newStartBlock, extentInfo->blockCount);
			}
		}
	}

	/* Update the volume free block count since the release and alloc above might
	 * have worked on same bit multiple times.
	 */
	UpdateFreeBlockCount (GPtr);

	/* Print correct status messages */
	if (status & S_DISKFULL) {
		PrintError (GPtr, E_DiskFull, 0);
	} 
	
	/* If moving of even one extent succeeds, return success */
	if (status & S_MOVEEXTENT) {
		err = noErr;
	}

	return err;
} /* FixOverlappingExtents */

/* Function: CompareExtentBlockCount
 *
 * Description: Compares the blockCount from two ExtentInfo and return the
 * comparison result. (since we have to arrange in descending order)
 *
 * Input:
 *	first and second - void pointers to ExtentInfo structure.
 *
 * Output:
 *	<0 if first > second
 * 	=0 if first == second
 *	>0 if first < second
 */
static int CompareExtentBlockCount(const void *first, const void *second)
{
	return (((ExtentInfo *)second)->blockCount - 
			((ExtentInfo *)first)->blockCount);
} /* CompareExtentBlockCount */

/* Function: MoveExtent
 *
 * Description: Move data from old extent to new extent and update corresponding
 * records.
 * 1. Search the extent record for the overlapping extent.
 *		If the fileID < kHFSFirstUserCatalogNodeID, 
 *			Ignore repair for BadBlock, RepairCatalog, BogusExtent files.
 *			Search for extent record in volume header. 
 *		Else, 
 *			Search for extent record in catalog BTree.  If the extent list does
 *			not end in catalog record and extent record not found in catalog
 *			record, search in extents BTree.
 * 2. If found, copy disk blocks from old extent to new extent.  
 * 3. If it succeeds, update extent record with new start block and write back
 *    to disk.
 * This function does not take care to deallocate blocks from old start block.
 *
 * Input: 
 *	GPtr - Global Scavenger structure pointer
 *  extentInfo - Current overlapping extent details.
 *
 * Output:
 * 	err: zero on success, non-zero on failure
 *		paramErr - Invalid paramter, ex. file ID is less than
 *		kHFSFirstUserCatalogNodeID.  
 */
static OSErr MoveExtent(SGlobPtr GPtr, ExtentInfo *extentInfo)
{
	OSErr err = noErr;
	Boolean isHFSPlus;

	CatalogRecord catRecord;
	CatalogKey catKey;
	HFSPlusExtentKey extentKey;
	HFSPlusExtentRecord extentData;
	HFSPlusAttrKey attrKey;
	HFSPlusAttrRecord attrRecord;
	UInt16 recordSize;

	enum locationTypes {volumeHeader, catalogBTree, extentsBTree, attributeBTree} foundLocation;

	UInt32 foundExtentIndex = 0;
	Boolean noMoreExtents = true;
	
	isHFSPlus = VolumeObjectIsHFSPlus();

	/* Find correct location of this overlapping extent */
	if (extentInfo->forkType == kEAData) {
		assert(isHFSPlus == true);

		/* Search extent in attribute btree */
		err = SearchExtentInAttributeBT (GPtr, extentInfo, &attrKey, &attrRecord, 
										&recordSize, &foundExtentIndex);
		if (err != noErr) {
			goto out;
		}
		foundLocation = attributeBTree;
	} else { /* kDataFork or kRsrcFork */
		if (extentInfo->fileID < kHFSFirstUserCatalogNodeID) {
			/* Ignore these fileIDs in repair.  Bad block file blocks should 
			 * never be moved.  kHFSRepairCatalogFileID and kHFSBogusExtentFileID 
			 * are temporary runtime files.  We need to return error to the 
			 * caller to deallocate disk blocks preallocated during preflight
			 * to move the overlapping extents.  Any other extent that overlaps
			 * with these extents might have moved successfully, thus repairing
			 * the problem.
			 */
			if ((extentInfo->fileID == kHFSBadBlockFileID) ||
				(extentInfo->fileID == kHFSRepairCatalogFileID) ||
				(extentInfo->fileID == kHFSBogusExtentFileID)) {
				err = paramErr;
				goto out;
			}
	
			/* Search for extent record in the volume header */
			err = SearchExtentInVH (GPtr, extentInfo, &foundExtentIndex, &noMoreExtents);
			foundLocation = volumeHeader;
		} else {
			/* Search the extent record from the catalog btree */
			err = SearchExtentInCatalogBT (GPtr, extentInfo, &catKey, &catRecord, 
										  &recordSize, &foundExtentIndex, &noMoreExtents);
			foundLocation = catalogBTree;
		}
		if (err != noErr) {
			if (noMoreExtents == false) { 
				/* search extent in extents overflow btree */
				err = SearchExtentInExtentBT (GPtr, extentInfo, &extentKey, 
											  &extentData, &recordSize, &foundExtentIndex);
				foundLocation = extentsBTree;
				if (err != noErr) {
					dbg_printf (d_error|d_overlap, "%s: No matching extent record found in extents btree for fileID = %d (err=%d)\n", __FUNCTION__, extentInfo->fileID, err);
					goto out;
				}
			} else {
				/* No more extents exist for this file */
				dbg_printf (d_error|d_overlap, "%s: No matching extent record found for fileID = %d\n", __FUNCTION__, extentInfo->fileID);
				goto out;
			}
		}
	}
	/* Copy disk blocks from old extent to new extent */
	err = CopyDiskBlocks(GPtr, extentInfo->startBlock, extentInfo->blockCount, 
						 extentInfo->newStartBlock);
	if (err != noErr) {
		dbg_printf (d_error|d_overlap, "%s: Error in copying disk blocks for fileID = %d (err=%d)\n", __FUNCTION__, extentInfo->fileID, err);
		goto out;
	}
	
	/* Replace the old start block in extent record with new start block */
	if (foundLocation == catalogBTree) {
		err = UpdateExtentInCatalogBT(GPtr, extentInfo, &catKey, &catRecord, 
									  &recordSize, foundExtentIndex);
	} else if (foundLocation == volumeHeader) {
		err = UpdateExtentInVH(GPtr, extentInfo, foundExtentIndex);
	} else if (foundLocation == extentsBTree) {
		extentData[foundExtentIndex].startBlock = extentInfo->newStartBlock;
		err = UpdateExtentRecord(GPtr->calculatedVCB, NULL, &extentKey, extentData, kNoHint);
	} else if (foundLocation == attributeBTree) {
		err = UpdateExtentInAttributeBT(GPtr, extentInfo, &attrKey, &attrRecord,
										&recordSize, foundExtentIndex);

	}
	if (err != noErr) {
		dbg_printf (d_error|d_overlap, "%s: Error in updating extent record for fileID = %d (err=%d)\n", __FUNCTION__, extentInfo->fileID, err);
		goto out;
	}

out:
	return err;
} /* MoveExtent */

/* Function: CreateCorruptFileSymlink
 *
 * Description: Create symlink to point to the corrupt files that might
 * have data loss due to repair (overlapping extents, bad extents)
 * 
 * The function looks up directory with name "DamagedFiles" in the 
 * root of the file system being repaired.  If it does not exists, it 
 * creates the directory.  The symlink to damaged file is created in this
 * directory.
 *
 * If fileID >= kHFSFirstUserCatalogNodeID,
 *	Lookup the filename and path to the file based on file ID.  Create the
 *	new file name as "fileID filename" and data as the relative path of the file
 *	from the root of the volume.
 *	If either
 *		the volume is plain HFS, or
 *		the length of the path pointed by data is greater than PATH_MAX, or
 *		the length of any intermediate path component is greater than NAME_MAX,
 *		Create a plain file with given data.
 *	Else
 *		Create a symlink.
 * Else	
 *	Find the name of file based on ID (ie. Catalog BTree, etc), and create plain
 *	regular file with name "fileID filename" and data as "System File:
 *	filename".
 *
 * Input:
 *	1. GPtr - global scavenger structure pointer.
 * 	2. fileID - fileID of the source for creating symlink
 *
 * Output:
 * 	returns zero on success, non-zero on failure.
 *		memFullErr - Not enough memory
 */
static OSErr CreateCorruptFileSymlink(SGlobPtr GPtr, UInt32 fileID)
{
	OSErr err = noErr;
	Boolean isHFSPlus;
	char *filename = NULL;
	unsigned int filenamelen; 
	char *data = NULL;
	unsigned int datalen;
	unsigned int filenameoffset;
	unsigned int dataoffset;
	UInt32 damagedDirID;
	UInt16 status;
	UInt16 fileType;
	
	isHFSPlus = VolumeObjectIsHFSPlus();
	
	/* Lookup and create, if required, the DamagedFiles folder */
	damagedDirID = CreateDirByName(GPtr, (u_char *)"DamagedFiles", kHFSRootFolderID);
	if (damagedDirID == 0) {
		goto out;
	}

	/* Allocate (kHFSPlusMaxFileNameChars * 4) for unicode - utf8 conversion */
	filenamelen = kHFSPlusMaxFileNameChars * 4;
	filename = malloc(filenamelen);
	if (!filename) {
		err = memFullErr;
		goto out;
	}

	/* Allocate (PATH_MAX * 4) instead of PATH_MAX for unicode - utf8 conversion */
	datalen = PATH_MAX * 4;
	data = malloc(datalen);
	if (!data) {
		err = memFullErr;
		goto out;
	}

	/* Find filename, path for fileID >= 16 and determine new fileType */
	if (fileID >= kHFSFirstUserCatalogNodeID) {
		char *name;
		char *path;

		/* construct symlink data with .. prefix */
		dataoffset = sprintf (data, "..");
		path = data + dataoffset;
		datalen -= dataoffset;

		/* construct new filename prefix with fileID<space> */
		filenameoffset = sprintf (filename, "%08x ", fileID);
		name = filename + filenameoffset;
		filenamelen -= filenameoffset;

		/* find file name and path (data for symlink) for fileID */
		err = GetFileNamePathByID(GPtr, fileID, path, &datalen, 
								  name, &filenamelen, &status);
		if (err != noErr) {
#if DEBUG_OVERLAP
			printf ("%s: Error in getting name/path for fileID = %d (err=%d)\n", __FUNCTION__, fileID, err);
#endif
			goto out;
		}

		/* update length of path and filename */
		filenamelen += filenameoffset;
		datalen += dataoffset;

		/* If 
		 * (1) the volume is plain HFS volume, or
		 * (2) any intermediate component in path was more than NAME_MAX bytes, or
		 * (3) the entire path was greater than PATH_MAX bytes 
		 * then create regular file
		 * else create symlink.
		 */
		if (!isHFSPlus || (status & FPATH_BIGNAME) || (datalen > PATH_MAX)) {
			/* create file */
			fileType = S_IFREG;
		} else {
			/* create symlink */
			fileType = S_IFLNK;
		}
	} else {
		/* for fileID < 16, create regular file */
		fileType = S_IFREG;

		/* construct the name of the file */
		filenameoffset = sprintf (filename, "%08x ", fileID);
		filenamelen -= filenameoffset;
		err = GetSystemFileName (fileID, (filename + filenameoffset), &filenamelen);
		filenamelen += filenameoffset;
		
		/* construct the data of the file */
		dataoffset = sprintf (data, "System File: ");
		datalen -= dataoffset;
		err = GetSystemFileName (fileID, (data + dataoffset), &datalen);
		datalen += dataoffset;
	}

	/* Create new file */
	err = CreateFileByName (GPtr, damagedDirID, fileType, (u_char *)filename, 
							filenamelen, (u_char *)data, datalen);
	/* Mask error if file already exists */
	if (err == EEXIST) {
		err = noErr;
	}
	if (err != noErr) {
#if DEBUG_OVERLAP
		printf ("%s: Error in creating fileType = %d for fileID = %d (err=%d)\n", __FUNCTION__, fileType, fileID, err);	
#endif
		goto out;
	}

out:
	if (err) {
		if ((GPtr->PrintStat & S_SymlinkCreate) == 0) {
			PrintError (GPtr, E_SymlinkCreate, 0);
			GPtr->PrintStat|= S_SymlinkCreate;
		}
	} else {
		if ((GPtr->PrintStat & S_DamagedDir) == 0) {
			PrintStatus (GPtr, M_LookDamagedDir, 0);
			GPtr->PrintStat|= S_DamagedDir;
		}
	}

	if (data) {
		free (data);
	}
	if (filename) {
		free (filename);
	}

	return err;
} /* CreateCorruptFileSymlink */

/* Function: SearchExtentInAttributeBT
 *	
 * Description: Search extent with given information (fileID, attribute name, 
 * startBlock, blockCount) in the attribute BTree.  
 *
 * Input:
 *	1. GPtr - global scavenger structure pointer.
 *	2. extentInfo - Information about extent to be searched.
 *
 * Output:
 *	Returns zero on success, fnfErr on failure.
 *	1. *attrKey - Attribute key for given fileID and attribute name, if found.
 *	2. *attrRecord - Attribute record for given fileID and attribute name, if found.
 *	3. *recordSize - Size of the record being returned.
 * 	4. *foundExtentIndex - Index in extent record which matches the input data. 
 */
static OSErr SearchExtentInAttributeBT(SGlobPtr GPtr, ExtentInfo *extentInfo, 
				HFSPlusAttrKey *attrKey, HFSPlusAttrRecord *attrRecord, 
				UInt16 *recordSize, UInt32 *foundExtentIndex)
{
	OSErr result = fnfErr; 
	BTreeIterator iterator;
	FSBufferDescriptor btRecord;
	HFSPlusAttrKey *key;
	Boolean noMoreExtents;
	unsigned char *attrname = NULL;
	size_t attrnamelen;

	assert((extentInfo->attrname != NULL));

	attrname = malloc (XATTR_MAXNAMELEN + 1);
	if (!attrname) {
		result = memFullErr;
		goto out;
	}

	/* Initialize the iterator, attribute record buffer, and attribute key */
	ClearMemory(&iterator, sizeof(BTreeIterator));
	key = (HFSPlusAttrKey *)&iterator.key;
	attrnamelen = strlen(extentInfo->attrname);
	BuildAttributeKey(extentInfo->fileID, 0, (unsigned char *)extentInfo->attrname, attrnamelen, key);

	btRecord.bufferAddress = attrRecord;
	btRecord.itemCount = 1;
	btRecord.itemSize = sizeof(HFSPlusAttrRecord);

	/* Search for the attribute record 
	 * Warning: Attribute record of type kHFSPlusAttrInlineData may be 
	 * truncated on read! (4425232).  This function only uses recordType 
	 * field from inline attribute record.
	 */
	result = BTSearchRecord(GPtr->calculatedAttributesFCB, &iterator, 
				kInvalidMRUCacheKey, &btRecord, recordSize, &iterator);
	if (result) {
		dbg_printf (d_error|d_overlap, "%s: Error finding attribute record (err=%d) for fileID = %d, attrname = %d\n", __FUNCTION__, result, extentInfo->fileID, extentInfo->attrname);
		goto out;	
	}
	
	/* Search the attribute record for overlapping extent.  If found, return
	 * success.  If not, iterate to the next record.  If it is a valid 
	 * attribute extent record belonging to the same attribute, search 
	 * for the desired extent.
	 */
	while (1) {
		if (attrRecord->recordType == kHFSPlusAttrForkData) {
			result = FindExtentInExtentRec(true, extentInfo->startBlock, 
					extentInfo->blockCount, attrRecord->forkData.theFork.extents,
					foundExtentIndex, &noMoreExtents);
			if ((result == noErr) || (noMoreExtents == true)) {
				goto out;
			}
		} else if (attrRecord->recordType == kHFSPlusAttrExtents) {
			result = FindExtentInExtentRec(true, extentInfo->startBlock, 
					extentInfo->blockCount, attrRecord->overflowExtents.extents,
					foundExtentIndex, &noMoreExtents);
			if ((result == noErr) || (noMoreExtents == true)) {
				goto out;
			}
		} else { 
			/* Invalid attribute record.  This function should not find any 
			 * attribute record except forkData and AttrExtents.
			 */
			result = fnfErr;
			goto out;
		}
			
		/* Iterate to the next record
	 	 * Warning: Attribute record of type kHFSPlusAttrInlineData may be 
	 	 * truncated on read! (4425232).  This function only uses recordType 
		 * field from inline attribute record.
	 	 */
		result = BTIterateRecord(GPtr->calculatedAttributesFCB, kBTreeNextRecord, 
					&iterator, &btRecord, recordSize); 
		if (result) {
			goto out;
		}

		(void) utf_encodestr(key->attrName, key->attrNameLen * 2, attrname, &attrnamelen);
		attrname[attrnamelen] = '\0';

		/* Check if the attribute record belongs to the same attribute */
		if ((key->fileID != extentInfo->fileID) ||
			(strcmp((char *)attrname, extentInfo->attrname))) {
			/* The attribute record belongs to another attribute */
			result = fnfErr;
			goto out;
		}
	}

out:
	/* Copy the correct key to the caller */
	if (result == noErr) {
		CopyMemory(key, attrKey, sizeof(HFSPlusAttrKey));
	}

	if (attrname != NULL) {
		free (attrname);
	}
	
	return (result);
}

/* Function: UpdateExtentInAttributeBT
 *	
 * Description: Update extent record with given information (fileID, startBlock,
 * blockCount) in attribute BTree.
 *
 * Input:
 *	1. GPtr - global scavenger structure pointer.
 *	2. extentInfo - Information about extent to be searched.
 *	3. *attrKey - Attribute key for record to update.
 *	4. *attrRecord - Attribute record to update.
 *	5. *recordSize - Size of the record.
 *	6. foundExtentIndex - Index in extent record to update.
 *
 * Output:
 *	Returns zero on success, non-zero on failure.
 */
static OSErr UpdateExtentInAttributeBT (SGlobPtr GPtr, ExtentInfo *extentInfo,
				HFSPlusAttrKey *attrKey, HFSPlusAttrRecord *attrRecord, 
				UInt16 *recordSize, UInt32 foundInExtentIndex)
{
	OSErr err;
	UInt32 foundHint;

	assert ((attrRecord->recordType == kHFSPlusAttrForkData) ||
			(attrRecord->recordType == kHFSPlusAttrExtents));

	/* Update the new start block count in the extent */
	if (attrRecord->recordType == kHFSPlusAttrForkData) {
		attrRecord->forkData.theFork.extents[foundInExtentIndex].startBlock = 
			extentInfo->newStartBlock;
	} else if (attrRecord->recordType == kHFSPlusAttrExtents) {
		attrRecord->overflowExtents.extents[foundInExtentIndex].startBlock = 
			extentInfo->newStartBlock;
	}

	/* Replace the attribute record.
 	 * Warning: Attribute record of type kHFSPlusAttrInlineData may be 
 	 * truncated on read! (4425232).  
	 */
	err = ReplaceBTreeRecord (GPtr->calculatedAttributesFCB, attrKey, kNoHint, 
							  attrRecord, *recordSize, &foundHint);
	
	return (err);
}

/* Function: SearchExtentInVH
 *	
 * Description: Search extent with given information (fileID, startBlock,
 * blockCount) in volume header.  
 *
 * Input:
 *	1. GPtr - global scavenger structure pointer.
 *	2. extentInfo - Information about extent to be searched.
 *
 * Output:
 *	Returns zero on success, fnfErr on failure.
 *	1. *foundExtentIndex - Index in extent record which matches the input data. 
 *	2. *noMoreExtents - Indicates that no more extents will exist for this
 *	fileID in extents BTree.
 */
static OSErr SearchExtentInVH(SGlobPtr GPtr, ExtentInfo *extentInfo, UInt32 *foundExtentIndex, Boolean *noMoreExtents)
{
	OSErr err = fnfErr;
	Boolean isHFSPlus;
	SFCB *fcb = NULL;

	isHFSPlus = VolumeObjectIsHFSPlus();
	*noMoreExtents = true;
	
	/* Find correct FCB structure */
	switch (extentInfo->fileID) {
		case kHFSExtentsFileID:
			fcb = GPtr->calculatedVCB->vcbExtentsFile;
			break;

		case kHFSCatalogFileID:
			fcb = GPtr->calculatedVCB->vcbCatalogFile;
			break;

		case kHFSAllocationFileID:
			fcb = GPtr->calculatedVCB->vcbAllocationFile;
			break;

		case kHFSStartupFileID:
			fcb = GPtr->calculatedVCB->vcbStartupFile;
			break;
			
		case kHFSAttributesFileID:
			fcb = GPtr->calculatedVCB->vcbAttributesFile;
			break;
	};

	/* If extent found, find correct extent index */
	if (fcb != NULL) {
		if (isHFSPlus) {
			err = FindExtentInExtentRec(isHFSPlus, extentInfo->startBlock, 
										extentInfo->blockCount, fcb->fcbExtents32, 
										foundExtentIndex, noMoreExtents);
		} else {
			err = FindExtentInExtentRec(isHFSPlus, extentInfo->startBlock, 
										extentInfo->blockCount, 
										(*(HFSPlusExtentRecord *)fcb->fcbExtents16),
										foundExtentIndex, noMoreExtents);
		}
	}
	return err;
} /* SearchExtentInVH */

/* Function: UpdateExtentInVH
 *
 * Description:	Update the extent record for given fileID and index in the
 * volume header with new start block.  
 *
 * Input:
 *	1. GPtr - global scavenger structure pointer.
 *	2. extentInfo - Information about extent to be searched.
 *	3. foundExtentIndex - Index in extent record to update.
 *
 * Output:
 *	Returns zero on success, fnfErr on failure.  This function will fail an
 *	incorrect fileID is passed.
 */
static OSErr UpdateExtentInVH (SGlobPtr GPtr, ExtentInfo *extentInfo, UInt32 foundExtentIndex)
{
	OSErr err = fnfErr;
	Boolean isHFSPlus;
	SFCB *fcb = NULL;

	isHFSPlus = VolumeObjectIsHFSPlus();
	
	/* Find correct FCB structure */
	switch (extentInfo->fileID) {
		case kHFSExtentsFileID:
			fcb = GPtr->calculatedVCB->vcbExtentsFile;
			break;

		case kHFSCatalogFileID:
			fcb = GPtr->calculatedVCB->vcbCatalogFile;
			break;

		case kHFSAllocationFileID:
			fcb = GPtr->calculatedVCB->vcbAllocationFile;
			break;

		case kHFSStartupFileID:
			fcb = GPtr->calculatedVCB->vcbStartupFile;
			break;
			
		case kHFSAttributesFileID:
			fcb = GPtr->calculatedVCB->vcbAttributesFile;
			break;
	};

	/* If extent found, find correct extent index */
	if (fcb != NULL) {
		if (isHFSPlus) {
			fcb->fcbExtents32[foundExtentIndex].startBlock = extentInfo->newStartBlock;
		} else {
			fcb->fcbExtents16[foundExtentIndex].startBlock = extentInfo->newStartBlock;
		}
		MarkVCBDirty(GPtr->calculatedVCB);
		err = noErr;
	}
	return err;
} /* UpdateExtentInVH */

/* Function: SearchExtentInCatalogBT
 *	
 * Description: Search extent with given information (fileID, startBlock,
 * blockCount) in catalog BTree.
 *
 * Input:
 *	1. GPtr - global scavenger structure pointer.
 *	2. extentInfo - Information about extent to be searched.
 *
 * Output:
 *	Returns zero on success, non-zero on failure.
 *	1. *catKey - Catalog key for given fileID, if found.
 *	2. *catRecord - Catalog record for given fileID, if found.
 *	3. *recordSize - Size of the record being returned.
 *	4. *foundExtentIndex - Index in extent record which matches the input data. 
 *	5. *noMoreExtents - Indicates that no more extents will exist for this
 *	fileID in extents BTree.
 */
static OSErr SearchExtentInCatalogBT(SGlobPtr GPtr, ExtentInfo *extentInfo, CatalogKey *catKey, CatalogRecord *catRecord, UInt16 *recordSize, UInt32 *foundExtentIndex, Boolean *noMoreExtents)
{							 
	OSErr err;
	Boolean isHFSPlus;
	
	isHFSPlus = VolumeObjectIsHFSPlus();

	/* Search catalog btree for this file ID */
	err = GetCatalogRecord(GPtr, extentInfo->fileID, isHFSPlus, catKey, catRecord, 
						   recordSize);
	if (err != noErr) {
#if DEBUG_OVERLAP
		printf ("%s: No matching catalog record found for fileID = %d (err=%d)\n", __FUNCTION__, extentInfo->fileID, err);
#endif
		goto out;
	}

	if (isHFSPlus) {
		/* HFS Plus */
		if (extentInfo->forkType == kDataFork) {	
			/* data fork */
			err = FindExtentInExtentRec(isHFSPlus, extentInfo->startBlock, 
										extentInfo->blockCount, 
										catRecord->hfsPlusFile.dataFork.extents, 
										foundExtentIndex, noMoreExtents);
		} else { 
			/* resource fork */
			err = FindExtentInExtentRec(isHFSPlus, extentInfo->startBlock, 
										extentInfo->blockCount, 
										catRecord->hfsPlusFile.resourceFork.extents, 
										foundExtentIndex, noMoreExtents);
		}
	} else {
		/* HFS */
		if (extentInfo->forkType == kDataFork) {	
			/* data fork */
			err = FindExtentInExtentRec(isHFSPlus, extentInfo->startBlock, 
										extentInfo->blockCount, 
										(*(HFSPlusExtentRecord *)catRecord->hfsFile.dataExtents),
										foundExtentIndex, noMoreExtents);
		} else { 
			/* resource fork */
			err = FindExtentInExtentRec(isHFSPlus, extentInfo->startBlock, 
										extentInfo->blockCount, 
										(*(HFSPlusExtentRecord *)catRecord->hfsFile.rsrcExtents),
										foundExtentIndex, noMoreExtents);
		}
	}

out:
	return err;
} /* SearchExtentInCatalogBT */

/* Function: UpdateExtentInCatalogBT
 *	
 * Description: Update extent record with given information (fileID, startBlock,
 * blockCount) in catalog BTree.
 *
 * Input:
 *	1. GPtr - global scavenger structure pointer.
 *	2. extentInfo - Information about extent to be searched.
 *	3. *catKey - Catalog key for record to update.
 *	4. *catRecord - Catalog record to update.
 *	5. *recordSize - Size of the record.
 *	6. foundExtentIndex - Index in extent record to update.
 *
 * Output:
 *	Returns zero on success, non-zero on failure.
 */
static OSErr UpdateExtentInCatalogBT (SGlobPtr GPtr, ExtentInfo *extentInfo, CatalogKey *catKey, CatalogRecord *catRecord, UInt16 *recordSize, UInt32 foundInExtentIndex)
{
	OSErr err;
	Boolean isHFSPlus;
	UInt32 foundHint;
	
	isHFSPlus = VolumeObjectIsHFSPlus();

	/* Modify the catalog record */
	if (isHFSPlus) {
		if (extentInfo->forkType == kDataFork) {
			catRecord->hfsPlusFile.dataFork.extents[foundInExtentIndex].startBlock = extentInfo->newStartBlock;
		} else {
			catRecord->hfsPlusFile.resourceFork.extents[foundInExtentIndex].startBlock = extentInfo->newStartBlock;
		}
	} else {
		if (extentInfo->forkType == kDataFork) {
			catRecord->hfsFile.dataExtents[foundInExtentIndex].startBlock = extentInfo->newStartBlock;
		} else {
			catRecord->hfsFile.rsrcExtents[foundInExtentIndex].startBlock = extentInfo->newStartBlock;
		}
	}

	/* Replace the catalog record */
	err = ReplaceBTreeRecord (GPtr->calculatedCatalogFCB, catKey, kNoHint, 
							  catRecord, *recordSize, &foundHint);
	if (err != noErr) {
#if DEBUG_OVERLAP
		printf ("%s: Error in replacing catalog record for fileID = %d (err=%d)\n", __FUNCTION__, extentInfo->fileID, err);
#endif
	}
	return err;
} /* UpdateExtentInCatalogBT */

/* Function: SearchExtentInExtentBT
 *	
 * Description: Search extent with given information (fileID, startBlock,
 * blockCount) in Extent BTree.
 *
 * Input:
 *	1. GPtr - global scavenger structure pointer.
 *	2. extentInfo - Information about extent to be searched.
 *
 * Output:
 *	Returns zero on success, non-zero on failure.
 *		fnfErr - desired extent record was not found.
 *	1. *extentKey - Extent key, if found.
 *	2. *extentRecord - Extent record, if found.
 *	3. *recordSize - Size of the record being returned.
 *	4. *foundExtentIndex - Index in extent record which matches the input data. 
 */
static OSErr SearchExtentInExtentBT(SGlobPtr GPtr, ExtentInfo *extentInfo, HFSPlusExtentKey *extentKey, HFSPlusExtentRecord *extentRecord, UInt16 *recordSize, UInt32 *foundExtentIndex) 
{
	OSErr err = noErr;
	Boolean isHFSPlus;
	Boolean noMoreExtents = true;
	UInt32 hint;

	isHFSPlus = VolumeObjectIsHFSPlus();

	/* set up extent key */
	BuildExtentKey (isHFSPlus, extentInfo->forkType, extentInfo->fileID, 0, extentKey);
	err = SearchBTreeRecord (GPtr->calculatedExtentsFCB, extentKey, kNoHint, 
							 extentKey, extentRecord, recordSize, &hint);
	if ((err != noErr) && (err != btNotFound)) {
#if DEBUG_OVERLAP
		printf ("%s: Error on searching first record for fileID = %d in Extents Btree (err=%d)\n", __FUNCTION__, extentInfo->fileID, err);
#endif
		goto out;
	}
	
	if (err == btNotFound)
	{
		/* Position to the first record for the given fileID */
		err = GetBTreeRecord (GPtr->calculatedExtentsFCB, 1, extentKey, 
							  extentRecord, recordSize, &hint);
	}
	
	while (err == noErr)
	{
		/* Break out if we see different fileID, forkType in the BTree */
		if (isHFSPlus) {
			if ((extentKey->fileID != extentInfo->fileID) || 
				(extentKey->forkType != extentInfo->forkType)) {
				err = fnfErr;
				break;
			}
		} else {
			if ((((HFSExtentKey *)extentKey)->fileID != extentInfo->fileID) || 
				(((HFSExtentKey *)extentKey)->forkType != extentInfo->forkType)) {
				err = fnfErr;
				break;
			}
		}

		/* Check the extents record for corresponding startBlock, blockCount */
		err = FindExtentInExtentRec(isHFSPlus, extentInfo->startBlock, 
									extentInfo->blockCount, *extentRecord,
									foundExtentIndex, &noMoreExtents);
		if (err == noErr) {
			break;
		}
		if (noMoreExtents == true) {
			err = fnfErr;
			break;
		}

		/* Try next record for this fileID and forkType */
		err = GetBTreeRecord (GPtr->calculatedExtentsFCB, 1, extentKey, 
							  extentRecord, recordSize, &hint);
	}
	
out:
	return err;
} /* SearchExtentInExtentBT */

/* Function: FindExtentInExtentRec
 *
 * Description: Traverse the given extent record (size based on if the volume is
 * HFS or HFSPlus volume) and find the index location if the given startBlock
 * and blockCount match.
 *
 * Input:
 *	1. isHFSPlus - If the volume is plain HFS or HFS Plus.
 *	2. startBlock - startBlock to be searched in extent record.
 *	3. blockCount - blockCount to be searched in extent record.
 *	4. extentData - Extent Record to be searched.
 * 
 * Output:
 *	Returns zero if the match is found, else fnfErr on failure.
 *	1. *foundExtentIndex - Index in extent record which matches the input data. 
 *	2. *noMoreExtents - Indicates that no more extents exist after this extent
 *	record.
 */
static OSErr FindExtentInExtentRec (Boolean isHFSPlus, UInt32 startBlock, UInt32 blockCount, const HFSPlusExtentRecord extentData, UInt32 *foundExtentIndex, Boolean *noMoreExtents)
{
	OSErr err = noErr;
	UInt32 numOfExtents;
	Boolean foundExtent;
	int i;

	foundExtent = false;
	*noMoreExtents = false;
	*foundExtentIndex = 0;

	if (isHFSPlus) {
		numOfExtents = kHFSPlusExtentDensity;
	} else {
		numOfExtents = kHFSExtentDensity;
	}
	
	for (i=0; i<numOfExtents; i++) {
		if (extentData[i].blockCount == 0) {
			/* no more extents left to check */
			*noMoreExtents = true;
			break;
		}
		if ((startBlock == extentData[i].startBlock) &&
			(blockCount == extentData[i].blockCount)) {
			foundExtent = true;
			*foundExtentIndex = i;
			break;
		}
	}

	if (foundExtent == false) {
		err = fnfErr;
	}

	return err;
} /* FindExtentInExtentRec */

/* Function: GetSystemFileName
 *
 * Description: Return the name of the system file based on fileID
 *
 * Input:
 *	1. fileID - fileID whose name is to be returned.
 *	2. *filenamelen - length of filename buffer.
 *
 * Output:
 *	1. *filename - filename, is limited by the length of filename buffer passed
 *	in *filenamelen.
 *	2. *filenamelen - length of the filename
 *	Always returns zero.
 */
OSErr GetSystemFileName(UInt32 fileID, char *filename, unsigned int *filenamelen)
{
	OSErr err = noErr;
	unsigned int len;

	if (filename) {
		len = *filenamelen - 1;
		switch (fileID) {
			case kHFSExtentsFileID:
				strncpy (filename, "Extents Overflow BTree", len);
				break;

			case kHFSCatalogFileID:
				strncpy (filename, "Catalog BTree", len); 
				break;

			case kHFSAllocationFileID:
				strncpy (filename, "Allocation File", len); 
				break;

			case kHFSStartupFileID:
				strncpy (filename, "Startup File", len); 
				break;
			
			case kHFSAttributesFileID:
				strncpy (filename, "Attributes BTree", len); 
				break;

			case kHFSBadBlockFileID:
				strncpy (filename, "Bad Allocation File", len); 
				break;

			case kHFSRepairCatalogFileID:
				strncpy (filename, "Repair Catalog File", len); 
				break;

			case kHFSBogusExtentFileID:
				strncpy (filename, "Bogus Extents File", len); 
				break;

			default:
				strncpy (filename, "Unknown File", len); 
				break;
		};
		filename[len] = '\0';
		*filenamelen = strlen (filename);
	}
	return err;
}

/* structure to store the intermediate path components during BTree traversal.
 * This is used as a LIFO linked list 
 */
struct fsPathString
{
	char *name;
	unsigned int namelen;
	struct fsPathString *childPtr;
};

/* Function: GetFileNamePathByID 
 *
 * Description: Return the file/directory name and/or full path by ID.  The
 * length of the strings returned is limited by string lengths passed as
 * parameters. 
 * The function lookups catalog thread record for given fileID and its parents
 * until it reaches the Root Folder.
 *
 * Note:
 * 	1. The path returned currently does not return mangled names. 
 *	2. Either one or both of fullPath and fileName can be NULL.  
 *	3. fullPath and fileName are returned as NULL-terminated UTF8 strings. 
 *	4. Returns error if fileID < kHFSFirstUserCatalogID.
 *
 * Input:
 *	1. GPtr - global scavenger structure pointer
 *	2. fileID - fileID for the target file/directory for finding the path
 *	3. fullPathLen - size of array to return full path
 *	4. fileNameLen - size of array to return file name
 *
 * Output:
 *	Return value: zero on success, non-zero on failure
 *		memFullErr - Not enough memory
 *		paramErr - Invalid paramter
 *
 *	The data in *fileNameLen and *fullPathLen is undefined on error.
 *
 *	1. fullPath - If fullPath is non-NULL, full path of file/directory is
 *	returned (size limited by fullPathLen)
 *	2. *fullPathLen - length of fullPath returned.
 *	3. fileName - If fileName is non-NULL, file name of fileID is returned (size
 *	limited by fileNameLen).
 *	4. *fileNameLen - length of fileName returned.
 *	5. *status - status of operation, any of the following bits can be set
 *	(defined in dfalib/Scavenger.h).
 *		FNAME_BUF2SMALL	- filename buffer is too small.
 *		FNAME_BIGNAME	- filename is more than NAME_MAX bytes.
 *		FPATH_BUF2SMALL	- path buffer is too small.
 *		FPATH_BIGNAME	- one or more intermediate path component is greater
 *						  than NAME_MAX bytes.
 *		F_RESERVE_FILEID- fileID is less than kHFSFirstUserCatalogNodeID.
 */
OSErr GetFileNamePathByID(SGlobPtr GPtr, UInt32 fileID, char *fullPath, unsigned int *fullPathLen, char *fileName, unsigned int *fileNameLen, u_int16_t *status)
{
	OSErr err = noErr;
	Boolean isHFSPlus;
	UInt16 recordSize;
	UInt16 curStatus = 0;
	UInt32 hint;
	CatalogKey catKey;
	CatalogRecord catRecord;
	struct fsPathString *listHeadPtr = NULL;
	struct fsPathString *listTailPtr = NULL;
	struct fsPathString *curPtr = NULL;
	u_char *filename = NULL;
	size_t namelen;

	if (!fullPath && !fileName) {
		goto out;
	}

	if (fileID < kHFSFirstUserCatalogNodeID) {
		curStatus = F_RESERVE_FILEID;
		err = paramErr;
		goto out;
	}

	isHFSPlus = VolumeObjectIsHFSPlus();

	if (isHFSPlus) {
		filename = malloc(kHFSPlusMaxFileNameChars * 3 + 1);
	} else {
		filename = malloc(kHFSMaxFileNameChars + 1);
	}
	if (!filename) {
		err = memFullErr;
#if DEBUG_OVERLAP
		printf ("%s: Not enough memory (err=%d)\n", __FUNCTION__, err);
#endif
		goto out;
	}

	while (fileID != kHFSRootFolderID) {
		/* lookup for thread record for this fileID */
		BuildCatalogKey(fileID, NULL, isHFSPlus, &catKey);
		err = SearchBTreeRecord(GPtr->calculatedCatalogFCB, &catKey, kNoHint,
								&catKey, &catRecord, &recordSize, &hint);
		if (err) {
#if DEBUG_OVERLAP
			printf ("%s: Error finding thread record for fileID = %d (err=%d)\n", __FUNCTION__, fileID, err);
#endif
			goto out;
		}

		/* Check if this is indeed a thread record */
		if ((catRecord.hfsPlusThread.recordType != kHFSPlusFileThreadRecord) &&
			(catRecord.hfsPlusThread.recordType != kHFSPlusFolderThreadRecord) &&
		    (catRecord.hfsThread.recordType != kHFSFileThreadRecord) &&
		    (catRecord.hfsThread.recordType != kHFSFolderThreadRecord)) {
			err = paramErr;
#if DEBUG_OVERLAP
			printf ("%s: Error finding valid thread record for fileID = %d\n", __FUNCTION__, fileID);
#endif
			goto out;
		}
								
		/* Convert the name string to utf8 */
		if (isHFSPlus) {
			(void) utf_encodestr(catRecord.hfsPlusThread.nodeName.unicode, 
								 catRecord.hfsPlusThread.nodeName.length * 2,
								 filename, &namelen);
		} else {
			namelen = catRecord.hfsThread.nodeName[0];
			memcpy (filename, catKey.hfs.nodeName, namelen);
		}

		/* Store the path name in LIFO linked list */
		curPtr = malloc(sizeof(struct fsPathString));
		if (!curPtr) {
			err = memFullErr;
#if DEBUG_OVERLAP
			printf ("%s: Not enough memory (err=%d)\n", __FUNCTION__, err);
#endif
			goto out;
		}

		/* Do not NULL terminate the string */
		curPtr->namelen = namelen;
		curPtr->name = malloc(namelen);
		if (!curPtr->name) {
			err = memFullErr;
#if DEBUG_OVERLAP
			printf ("%s: Not enough memory (err=%d)\n", __FUNCTION__, err);
#endif
		}
		memcpy (curPtr->name, filename, namelen); 
		curPtr->childPtr = listHeadPtr;
		listHeadPtr = curPtr;
		if (listTailPtr == NULL) {
			listTailPtr = curPtr;
		}
		
		/* lookup for parentID */
		if (isHFSPlus) {
			fileID = catRecord.hfsPlusThread.parentID;
		} else {
			fileID = catRecord.hfsThread.parentID;
		}
	
		/* no need to find entire path, bail out */
		if (fullPath == NULL) {
			break;
		}
	}

	/* return the name of the file/directory */
	if (fileName) {
		/* Do not overflow the buffer length passed */
		if (*fileNameLen < (listTailPtr->namelen + 1)) {
			*fileNameLen = *fileNameLen - 1;
			curStatus |= FNAME_BUF2SMALL;
		} else {
			*fileNameLen = listTailPtr->namelen;
		}
		if (*fileNameLen > NAME_MAX) {
			curStatus |= FNAME_BIGNAME;
		}
		memcpy (fileName, listTailPtr->name, *fileNameLen);
		fileName[*fileNameLen] = '\0';
	}

	/* return the full path of the file/directory */
	if (fullPath) {
		/* Do not overflow the buffer length passed and reserve last byte for NULL termination */
		unsigned int bytesRemain = *fullPathLen - 1;

		*fullPathLen = 0;
		while (listHeadPtr != NULL) {
			if (bytesRemain == 0) {
				break;
			}
			memcpy ((fullPath + *fullPathLen), "/", 1);
			*fullPathLen += 1;
			bytesRemain--; 

			if (bytesRemain == 0) {
				break;
			}
			if (bytesRemain < listHeadPtr->namelen) {
				namelen = bytesRemain;
				curStatus |= FPATH_BUF2SMALL;
			} else {
				namelen = listHeadPtr->namelen;
			}
			if (namelen > NAME_MAX) {
				curStatus |= FPATH_BIGNAME;
			}
			memcpy ((fullPath + *fullPathLen), listHeadPtr->name, namelen);
			*fullPathLen += namelen;
			bytesRemain -= namelen;

			curPtr = listHeadPtr;
			listHeadPtr = listHeadPtr->childPtr;
			free(curPtr->name);
			free(curPtr);
		}

		fullPath[*fullPathLen] = '\0';
	}

	err = noErr;

out:
	if (status) {
		*status = curStatus;
	}

	/* free any remaining allocated memory */
	while (listHeadPtr != NULL) {
		curPtr = listHeadPtr;
		listHeadPtr = listHeadPtr->childPtr;
		if (curPtr->name) {
			free (curPtr->name);
		}
		free (curPtr);
	}
	if (filename) {
		free (filename);
	}
	
	return err;
} /* GetFileNamePathByID */

/* Function: CopyDiskBlocks
 *
 * Description: Copy data from source extent to destination extent 
 * for blockCount on the disk.
 *
 * Input: 
 *	1. GPtr - pointer to global scavenger structure.
 * 	2. startAllocationBlock - startBlock for old extent
 * 	3. blockCount - total blocks to copy
 * 	4. newStartAllocationBlock - startBlock for new extent
 *
 * Output:
 * 	err, zero on success, non-zero on failure.
 *		memFullErr - Not enough memory
 */
OSErr CopyDiskBlocks(SGlobPtr GPtr, const UInt32 startAllocationBlock, const UInt32 blockCount, const UInt32 newStartAllocationBlock )
{
	OSErr err = noErr;
	int i;
	int drive;
	char *tmpBuffer = NULL;
	SVCB *vcb;
	UInt32 sectorsPerBlock;
	UInt32 sectorsInBuffer;
	UInt32 ioReqCount;
	UInt32 oldDiskBlock;
	UInt32 newDiskBlock;
	UInt32 actBytes;
	UInt32 numberOfBuffersToWrite;

	tmpBuffer = malloc(DISK_IOSIZE);
	if (!tmpBuffer) {
		err = memFullErr;
#if DEBUG_OVERLAP
		printf ("%s: Not enough memory (err=%d)\n", __FUNCTION__, err);
#endif
		goto out;
	}
	
	vcb = GPtr->calculatedVCB;
	drive = vcb->vcbDriveNumber;
	sectorsPerBlock = vcb->vcbBlockSize / Blk_Size;
	ioReqCount = DISK_IOSIZE;
	sectorsInBuffer = DISK_IOSIZE / Blk_Size;
	numberOfBuffersToWrite = ((blockCount * sectorsPerBlock) + sectorsInBuffer - 1) / sectorsInBuffer; 

	/*
	 * Make sure all changes to the source blocks have been flushed to disk
	 * so that we end up copying current content.  And we might as well
	 * remove the old blocks since we'll never refer to them again.
	 */
	CacheFlushRange(vcb->vcbBlockCache,
					startAllocationBlock * vcb->vcbBlockSize,
					blockCount * vcb->vcbBlockSize,
					true);


	for (i=0; i<numberOfBuffersToWrite; i++) {
		if (i == (numberOfBuffersToWrite - 1)) {
			/* last buffer */	
			ioReqCount = ((blockCount * sectorsPerBlock) - (i * sectorsInBuffer)) * Blk_Size;
		}
		
		/* Calculate the old disk block offset */
		oldDiskBlock = vcb->vcbAlBlSt + (sectorsPerBlock * startAllocationBlock) + (i * sectorsInBuffer);

		/* Read up to one buffer full */
		err = DeviceRead(vcb->vcbDriverReadRef, drive, tmpBuffer, 
						 (SInt64)((UInt64)oldDiskBlock << Log2BlkLo), ioReqCount, &actBytes);
		if (err != noErr) {
			goto out;
		}
		
		/* Calculate the new disk block offset */
		newDiskBlock = vcb->vcbAlBlSt + (sectorsPerBlock * newStartAllocationBlock) + (i * sectorsInBuffer);

		/* Write up to one buffer full */
		err = DeviceWrite(vcb->vcbDriverWriteRef, drive, tmpBuffer, 
						  (SInt64)((UInt64)newDiskBlock << Log2BlkLo), ioReqCount, &actBytes);
		if (err != noErr) {
			goto out;
		}
#if 0 // DEBUG_OVERLAP
		printf ("%s: Moved %d bytes of data from block %d to %d\n", __FUNCTION__, ioReqCount, oldDiskBlock, newDiskBlock);
#endif
	}

out:
	if (tmpBuffer) {
		free (tmpBuffer);
	}
	return err;
} /* CopyDiskBlocks */

/* Function: WriteDiskBlocks
 * 
 * Description: Write given buffer data to disk blocks.
 *
 * Input:
 *	1. GPtr - global scavenger structure pointer
 *	2. startBlock - starting block number for writing data.
 *	3. blockCount - total number of contiguous blocks to be written
 *	4. buffer - data buffer to be written to disk
 *	5. bufLen - length of data buffer to be written to disk.
 *
 * Output:
 * 	returns zero on success, non-zero on failure.
 *		memFullErr - Not enough memory
 */
OSErr WriteDiskBlocks(SGlobPtr GPtr, UInt32 startBlock, UInt32 blockCount, u_char *buffer, int bufLen) 
{
	OSErr err = noErr;
	int i;
	SVCB *vcb;
	int drive;
	u_char *dataBuffer;
	UInt32 sectorsPerBlock;
	UInt32 sectorsInBuffer;
	UInt32 ioReqCount;
	UInt32 diskBlock;
	UInt32 actBytes;
	UInt32 numberOfBuffersToWrite;
	UInt32 bufOffset = 0;

	dataBuffer = buffer;
	vcb = GPtr->calculatedVCB;
	drive = vcb->vcbDriveNumber;
	sectorsPerBlock = vcb->vcbBlockSize / Blk_Size;
	ioReqCount = DISK_IOSIZE;
	sectorsInBuffer = DISK_IOSIZE / Blk_Size;
	numberOfBuffersToWrite = ((blockCount * sectorsPerBlock) + sectorsInBuffer - 1) / sectorsInBuffer; 

	for (i=0; i<numberOfBuffersToWrite; i++) {
		if (i == (numberOfBuffersToWrite - 1)) {
			/* last buffer - should be Blk_Size multiple */	
			ioReqCount = bufLen - bufOffset;
			if (ioReqCount % Blk_Size) {
				ioReqCount = ((ioReqCount / Blk_Size) + 1) * Blk_Size;
			} else {
				ioReqCount = (ioReqCount / Blk_Size) * Blk_Size;
			}
			
			dataBuffer = calloc (1, ioReqCount);
			if (!dataBuffer) {
				err = memFullErr;
				goto out;
			}

			memcpy (dataBuffer, buffer + bufOffset, (bufLen - bufOffset));
			bufOffset = 0;
		}
		
		/* Calculate the new disk block offset */
		diskBlock = vcb->vcbAlBlSt + (sectorsPerBlock * startBlock) + (i * sectorsInBuffer);
		
		/* Write up to one buffer full */
		err = DeviceWrite(vcb->vcbDriverWriteRef, drive, dataBuffer + bufOffset, 
						 (SInt64)((UInt64)diskBlock << Log2BlkLo), ioReqCount, &actBytes);
		if (err != noErr) {
			goto out;
		}

		bufOffset += ioReqCount;
	}

out:
	if (dataBuffer != buffer) {
		free (dataBuffer);
	}
	return err;
} /* WriteDiskBlocks */

//	2210409, in System 8.1, moving file or folder would cause HFS+ thread records to be
//	520 bytes in size.  We only shrink the threads if other repairs are needed.
static	OSErr	FixBloatedThreadRecords( SGlob *GPtr )
{
	CatalogRecord		record;
	CatalogKey			foundKey;
	UInt32				hint;
	UInt16 				recordSize;
	SInt16				i = 0;
	OSErr				err;
	SInt16				selCode				= 0x8001;										//	 Start with 1st record

	err = GetBTreeRecord( GPtr->calculatedCatalogFCB, selCode, &foundKey, &record, &recordSize, &hint );
	ReturnIfError( err );

	selCode = 1;																//	 Get next record from now on		

	do
	{
		if ( ++i > 10 ) { (void) CheckForStop( GPtr ); i = 0; }					//	Spin the cursor every 10 entries
		
		if (  (recordSize == sizeof(HFSPlusCatalogThread)) && ((record.recordType == kHFSPlusFolderThreadRecord) || (record.recordType == kHFSPlusFileThreadRecord)) )
		{
			// HFS Plus has varaible sized threads so adjust to actual length
			recordSize -= ( sizeof(record.hfsPlusThread.nodeName.unicode) - (record.hfsPlusThread.nodeName.length * sizeof(UniChar)) );

			err = ReplaceBTreeRecord( GPtr->calculatedCatalogFCB, &foundKey, hint, &record, recordSize, &hint );
			ReturnIfError( err );
		}

		err = GetBTreeRecord( GPtr->calculatedCatalogFCB, selCode, &foundKey, &record, &recordSize, &hint );
	} while ( err == noErr );

	if ( err == btNotFound )
		err = noErr;
		
	return( err );
}


static OSErr
FixMissingThreadRecords( SGlob *GPtr )
{
	struct MissingThread *	mtp;
	FSBufferDescriptor    	btRecord;
	BTreeIterator         	iterator;
	OSStatus           		result;
	UInt16              	dataSize;
	Boolean					headsUp;
	UInt32					lostAndFoundDirID;

	lostAndFoundDirID = 0;
	headsUp = false;
	for (mtp = GPtr->missingThreadList; mtp != NULL; mtp = mtp->link) {
		if ( mtp->threadID == 0 )
			continue;

		// if the thread record information in the MissingThread struct is not there
		// then we have a missing directory in addition to a missing thread record 
		// for that directory.  We will recreate the missing directory in our 
		// lost+found directory.
		if ( mtp->thread.parentID == 0 ) {
			char 	myString[32];
			if ( lostAndFoundDirID == 0 )
				lostAndFoundDirID = CreateDirByName( GPtr , (u_char *)"lost+found", kHFSRootFolderID);
			if ( lostAndFoundDirID == 0 ) {
				if ( GPtr->logLevel >= kDebugLog )
					printf( "\tCould not create lost+found directory \n" );
				return( R_RFail );
			}
			sprintf( myString, "%ld", (long)mtp->threadID );
			PrintError( GPtr, E_NoDir, 1, myString );
			result = FixMissingDirectory( GPtr, mtp->threadID, lostAndFoundDirID );
			if ( result != 0 ) {
				if ( GPtr->logLevel >= kDebugLog )
					printf( "\tCould not recreate a missing directory \n" );
				return( R_RFail );
			}
			else
				headsUp = true;
			continue;
		}

		dataSize = 10 + (mtp->thread.nodeName.length * 2);
		btRecord.bufferAddress = (void *)&mtp->thread;
		btRecord.itemSize = dataSize;
		btRecord.itemCount = 1;
		iterator.hint.nodeNum = 0;
		BuildCatalogKey(mtp->threadID, NULL, true, (CatalogKey*)&iterator.key);

		result = BTInsertRecord(GPtr->calculatedCatalogFCB, &iterator, &btRecord, dataSize);
		if (result)
			return (IntError(GPtr, R_IntErr));
		mtp->threadID = 0;
	}
	if ( headsUp )
		PrintStatus( GPtr, M_Look, 0 );

	return (0);
}


static OSErr
FixMissingDirectory( SGlob *GPtr, UInt32 theObjID, UInt32 theParID )
{
	Boolean				isHFSPlus;
	UInt16				recSize;
	OSErr				result;		
	int					nameLen;
	UInt32				hint;		
	UInt32				myItemsCount;		
	char 				myString[ 32 ];
	CatalogName			myName;
	CatalogRecord		catRec;
	CatalogKey			myKey, myThreadKey;

	isHFSPlus = VolumeObjectIsHFSPlus( );
	
	// we will use the object ID of the missing directory as the name since we have
	// no way to find the original name and this should make it unique within our
	// lost+found directory.
	sprintf( myString, "%ld", (long)theObjID );
	nameLen = strlen( myString );

    if ( isHFSPlus )
    {
        int		i;
        myName.ustr.length = nameLen;
        for ( i = 0; i < myName.ustr.length; i++ )
            myName.ustr.unicode[ i ] = (u_int16_t) myString[ i ];
    }
    else
    {
        myName.pstr[0] = nameLen;
        memcpy( &myName.pstr[1], &myString[0], nameLen );
    }

	// make sure the name is not already used 
	BuildCatalogKey( theParID, &myName, isHFSPlus, &myKey );
	result = SearchBTreeRecord( GPtr->calculatedCatalogFCB, &myKey, kNoHint, 
								NULL, &catRec, &recSize, &hint );
	if ( result == noErr )
		return( R_IntErr );
	
    // insert new directory and thread record into the catalog
	recSize = BuildThreadRec( &myKey, &catRec, isHFSPlus, true );
	BuildCatalogKey( theObjID, NULL, isHFSPlus, &myThreadKey );
	result	= InsertBTreeRecord( GPtr->calculatedCatalogFCB, &myThreadKey, &catRec, recSize, &hint );
	if ( result != noErr )
		return( result );

	// need to look up all objects in the directory so we can set the valance
	result = SearchBTreeRecord( GPtr->calculatedCatalogFCB, &myThreadKey, kNoHint, 
								NULL, &catRec, &recSize, &hint );
	if ( result != noErr )
		return( result );

	myItemsCount = 0;
	for ( ;; ) {
		CatalogKey		foundKey;
		result = GetBTreeRecord( GPtr->calculatedCatalogFCB, 1, &foundKey, &catRec, &recSize, &hint );
		if ( result != noErr )
			break;
		if ( isHFSPlus ) {
			if ( foundKey.hfsPlus.parentID != theObjID )
				break;
		} else {
			if ( foundKey.hfs.parentID != theObjID )
				break;
		}
		if ( catRec.recordType == kHFSPlusFolderRecord || catRec.recordType == kHFSPlusFileRecord ||
			 catRec.recordType == kHFSFolderRecord || catRec.recordType == kHFSFileRecord ) {
			myItemsCount++;
		}
	}

	recSize = BuildFolderRec( 01777, theObjID, isHFSPlus, &catRec );
	if ( isHFSPlus )
		catRec.hfsPlusFolder.valence = myItemsCount;
	else
		catRec.hfsFolder.valence = myItemsCount;
	result	= InsertBTreeRecord( GPtr->calculatedCatalogFCB, &myKey, &catRec, recSize, &hint );
	if ( result != noErr )
		return( result );
	
	/* update parent directory to reflect addition of new directory */
	result = UpdateFolderCount( GPtr->calculatedVCB, theParID, NULL, 
								((isHFSPlus) ? kHFSPlusFolderRecord : kHFSFolderRecord), 
								kNoHint, 1 );

	/* update our header node on disk from our BTreeControlBlock */
	UpdateBTreeHeader( GPtr->calculatedCatalogFCB );
		
	return( result );
	
} /* FixMissingDirectory */


static HFSCatalogNodeID 
GetObjectID( CatalogRecord * theRecPtr )
{
    HFSCatalogNodeID	myObjID;
    
	switch ( theRecPtr->recordType ) {
	case kHFSPlusFolderRecord:
        myObjID = theRecPtr->hfsPlusFolder.folderID;
		break;
	case kHFSPlusFileRecord:
        myObjID = theRecPtr->hfsPlusFile.fileID;
		break;
	case kHFSFolderRecord:
        myObjID = theRecPtr->hfsFolder.folderID;
		break;
	case kHFSFileRecord:
        myObjID = theRecPtr->hfsFile.fileID;
		break;
	default:
        myObjID = 0;
	}
	
    return( myObjID );
    
} /* GetObjectID */

/* Function: CreateFileByName
 *
 * Description: Create a file with given fileName of type fileType containing
 * data of length dataLen.  This function assumes that the name of symlink
 * to be created is passed as UTF8
 *
 * Input:
 *	1. GPtr - pointer to global scavenger structure
 *	2. parentID - ID of parent directory to create the new file.
 *	3. fileName - name of the file to create in UTF8 format.  
 *	4. fileNameLen - length of the filename to be created.  
 *			If the volume is HFS Plus, the filename is delimited to
 *			kHFSPlusMaxFileNameChars characters.
 *			If the volume is plain HFS, the filename is delimited to
 *			kHFSMaxFileNameChars characters.
 *	5. fileType - file type (currently supported S_IFREG, S_IFLNK).
 *	6. data - data content of first data fork of the file
 *	7. dataLen - length of data to be written
 *
 * Output:
 *	returns zero on success, non-zero on failure.
 *		memFullErr - Not enough memory
 *		paramErr - Invalid paramter
 */
OSErr CreateFileByName(SGlobPtr GPtr, UInt32 parentID, UInt16 fileType, u_char *fileName, unsigned int filenameLen, u_char *data, unsigned int dataLen)
{	
	OSErr err = noErr;
	Boolean isHFSPlus;
	Boolean isCatUpdated = false;

	CatalogName fName;
	CatalogRecord catRecord;
	CatalogKey catKey;
	CatalogKey threadKey;
	UInt32 hint;
	UInt16 recordSize;

	UInt32 startBlock = 0;
	UInt32 blockCount = 0;
	UInt32 nextCNID;

	isHFSPlus = VolumeObjectIsHFSPlus();

	/* Construct unicode name for file name to construct catalog key */
	if (isHFSPlus) {
		/* Convert utf8 filename to Unicode filename */
		size_t namelen;

		if (filenameLen < kHFSPlusMaxFileNameChars) {
			(void) utf_decodestr (fileName, filenameLen, fName.ustr.unicode, &namelen);
			namelen /= 2;
			fName.ustr.length = namelen;
		} else {
			/* The resulting may result in more than kHFSPlusMaxFileNameChars chars */
			UInt16 *unicodename;

			/* Allocate a large array to convert the utf-8 to utf-16 */
			unicodename = malloc (filenameLen * 4);
			if (unicodename == NULL) {
				err = memFullErr;
				goto out;
			}

			(void) utf_decodestr (fileName, filenameLen, unicodename, &namelen);
			namelen /= 2;

			/* Chopping unicode string based on length might affect unicode 
			 * chars that take more than one UInt16 - very rare possiblity.
			 */
			if (namelen > kHFSPlusMaxFileNameChars) {
				namelen = kHFSPlusMaxFileNameChars;
			}

			memcpy (fName.ustr.unicode, unicodename, (namelen * 2));
			free (unicodename);
			fName.ustr.length = namelen;
		}
	} else {
		if (filenameLen > kHFSMaxFileNameChars) {
			filenameLen = kHFSMaxFileNameChars;
		}
		fName.pstr[0] = filenameLen;
		memcpy(&fName.pstr[1], fileName, filenameLen);
	}

	/* Make sure that a file with same name does not exist in parent dir */
	BuildCatalogKey(parentID, &fName, isHFSPlus, &catKey);
	err = SearchBTreeRecord(GPtr->calculatedCatalogFCB, &catKey, kNoHint, NULL, 
							&catRecord, &recordSize, &hint);
	if (err != fsBTRecordNotFoundErr) {
#if DEBUG_OVERLAP
		printf ("%s: %s probably exists in dirID = %d (err=%d)\n", __FUNCTION__, fileName, parentID, err);
#endif
		err = EEXIST;
		goto out;
	}

	if (data) {
		/* Calculate correct number of blocks required for data */
		if (dataLen % (GPtr->calculatedVCB->vcbBlockSize)) {
			blockCount = (dataLen / (GPtr->calculatedVCB->vcbBlockSize)) + 1;
		} else {
			blockCount = dataLen / (GPtr->calculatedVCB->vcbBlockSize);
		}
	
		if (blockCount) {
			/* Allocate disk space for the data */
			err = AllocateContigBitmapBits (GPtr->calculatedVCB, blockCount, &startBlock);
			if (err != noErr) {
#if DEBUG_OVERLAP
				printf ("%s: Not enough disk space (err=%d)\n", __FUNCTION__, err);
#endif
				goto out;
			}

			/* Write the data to the blocks */
			err = WriteDiskBlocks(GPtr, startBlock, blockCount, data, dataLen);
			if (err != noErr) {
#if DEBUG_OVERLAP
				printf ("%s: Error in writing data of %s to disk (err=%d)\n", __FUNCTION__, fileName, err);
#endif
				goto out;
			}
		}
	}

	/* Build and insert thread record */
	nextCNID = GPtr->calculatedVCB->vcbNextCatalogID;
	if (!isHFSPlus && nextCNID == 0xffffFFFF) {
		goto out;
	}
	recordSize = BuildThreadRec(&catKey, &catRecord, isHFSPlus, false);
	for (;;) {
		BuildCatalogKey(nextCNID, NULL, isHFSPlus, &threadKey);
		err	= InsertBTreeRecord(GPtr->calculatedCatalogFCB, &threadKey, &catRecord,
								recordSize, &hint );
		if (err == fsBTDuplicateRecordErr && isHFSPlus) {
			/* Allow CNIDs on HFS Plus volumes to wrap around */
			++nextCNID;
			if (nextCNID < kHFSFirstUserCatalogNodeID) {
				GPtr->calculatedVCB->vcbAttributes |= kHFSCatalogNodeIDsReusedMask;
				MarkVCBDirty(GPtr->calculatedVCB);
				nextCNID = kHFSFirstUserCatalogNodeID;
			}
			continue;
		}
		break;
	}
	if (err != noErr) {
#if DEBUG_OVERLAP
		printf ("%s: Error inserting thread record for file = %s (err=%d)\n", __FUNCTION__, fileName, err);
#endif
		goto out;
	}

	/* Build file record */
	recordSize = BuildFileRec(fileType, 0666, nextCNID, isHFSPlus, &catRecord);
	if (recordSize == 0) {
#if DEBUG_OVERLAP
		printf ("%s: Incorrect fileType\n", __FUNCTION__);
#endif

		/* Remove the thread record inserted above */
		err = DeleteBTreeRecord (GPtr->calculatedCatalogFCB, &threadKey);
		if (err != noErr) {
#if DEBUG_OVERLAP
			printf ("%s: Error in removing thread record\n", __FUNCTION__);
#endif
		}
		err = paramErr;
		goto out;
	}

	/* Update startBlock, blockCount, etc */
	if (isHFSPlus) {
		catRecord.hfsPlusFile.dataFork.logicalSize = dataLen; 
		catRecord.hfsPlusFile.dataFork.totalBlocks = blockCount;
		catRecord.hfsPlusFile.dataFork.extents[0].startBlock = startBlock;
		catRecord.hfsPlusFile.dataFork.extents[0].blockCount = blockCount;
	} else {
		catRecord.hfsFile.dataLogicalSize = dataLen;
		catRecord.hfsFile.dataPhysicalSize = blockCount * GPtr->calculatedVCB->vcbBlockSize;
		catRecord.hfsFile.dataExtents[0].startBlock = startBlock;
		catRecord.hfsFile.dataExtents[0].blockCount = blockCount;
	}

	/* Insert catalog file record */
    err	= InsertBTreeRecord(GPtr->calculatedCatalogFCB, &catKey, &catRecord, recordSize, &hint );
	if (err == noErr) {
		isCatUpdated = true;

#if DEBUG_OVERLAP
	printf ("Created \"%s\" with ID = %d startBlock = %d, blockCount = %d, dataLen = %d\n", fileName, nextCNID, startBlock, blockCount, dataLen);
#endif
	} else {
#if DEBUG_OVERLAP
		printf ("%s: Error in inserting file record for file = %s (err=%d)\n", __FUNCTION__, fileName, err);
#endif

		/* remove the thread record inserted above */
		err = DeleteBTreeRecord (GPtr->calculatedCatalogFCB, &threadKey);
		if (err != noErr) {
#if DEBUG_OVERLAP
			printf ("%s: Error in removing thread record\n", __FUNCTION__);
#endif
		}
		err = paramErr;
		goto out;
	}

	/* Update volume header */
	GPtr->calculatedVCB->vcbNextCatalogID = nextCNID + 1;
	if (GPtr->calculatedVCB->vcbNextCatalogID < kHFSFirstUserCatalogNodeID) {
		GPtr->calculatedVCB->vcbAttributes |= kHFSCatalogNodeIDsReusedMask;
		GPtr->calculatedVCB->vcbNextCatalogID = kHFSFirstUserCatalogNodeID;
	}
	MarkVCBDirty( GPtr->calculatedVCB );
	
	/* update our header node on disk from our BTreeControlBlock */
	UpdateBTreeHeader(GPtr->calculatedCatalogFCB);

	/* update parent directory to reflect addition of new file */
	err = UpdateFolderCount(GPtr->calculatedVCB, parentID, NULL, kHFSPlusFileRecord, kNoHint, 1);
	if (err != noErr) {
#if DEBUG_OVERLAP
		printf ("%s: Error in updating parent folder count (err=%d)\n", __FUNCTION__, err);
#endif
		goto out;
	}

out:
	/* On error, if catalog record was not inserted and disk block were allocated,
	 * deallocate the blocks 
	 */
	if (err && (isCatUpdated == false) && startBlock) {
		ReleaseBitmapBits (startBlock, blockCount);
	}

	return err;
} /* CreateFileByName */

/* Function: CreateDirByName
 *
 * Description: Create directory with name dirName in a directory with ID as
 * parentID.  The function assumes that the dirName passed is ASCII.
 *
 * Input: 
 *	GPtr - global scavenger structure pointer
 * 	dirName - name of directory to be created
 *	parentID - dirID of the parent directory for new directory
 *
 * Output:
 * 	on success, ID of the new directory created.
 * 	on failure, zero.
 *  
 */
UInt32 CreateDirByName(SGlob *GPtr , const u_char *dirName, const UInt32 parentID)
{
	Boolean				isHFSPlus;
	UInt16				recSize;
	UInt16				myMode;
	int					result;		
	int					nameLen;
	UInt32				hint;		
	UInt32				nextCNID;		
	SFCB *				fcbPtr;
	CatalogKey			myKey;
	CatalogName			myName;
	CatalogRecord		catRec;
	
	isHFSPlus = VolumeObjectIsHFSPlus( );
  	fcbPtr = GPtr->calculatedCatalogFCB;
	nameLen = strlen( (char *)dirName );

    if ( isHFSPlus )
    {
        int		i;
        myName.ustr.length = nameLen;
        for ( i = 0; i < myName.ustr.length; i++ )
            myName.ustr.unicode[ i ] = (u_int16_t) dirName[ i ];
    }
    else
    {
        myName.pstr[0] = nameLen;
        memcpy( &myName.pstr[1], &dirName[0], nameLen );
    }

	// see if we already have a lost and found directory
	BuildCatalogKey( parentID, &myName, isHFSPlus, &myKey );
	result = SearchBTreeRecord( fcbPtr, &myKey, kNoHint, NULL, &catRec, &recSize, &hint );
	if ( result == noErr ) {
		if ( isHFSPlus ) {
			if ( catRec.recordType == kHFSPlusFolderRecord )
				return( catRec.hfsPlusFolder.folderID ); 
		}
		else if ( catRec.recordType == kHFSFolderRecord )
			return( catRec.hfsFolder.folderID ); 	
        return( 0 );  // something already there but not a directory
	}
  
    // insert new directory and thread record into the catalog
	nextCNID = GPtr->calculatedVCB->vcbNextCatalogID;
	if ( !isHFSPlus && nextCNID == 0xFFFFFFFF )
		return( 0 );

	recSize = BuildThreadRec( &myKey, &catRec, isHFSPlus, true );
	for (;;) {
		CatalogKey			key;
		
		BuildCatalogKey( nextCNID, NULL, isHFSPlus, &key );
		result	= InsertBTreeRecord( fcbPtr, &key, &catRec, recSize, &hint );
		if ( result == fsBTDuplicateRecordErr && isHFSPlus ) {
			/*
			 * Allow CNIDs on HFS Plus volumes to wrap around
			 */
			++nextCNID;
			if ( nextCNID < kHFSFirstUserCatalogNodeID ) {
				GPtr->calculatedVCB->vcbAttributes |= kHFSCatalogNodeIDsReusedMask;
				MarkVCBDirty( GPtr->calculatedVCB );
				nextCNID = kHFSFirstUserCatalogNodeID;
			}
			continue;
		}
		break;
	}
	if ( result != 0 )
		return( 0 ); 	
	
	myMode = ( GPtr->lostAndFoundMode == 0 ) ? 01777 : GPtr->lostAndFoundMode;
	recSize = BuildFolderRec( myMode, nextCNID, isHFSPlus, &catRec );
    result	= InsertBTreeRecord( fcbPtr, &myKey, &catRec, recSize, &hint );
	if ( result != 0 )
		return( 0 );

	/* Update volume header */
	GPtr->calculatedVCB->vcbNextCatalogID = nextCNID + 1;
	if ( GPtr->calculatedVCB->vcbNextCatalogID < kHFSFirstUserCatalogNodeID ) {
		GPtr->calculatedVCB->vcbAttributes |= kHFSCatalogNodeIDsReusedMask;
		GPtr->calculatedVCB->vcbNextCatalogID = kHFSFirstUserCatalogNodeID;
	}
	MarkVCBDirty( GPtr->calculatedVCB );
	
	/* update parent directory to reflect addition of new directory */
	result = UpdateFolderCount( GPtr->calculatedVCB, parentID, NULL, kHFSPlusFolderRecord, kNoHint, 1 );

	/* update our header node on disk from our BTreeControlBlock */
	UpdateBTreeHeader( GPtr->calculatedCatalogFCB );

	return( nextCNID );

} /* CreateDirByName */

/*
 * Build a catalog node folder record with the given input.
 */
static int
BuildFolderRec( u_int16_t theMode, UInt32 theObjID, Boolean isHFSPlus, CatalogRecord * theRecPtr )
{
	UInt16				recSize;
	UInt32 				createTime;
	
	ClearMemory( (Ptr)theRecPtr, sizeof(*theRecPtr) );
	
	if ( isHFSPlus ) {
		createTime = GetTimeUTC();
		theRecPtr->hfsPlusFolder.recordType = kHFSPlusFolderRecord;
		theRecPtr->hfsPlusFolder.folderID = theObjID;
		theRecPtr->hfsPlusFolder.createDate = createTime;
		theRecPtr->hfsPlusFolder.contentModDate = createTime;
		theRecPtr->hfsPlusFolder.attributeModDate = createTime;
		theRecPtr->hfsPlusFolder.bsdInfo.ownerID = getuid( );
		theRecPtr->hfsPlusFolder.bsdInfo.groupID = getgid( );
		theRecPtr->hfsPlusFolder.bsdInfo.fileMode = S_IFDIR;
		theRecPtr->hfsPlusFolder.bsdInfo.fileMode |= theMode;
		recSize= sizeof(HFSPlusCatalogFolder);
	}
	else {
		createTime = GetTimeLocal( true );
		theRecPtr->hfsFolder.recordType = kHFSFolderRecord;
		theRecPtr->hfsFolder.folderID = theObjID;
		theRecPtr->hfsFolder.createDate = createTime;
		theRecPtr->hfsFolder.modifyDate = createTime;
		recSize= sizeof(HFSCatalogFolder);
	}

	return( recSize );
	
} /* BuildFolderRec */


/*
 * Build a catalog node thread record from a catalog key
 * and return the size of the record.
 */
static int
BuildThreadRec( CatalogKey * theKeyPtr, CatalogRecord * theRecPtr, 
				Boolean isHFSPlus, Boolean isDirectory )
{
	int size = 0;

	if ( isHFSPlus ) {
		HFSPlusCatalogKey *key = (HFSPlusCatalogKey *)theKeyPtr;
		HFSPlusCatalogThread *rec = (HFSPlusCatalogThread *)theRecPtr;

		size = sizeof(HFSPlusCatalogThread);
		if ( isDirectory )
			rec->recordType = kHFSPlusFolderThreadRecord;
		else
			rec->recordType = kHFSPlusFileThreadRecord;
		rec->reserved = 0;
		rec->parentID = key->parentID;			
		bcopy(&key->nodeName, &rec->nodeName,
			sizeof(UniChar) * (key->nodeName.length + 1));

		/* HFS Plus has varaible sized thread records */
		size -= (sizeof(rec->nodeName.unicode) -
			  (rec->nodeName.length * sizeof(UniChar)));
	} 
	else /* HFS standard */ {
		HFSCatalogKey *key = (HFSCatalogKey *)theKeyPtr;
		HFSCatalogThread *rec = (HFSCatalogThread *)theRecPtr;

		size = sizeof(HFSCatalogThread);
		bzero(rec, size);
		if ( isDirectory )
			rec->recordType = kHFSFolderThreadRecord;
		else
			rec->recordType = kHFSFileThreadRecord;
		rec->parentID = key->parentID;
		bcopy(key->nodeName, rec->nodeName, key->nodeName[0]+1);
	}
	
	return (size);
	
} /* BuildThreadRec */

/* Function: BuildFileRec
 *
 * Description: Build a catalog file record with given fileID, fileType 
 * and fileMode.
 *
 * Input:
 *	1. fileType - currently supports S_IFREG, S_IFLNK
 *	2. fileMode - file mode desired.
 *	3. fileID - file ID
 *	4. isHFSPlus - indicates whether the record is being created for 
 *	HFSPlus volume or plain HFS volume.
 *	5. catRecord - pointer to catalog record
 *
 * Output:
 *	returns size of the catalog record.
 *	on success, non-zero value; on failure, zero.
 */
static int BuildFileRec(UInt16 fileType, UInt16 fileMode, UInt32 fileID, Boolean isHFSPlus, CatalogRecord *catRecord)
{
	UInt16 recordSize = 0;
	UInt32 createTime;
	
	/* We only support creating S_IFREG and S_IFLNK and S_IFLNK is not supported
	 * on plain HFS 
	 */
	if (((fileType != S_IFREG) && (fileType != S_IFLNK)) || 
	 	((isHFSPlus == false) && (fileType == S_IFLNK))) {
		goto out;
	}

	ClearMemory((Ptr)catRecord, sizeof(*catRecord));
	
	if ( isHFSPlus ) {
		createTime = GetTimeUTC();
		catRecord->hfsPlusFile.recordType = kHFSPlusFileRecord;
		catRecord->hfsPlusFile.fileID = fileID;
		catRecord->hfsPlusFile.createDate = createTime;
		catRecord->hfsPlusFile.contentModDate = createTime;
		catRecord->hfsPlusFile.attributeModDate = createTime;
		catRecord->hfsPlusFile.bsdInfo.ownerID = getuid();
		catRecord->hfsPlusFile.bsdInfo.groupID = getgid();
		catRecord->hfsPlusFile.bsdInfo.fileMode = fileType;
		catRecord->hfsPlusFile.bsdInfo.fileMode |= fileMode;
		if (fileType == S_IFLNK) {
			catRecord->hfsPlusFile.userInfo.fdType = kSymLinkFileType;
			catRecord->hfsPlusFile.userInfo.fdCreator = kSymLinkCreator;
		} else {
			catRecord->hfsPlusFile.userInfo.fdType = kTextFileType;
			catRecord->hfsPlusFile.userInfo.fdCreator = kTextFileCreator;
		}
		recordSize= sizeof(HFSPlusCatalogFile);
	}
	else {
		createTime = GetTimeLocal(true);
		catRecord->hfsFile.recordType = kHFSFileRecord;
		catRecord->hfsFile.fileID = fileID;
		catRecord->hfsFile.createDate = createTime;
		catRecord->hfsFile.modifyDate = createTime;
		catRecord->hfsFile.userInfo.fdType = kTextFileType;
		catRecord->hfsFile.userInfo.fdCreator = kTextFileCreator;
		recordSize= sizeof(HFSCatalogFile);
	}

out:
	return(recordSize);
} /* BuildFileRec */

/* Function: BuildAttributeKey
 *
 * Build attribute key based on given information like -
 * fileID, startBlock, attribute name and attribute name length.
 * 
 * Note that the attribute name is the UTF-8 format string.
 */
static void BuildAttributeKey(u_int32_t fileID, u_int32_t startBlock, 
			unsigned char *attrName, u_int16_t attrNameLen, HFSPlusAttrKey *key)
{
	size_t attrNameLenBytes;

	assert(VolumeObjectIsHFSPlus() == true);

	key->pad = 0;
	key->fileID = fileID;
	key->startBlock = startBlock;

	/* Convert UTF-8 attribute name to unicode */
	(void) utf_decodestr(attrName, attrNameLen, key->attrName, &attrNameLenBytes);
	key->attrNameLen = attrNameLenBytes / 2;

	key->keyLength = kHFSPlusAttrKeyMinimumLength + attrNameLenBytes;
}