summaryrefslogtreecommitdiff
path: root/FreeRTOS-Labs/Source/FreeRTOS-Plus-FAT/ff_file.c
blob: 8d19c1bb06390cd7acfefc3b64349738795438b8 (plain)
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
/*
 * FreeRTOS+FAT build 191128 - Note:  FreeRTOS+FAT is still in the lab!
 * Copyright (C) 2018 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
 * Authors include James Walmsley, Hein Tibosch and Richard Barry
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * https://www.FreeRTOS.org
 *
 */

/**
 *	@file		ff_file.c
 *	@ingroup	FILEIO
 *
 *	@defgroup	FILEIO FILE I/O Access
 *	@brief		Provides an interface to allow File I/O on a mounted IOMAN.
 *
 *	Provides file-system interfaces for the FAT file-system.
 **/

#include "ff_headers.h"

#if( ffconfigUNICODE_UTF16_SUPPORT != 0 )
#include <wchar.h>
#endif

static FF_Error_t FF_Truncate( FF_FILE *pxFile, BaseType_t bClosing );

static int32_t FF_ReadPartial( FF_FILE *pxFile, uint32_t ulItemLBA, uint32_t ulRelBlockPos, uint32_t ulCount,
	uint8_t *pucBuffer, FF_Error_t *pxError );

static int32_t FF_WritePartial( FF_FILE *pxFile, uint32_t ulItemLBA, uint32_t ulRelBlockPos, uint32_t ulCount,
	const uint8_t *pucBuffer, FF_Error_t *pxError );

static uint32_t FF_SetCluster( FF_FILE *pxFile, FF_Error_t *pxError );
static uint32_t FF_FileLBA( FF_FILE *pxFile );

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

/**
 *	@public
 *	@brief	Converts STDIO mode strings into the equivalent FreeRTOS+FAT mode.
 *
 *	@param	Mode	The mode string e.g. "rb" "rb+" "w" "a" "r" "w+" "a+" etc
 *
 *	@return	Returns the mode bits that should be passed to the FF_Open function.
 **/
uint8_t FF_GetModeBits( const char *pcMode )
{
uint8_t ucModeBits = 0x00;

	while( *pcMode != '\0' )
	{
		switch( *pcMode )
		{
			case 'r':						/* Allow Read. */
			case 'R':
				ucModeBits |= FF_MODE_READ;
				break;

			case 'w':						/* Allow Write. */
			case 'W':
				ucModeBits |= FF_MODE_WRITE;
				ucModeBits |= FF_MODE_CREATE; /* Create if not exist. */
				ucModeBits |= FF_MODE_TRUNCATE;
				break;

			case 'a':						/* Append new writes to the end of the file. */
			case 'A':
				ucModeBits |= FF_MODE_WRITE;
				ucModeBits |= FF_MODE_APPEND;
				ucModeBits |= FF_MODE_CREATE; /* Create if not exist. */
				break;

			case '+':						/* Update the file, don't Append! */
				ucModeBits |= FF_MODE_READ;
				ucModeBits |= FF_MODE_WRITE;	/* RW Mode. */
				break;

			case 'D':
				/* Internal use only! */
				ucModeBits |= FF_MODE_DIR;
				break;

			case 'b':
			case 'B':
				/* b|B flags not supported (Binary mode is native anyway). */
				break;

			default:
				break;
		}

		pcMode++;
	}

	return ucModeBits;
}	/* FF_GetModeBits() */
/*-----------------------------------------------------------*/

static FF_FILE *prvAllocFileHandle( FF_IOManager_t *pxIOManager, FF_Error_t *pxError )
{
FF_FILE *pxFile;

	pxFile = ffconfigMALLOC( sizeof( FF_FILE ) );
	if( pxFile == NULL )
	{
		*pxError = ( FF_Error_t ) ( FF_ERR_NOT_ENOUGH_MEMORY | FF_OPEN );
	}
	else
	{
		memset( pxFile, 0, sizeof( *pxFile ) );

		#if( ffconfigOPTIMISE_UNALIGNED_ACCESS != 0 )
		{
			pxFile->pucBuffer = ( uint8_t * ) ffconfigMALLOC( pxIOManager->usSectorSize );
			if( pxFile->pucBuffer != NULL )
			{
				memset( pxFile->pucBuffer, 0, pxIOManager->usSectorSize );
			}
			else
			{
				*pxError = ( FF_Error_t ) ( FF_ERR_NOT_ENOUGH_MEMORY | FF_OPEN );
				ffconfigFREE( pxFile );
				/* Make sure that NULL will be returned. */
				pxFile = NULL;
			}
		}
		#else
		{
			/* Remove compiler warnings. */
			( void ) pxIOManager;
		}
		#endif
	}

	return pxFile;
}	/* prvAllocFileHandle() */
/*-----------------------------------------------------------*/

/**
 * FF_Open() Mode Information
 * - FF_MODE_WRITE
 *   - Allows WRITE access to the file.
 *   .
 * - FF_MODE_READ
 *   - Allows READ access to the file.
 *   .
 * - FF_MODE_CREATE
 *   - Create file if it doesn't exist.
 *   .
 * - FF_MODE_TRUNCATE
 *   - Erase the file if it already exists and overwrite.
 *   *
 * - FF_MODE_APPEND
 *   - Causes all writes to occur at the end of the file. (Its impossible to overwrite other data in a file with this flag set).
 *   .
 * .
 *
 * Some sample modes:
 * - (FF_MODE_WRITE | FF_MODE_CREATE | FF_MODE_TRUNCATE)
 *   - Write access to the file. (Equivalent to "w").
 *   .
 * - (FF_MODE_WRITE | FF_MODE_READ)
 *   - Read and Write access to the file. (Equivalent to "rb+").
 *   .
 * - (FF_MODE_WRITE | FF_MODE_READ | FF_MODE_APPEND | FF_MODE_CREATE)
 *   - Read and Write append mode access to the file. (Equivalent to "a+").
 *   .
 * .
 * Be careful when choosing modes. For those using FF_Open() at the application layer
 * its best to use the provided FF_GetModeBits() function, as this complies to the same
 * behaviour as the stdio.h fopen() function.
 *
 **/

/**
 *	@public
 *	@brief	Opens a File for Access
 *
 *	@param	pxIOManager	FF_IOManager_t object that was created by FF_CreateIOManger().
 *	@param	pcPath		Path to the File or object.
 *	@param	ucMode		Access Mode required. Modes are a little complicated, the function FF_GetModeBits()
 *	@param	ucMode		will convert a stdio Mode string into the equivalent Mode bits for this parameter.
 *	@param	pxError		Pointer to a signed byte for error checking. Can be NULL if not required.
 *	@param	pxError		To be checked when a NULL pointer is returned.
 *
 *	@return	NULL pointer on error, in which case pxError should be checked for more information.
 *	@return	pxError can be:
 **/
#if( ffconfigUNICODE_UTF16_SUPPORT != 0 )
FF_FILE *FF_Open( FF_IOManager_t *pxIOManager, const FF_T_WCHAR *pcPath, uint8_t ucMode, FF_Error_t *pxError )
#else
FF_FILE *FF_Open( FF_IOManager_t *pxIOManager, const char *pcPath, uint8_t ucMode, FF_Error_t *pxError )
#endif
{
FF_FILE *pxFile = NULL;
FF_FILE *pxFileChain;
FF_DirEnt_t xDirEntry;
uint32_t ulFileCluster;
FF_Error_t xError;
BaseType_t xIndex;
FF_FindParams_t xFindParams;
#if( ffconfigUNICODE_UTF16_SUPPORT != 0 )
	FF_T_WCHAR pcFileName[ ffconfigMAX_FILENAME ];
#else
	char pcFileName[ ffconfigMAX_FILENAME ];
#endif

	memset( &xFindParams, '\0', sizeof( xFindParams ) );

	/* Inform the functions that the entry will be created if not found. */
	if( ( ucMode & FF_MODE_CREATE ) != 0 )
	{
		xFindParams.ulFlags |= FIND_FLAG_CREATE_FLAG;
	}

	if( pxIOManager == NULL )
	{
		/* Use the error function code 'FF_OPEN' as this static
		function is only called from that function. */
		xError = ( FF_Error_t ) ( FF_ERR_NULL_POINTER | FF_OPEN );
	}
#if( ffconfigREMOVABLE_MEDIA != 0 )
	else if( ( pxIOManager->ucFlags & FF_IOMAN_DEVICE_IS_EXTRACTED ) != 0 )
	{
		xError = ( FF_Error_t ) ( FF_ERR_IOMAN_DRIVER_NOMEDIUM | FF_OPEN );
	}
#endif /* ffconfigREMOVABLE_MEDIA */
	else
	{
		xError = FF_ERR_NONE;

		/* Let xIndex point to the last occurrence of '/' or '\',
		to separate the path from the file name. */
		xIndex = ( BaseType_t ) STRLEN( pcPath );
		while( xIndex != 0 )
		{
			if( ( pcPath[ xIndex ] == '\\' ) || ( pcPath[ xIndex ] == '/' ) )
			{
				break;
			}
			xIndex--;
		}

		/* Copy the file name, i.e. the string that comes after the last separator. */
		STRNCPY( pcFileName, pcPath + xIndex + 1, ffconfigMAX_FILENAME );

		if( xIndex == 0 )
		{
			/* Only for the root, the slash is part of the directory name.
			'xIndex' now equals to the length of the path name. */
			xIndex = 1;
		}

		/* FF_CreateShortName() might set flags FIND_FLAG_FITS_SHORT and FIND_FLAG_SIZE_OK. */
		FF_CreateShortName( &xFindParams, pcFileName );

		/* Lookup the path and find the cluster pointing to the directory: */
		xFindParams.ulDirCluster = FF_FindDir( pxIOManager, pcPath, xIndex, &xError );
		if( xFindParams.ulDirCluster == 0ul )
		{
			if( ( ucMode & FF_MODE_WRITE ) != 0 )
			{
				FF_PRINTF( "FF_Open[%s]: Path not found\n", pcPath );
			}
			/* The user tries to open a file but the path leading to the file does not exist. */
		}
		else if( FF_isERR( xError ) == pdFALSE )
		{
			/* Allocate an empty file handle and buffer space for 'unaligned access'. */
			pxFile = prvAllocFileHandle( pxIOManager, &xError );
		}
	}

	if( FF_isERR( xError ) == pdFALSE )
	{
		/* Copy the Mode Bits. */
		pxFile->ucMode = ucMode;

		/* See if the file does exist within the given directory. */
		ulFileCluster = FF_FindEntryInDir( pxIOManager, &xFindParams, pcFileName, 0x00, &xDirEntry, &xError );

		if( ulFileCluster == 0ul )
		{
			/* If cluster 0 was returned, it might be because the file has no allocated cluster,
			i.e. only a directory entry and no stored data. */
			if( STRLEN( pcFileName ) == STRLEN( xDirEntry.pcFileName ) )
			{
				if( ( xDirEntry.ulFileSize == 0 ) && ( FF_strmatch( pcFileName, xDirEntry.pcFileName, ( BaseType_t ) STRLEN( pcFileName ) ) == pdTRUE ) )
				{
					/* It is the file, give it a pseudo cluster number '1'. */
					ulFileCluster = 1;
					/* And reset any error. */
					xError = FF_ERR_NONE;
				}
			}
		}

		/* Test 'ulFileCluster' again, it might have been changed. */
		if( ulFileCluster == 0ul )
		{
			/* The path is found, but it does not contain the file name yet.
			Maybe the user wants to create it? */
			if( ( ucMode & FF_MODE_CREATE ) == 0 )
			{
				xError = ( FF_Error_t ) ( FF_ERR_FILE_NOT_FOUND | FF_OPEN );
			}
			else
			{
				ulFileCluster = FF_CreateFile( pxIOManager, &xFindParams, pcFileName, &xDirEntry, &xError );
				if( FF_isERR( xError ) == pdFALSE )
				{
					xDirEntry.usCurrentItem += 1;
				}
			}
		}
	}

	if( FF_isERR( xError ) == pdFALSE )
	{
		/* Now the file exists, or it has been created.
		Check if the Mode flags are allowed: */
		if( ( xDirEntry.ucAttrib == FF_FAT_ATTR_DIR ) && ( ( ucMode & FF_MODE_DIR ) == 0 ) )
		{
			/* Not the object, File Not Found! */
			xError = ( FF_Error_t ) ( FF_ERR_FILE_OBJECT_IS_A_DIR | FF_OPEN );
		}
		/*---------- Ensure Read-Only files don't get opened for Writing. */
		else if( ( ( ucMode & ( FF_MODE_WRITE | FF_MODE_APPEND ) ) != 0 ) && ( ( xDirEntry.ucAttrib & FF_FAT_ATTR_READONLY ) != 0 ) )
		{
			xError = ( FF_Error_t ) ( FF_ERR_FILE_IS_READ_ONLY | FF_OPEN );
		}
	}

	if( FF_isERR( xError ) == pdFALSE )
	{
		pxFile->pxIOManager = pxIOManager;
		pxFile->ulFilePointer = 0;
		/* Despite the warning output by MSVC - it is not possible to get here
		if xDirEntry has not been initialised. */
		pxFile->ulObjectCluster = xDirEntry.ulObjectCluster;
		pxFile->ulFileSize = xDirEntry.ulFileSize;
		pxFile->ulCurrentCluster = 0;
		pxFile->ulAddrCurrentCluster = pxFile->ulObjectCluster;

		pxFile->pxNext = NULL;
		pxFile->ulDirCluster = xFindParams.ulDirCluster;
		pxFile->usDirEntry = xDirEntry.usCurrentItem - 1;
		pxFile->ulChainLength = 0;
		pxFile->ulEndOfChain = 0;
		pxFile->ulValidFlags &= ~( FF_VALID_FLAG_DELETED );

		/* Add pxFile onto the end of our linked list of FF_FILE objects.
		But first make sure that there are not 2 handles with write access
		to the same object. */
		FF_PendSemaphore( pxIOManager->pvSemaphore );
		{
			pxFileChain = ( FF_FILE * ) pxIOManager->FirstFile;
			if( pxFileChain == NULL )
			{
				pxIOManager->FirstFile = pxFile;
			}
			else
			{
				for( ; ; )
				{
					/* See if two file handles point to the same object. */
					if( ( pxFileChain->ulObjectCluster == pxFile->ulObjectCluster ) &&
						( pxFileChain->ulDirCluster == pxFile->ulDirCluster ) &&
						( pxFileChain->usDirEntry == pxFile->usDirEntry ) )
					{
						/* Fail if any of the two has write access to the object. */
						if( ( ( pxFileChain->ucMode | pxFile->ucMode ) & ( FF_MODE_WRITE | FF_MODE_APPEND ) ) != 0 )
						{
							/* File is already open! DON'T ALLOW IT! */
							xError = ( FF_Error_t ) ( FF_ERR_FILE_ALREADY_OPEN | FF_OPEN );
							break;
						}
					}

					if( pxFileChain->pxNext == NULL )
					{
						pxFileChain->pxNext = pxFile;
						break;
					}

					pxFileChain = ( FF_FILE * ) pxFileChain->pxNext;
				}
			}
		}

		FF_ReleaseSemaphore( pxIOManager->pvSemaphore );
	}

	if( FF_isERR( xError ) == pdFALSE )
	{
		/* If the file is opened with the truncate flag, truncate its contents. */
		if( ( ucMode & FF_MODE_TRUNCATE ) != 0 )
		{
			/* Set the current size and position to zero. */
			pxFile->ulFileSize = 0;
			pxFile->ulFilePointer = 0;
		}
	}

	if( FF_isERR( xError ) != pdFALSE )
	{
		if( pxFile != NULL )
		{
			#if( ffconfigOPTIMISE_UNALIGNED_ACCESS != 0 )
			{
				ffconfigFREE( pxFile->pucBuffer );
			}
			#endif
			ffconfigFREE( pxFile );
		}
		pxFile = NULL;
	}

	if( pxError != NULL )
	{
		*pxError = xError;
	}

	return pxFile;
}  /* FF_Open() */
/*-----------------------------------------------------------*/

/**
 *	@public
 *	@brief	Tests if a Directory contains any other files or folders.
 *
 *	@param	pxIOManager	FF_IOManager_t object returned from the FF_CreateIOManger() function.
 *
 **/
#if( ffconfigUNICODE_UTF16_SUPPORT != 0 )
BaseType_t FF_isDirEmpty ( FF_IOManager_t * pxIOManager, const FF_T_WCHAR *pcPath )
#else
BaseType_t FF_isDirEmpty ( FF_IOManager_t * pxIOManager, const char *pcPath )
#endif
{
FF_DirEnt_t	xDirEntry;
FF_Error_t	xError = FF_ERR_NONE;
BaseType_t xReturn;

	if( pxIOManager == NULL )
	{
		xReturn = pdFALSE;
	}
	else
	{
		xError = FF_FindFirst( pxIOManager, &xDirEntry, pcPath );

		/* Assume the directory is empty until a file is
		encountered with a name other than ".." or "." */
		xReturn = pdTRUE;

		while( xError == 0 )
		{
			/* As we can't be sure the first 2 entries contain
			 * "." and "..", check it, not just count them
			 */
		#if( ffconfigUNICODE_UTF16_SUPPORT != 0 )
			if( ( wcscmp( xDirEntry.pcFileName, L".." ) != 0 ) && ( wcscmp( xDirEntry.pcFileName, L"." ) != 0 ) )
		#else
			if( ( strcmp( xDirEntry.pcFileName, ".." ) != 0 ) && ( strcmp( xDirEntry.pcFileName, "." ) != 0 ) )
		#endif
			{
				xReturn = pdFALSE;
				break;
			}
			xError = FF_FindNext( pxIOManager, &xDirEntry );
		}
	}

	return xReturn;
}	/* FF_isDirEmpty() */
/*-----------------------------------------------------------*/

#if( ffconfigPATH_CACHE != 0 )
	/* _HT_ After a directory has been renamed, the path cache becomes out-of-date */
	#if( ffconfigUNICODE_UTF16_SUPPORT != 0 )
	static void FF_RmPathCache ( FF_IOManager_t * pxIOManager, const FF_T_WCHAR * pcPath )
	#else
	static void FF_RmPathCache ( FF_IOManager_t * pxIOManager, const char *pcPath )
	#endif
	{
		/*
	* The directory 'path' will be removed or renamed
	* now clear all entries starting with 'path' in the path cache
	*/
		BaseType_t	xIndex;
		BaseType_t	pathLen = STRLEN( pcPath );

		FF_PendSemaphore( pxIOManager->pvSemaphore );
		{
			for( xIndex = 0; xIndex < ffconfigPATH_CACHE_DEPTH; xIndex++ )
			{
				BaseType_t	len2 = STRLEN( pxIOManager->xPartition.pxPathCache[ xIndex ].pcPath );

				if( len2 >= pathLen && FF_strmatch( pxIOManager->xPartition.pxPathCache[ xIndex ].pcPath, pcPath, pathLen ) )
				{
					pxIOManager->xPartition.pxPathCache[ xIndex ].pcPath[ 0 ] = '\0';
					pxIOManager->xPartition.pxPathCache[ xIndex ].ulDirCluster = 0;
				}
			}
		}

		FF_ReleaseSemaphore( pxIOManager->pvSemaphore );
	}
#endif /* ffconfigPATH_CACHE */
/*-----------------------------------------------------------*/


#if( ffconfigUNICODE_UTF16_SUPPORT != 0 )
FF_Error_t FF_RmDir( FF_IOManager_t *pxIOManager, const FF_T_WCHAR *pcPath )
#else
FF_Error_t FF_RmDir( FF_IOManager_t *pxIOManager, const char *pcPath )
#endif
{
FF_FILE				*pxFile;
uint8_t				ucEntryBuffer[32];
FF_FetchContext_t	xFetchContext;
FF_Error_t			xError = FF_ERR_NONE;

	if( pxIOManager == NULL )
	{
		xError = ( FF_Error_t ) ( FF_ERR_NULL_POINTER | FF_RMDIR );
	}
#if( ffconfigREMOVABLE_MEDIA != 0 )
	else if( ( pxIOManager->ucFlags & FF_IOMAN_DEVICE_IS_EXTRACTED ) != 0 )
	{
		xError = ( FF_Error_t ) ( FF_ERR_IOMAN_DRIVER_NOMEDIUM | FF_RMDIR );
	}
#endif /* ffconfigREMOVABLE_MEDIA */
	else
	{
		pxFile = FF_Open( pxIOManager, pcPath, FF_MODE_DIR, &xError );

		if( pxFile != NULL )
		{
			pxFile->ulValidFlags |= FF_VALID_FLAG_DELETED;

			/* Clear the struct to allow a call to FF_CleanupEntryFetch() in any
			state. */
			memset( &xFetchContext, '\0', sizeof( xFetchContext ) );

			/* This task will get the unique right to change directories. */
			FF_LockDirectory( pxIOManager );
			do /* while( pdFALSE ) */
			{
				/* This while loop is only introduced to be able to use break
				statements. */
				if( FF_isDirEmpty( pxIOManager, pcPath ) == pdFALSE )
				{
					xError = ( FF_ERR_DIR_NOT_EMPTY | FF_RMDIR );
					break;
				}
				FF_LockFAT( pxIOManager );
				#if( ffconfigHASH_CACHE != 0 )
				{
					/* A directory is removed so invalidate any hash table
					referring to this directory. */
					FF_UnHashDir( pxIOManager, pxFile->ulObjectCluster );
				}
				#endif	/* ffconfigHASH_CACHE */
				{
					/* Add parameter 0 to delete the entire chain!
					The actual directory entries on disk will be freed. */
					xError = FF_UnlinkClusterChain( pxIOManager, pxFile->ulObjectCluster, 0 );
				}
				FF_UnlockFAT( pxIOManager );
				if( FF_isERR( xError ) )
				{
					break;
				}

				/* Now remove this directory from its parent directory.
				Initialise the dirent Fetch Context object for faster removal of
				dirents. */
				xError = FF_InitEntryFetch( pxIOManager, pxFile->ulDirCluster, &xFetchContext );
				if( FF_isERR( xError ) )
				{
					break;
				}

				#if( ffconfigHASH_CACHE != 0 )
				{
					/* Invalidate any hash table of the parent directory
					as well. */
					FF_UnHashDir( pxIOManager, pxFile->ulDirCluster );
				}
				#endif	/* ffconfigHASH_CACHE */

				/* Edit the Directory Entry, so it will show as deleted.
				First remove the LFN entries: */
				xError = FF_RmLFNs( pxIOManager, pxFile->usDirEntry, &xFetchContext );
				if( FF_isERR( xError ) )
				{
					break;
				}

				/* And remove the Short file name entry: */
				xError = FF_FetchEntryWithContext( pxIOManager, pxFile->usDirEntry, &xFetchContext, ucEntryBuffer );
				if( FF_isERR( xError ) == pdFALSE )
				{
					ucEntryBuffer[0] = FF_FAT_DELETED;
					FF_putShort( ucEntryBuffer, FF_FAT_DIRENT_CLUS_HIGH, ( uint32_t ) 0ul );
					FF_putShort( ucEntryBuffer, FF_FAT_DIRENT_CLUS_LOW,  ( uint32_t ) 0ul );

					xError = FF_PushEntryWithContext( pxIOManager, pxFile->usDirEntry, &xFetchContext, ucEntryBuffer );
				}
				if( FF_isERR( xError ) )
				{
					break;
				}

				#if( ffconfigPATH_CACHE != 0 )
				{
					/* We're removing a directory which might contain
					subdirectories.  Instead of iterating through all
					subdirectories, just clear the path cache. */
					FF_RmPathCache( pxIOManager, pcPath );
				}
				#endif
			} while( pdFALSE );
			{
			FF_Error_t xTempError;
				xTempError = FF_CleanupEntryFetch( pxIOManager, &xFetchContext );
				if( FF_isERR( xError ) == pdFALSE )
				{
					xError = xTempError;
				}
				FF_UnlockDirectory( pxIOManager );

				/* Free the file pointer resources. */
				xTempError = FF_Close( pxFile );
				if( FF_isERR( xError ) == pdFALSE )
				{
					xError = xTempError;
				}

				xTempError = FF_FlushCache( pxIOManager );
				if( FF_isERR( xError ) == pdFALSE )
				{
					xError = xTempError;
				}
			}
		}	/* if( pxFile != NULL ) */
	}	/* else if( pxIOManager != NULL ) */

	return xError;
}	/* FF_RmDir() */
/*-----------------------------------------------------------*/

#if( ffconfigUNICODE_UTF16_SUPPORT != 0 )
FF_Error_t FF_RmFile( FF_IOManager_t *pxIOManager, const FF_T_WCHAR *pcPath )
#else
FF_Error_t FF_RmFile( FF_IOManager_t *pxIOManager, const char *pcPath )
#endif
{
FF_FILE *pxFile;
FF_Error_t xError = FF_ERR_NONE;
uint8_t ucEntryBuffer[32];
FF_FetchContext_t xFetchContext;

	/* Opening the file-to-be-deleted in WR mode has two advantages:
	1. The file handle gives all necessary information to delete it such
	   as the data clusters and directory entries.
	2. The file is now locked, it can not be opened by another task. */
	pxFile = FF_Open( pxIOManager, pcPath, FF_MODE_WRITE, &xError );

	if( pxFile != NULL )
	{
		/* FF_Close() will see this flag and won't do any disc access. */
		pxFile->ulValidFlags |= FF_VALID_FLAG_DELETED;

		/* Ensure there is actually a cluster chain to delete! */
		if( pxFile->ulObjectCluster != 0 )
		{
			/* Lock the FAT so its thread-safe. */
			FF_LockFAT( pxIOManager );
			{
				/* 0 to delete the entire chain! */
				xError = FF_UnlinkClusterChain( pxIOManager, pxFile->ulObjectCluster, 0 );
			}
			FF_UnlockFAT( pxIOManager );
		}

		if( FF_isERR( xError ) == pdFALSE )
		{
			/* Clear the struct to allow a call to FF_CleanupEntryFetch() in any
			state. */
			memset( &xFetchContext, '\0', sizeof( xFetchContext ) );

			/* Get sole access to "directory changes" */
			FF_LockDirectory( pxIOManager );

			/* Edit the Directory Entry! (So it appears as deleted); */
			do {
				xError = FF_InitEntryFetch( pxIOManager, pxFile->ulDirCluster, &xFetchContext );
				if( FF_isERR( xError ) )
				{
					break;
				}

				#if( ffconfigHASH_CACHE != 0 )
				{
					FF_UnHashDir( pxIOManager, pxFile->ulDirCluster );
				}
				#endif	/* ffconfigHASH_CACHE */
				/* Remove LFN entries, if any. */
				xError = FF_RmLFNs( pxIOManager, ( uint16_t ) pxFile->usDirEntry, &xFetchContext );
				if( FF_isERR( xError ) )
				{
					break;
				}

				/* Remove the Short file name entry. */
				xError = FF_FetchEntryWithContext( pxIOManager, pxFile->usDirEntry, &xFetchContext, ucEntryBuffer );
				if( FF_isERR( xError ) == pdFALSE )
				{
					ucEntryBuffer[0] = FF_FAT_DELETED;
					FF_putShort( ucEntryBuffer, FF_FAT_DIRENT_CLUS_HIGH, ( uint32_t ) 0ul );
					FF_putShort( ucEntryBuffer, FF_FAT_DIRENT_CLUS_LOW,  ( uint32_t ) 0ul );

					xError = FF_PushEntryWithContext( pxIOManager, pxFile->usDirEntry, &xFetchContext, ucEntryBuffer );
				}
			} while( pdFALSE );
			{
			FF_Error_t xTempError;
				xTempError = FF_CleanupEntryFetch( pxIOManager, &xFetchContext );
				if( FF_isERR( xError ) == pdFALSE )
				{
					xError = xTempError;
				}
				FF_UnlockDirectory( pxIOManager );

				/* Free the file pointer resources. */
				xTempError = FF_Close( pxFile );
				if( FF_isERR( xError ) == pdFALSE )
				{
					xError = xTempError;
				}

				xTempError = FF_FlushCache( pxIOManager );
				if( FF_isERR( xError ) == pdFALSE )
				{
					xError = xTempError;
				}
			}
		}
	}	/* if( pxFile != NULL ) */

	return xError;
}	/* FF_RmFile() */
/*-----------------------------------------------------------*/

/**
 *	@public
 *	@brief	Moves a file or directory from source to destination.
 *
 *	@param	pxIOManager				The FF_IOManager_t object pointer.
 *	@param	szSourceFile		String of the source file to be moved or renamed.
 *	@param	szDestinationFile	String of the destination file to where the source should be moved or renamed.
 *
 *	@return	FF_ERR_NONE on success.
 *	@return FF_ERR_FILE_DESTINATION_EXISTS if the destination file exists.
 *	@return FF_ERR_FILE_COULD_NOT_CREATE_DIRENT if dirent creation failed (fatal error!).
 *	@return FF_ERR_FILE_DIR_NOT_FOUND if destination directory was not found.
 *	@return FF_ERR_FILE_SOURCE_NOT_FOUND if the source file was not found.
 *
 **/

#if( ffconfigUNICODE_UTF16_SUPPORT != 0 )
FF_Error_t FF_Move( FF_IOManager_t *pxIOManager, const FF_T_WCHAR*szSourceFile,
	const FF_T_WCHAR *szDestinationFile, BaseType_t xDeleteIfExists )
#else
FF_Error_t FF_Move( FF_IOManager_t *pxIOManager, const char	*szSourceFile,
	const char	*szDestinationFile, BaseType_t	xDeleteIfExists )
#endif
{
FF_Error_t xError;
FF_FILE *pSrcFile, *pxDestFile;
FF_DirEnt_t xMyFile;
uint8_t ucEntryBuffer[32];
BaseType_t xIndex;
uint32_t ulDirCluster = 0ul;
FF_FetchContext_t xFetchContext;
#if( ffconfigPATH_CACHE != 0 )
	BaseType_t xIsDirectory = pdFALSE;
#endif

	memset( &xFetchContext, '\0', sizeof( xFetchContext ) );

	if( pxIOManager == NULL )
	{
		xError = ( FF_Error_t ) ( FF_ERR_NULL_POINTER | FF_MOVE );
	}
#if( ffconfigREMOVABLE_MEDIA != 0 )
	else if( ( pxIOManager->ucFlags & FF_IOMAN_DEVICE_IS_EXTRACTED ) != 0 )
	{
		xError = ( FF_Error_t ) ( FF_ERR_IOMAN_DRIVER_NOMEDIUM | FF_MOVE );
	}
#endif /* ffconfigREMOVABLE_MEDIA */
	else
	{
		/* Check destination file doesn't exist! */
		pxDestFile = FF_Open( pxIOManager, szDestinationFile, FF_MODE_READ, &xError );

		if( ( pxDestFile != NULL) || ( FF_GETERROR( xError ) == FF_ERR_FILE_OBJECT_IS_A_DIR ) )
		{
			xError = ( FF_Error_t ) ( FF_ERR_FILE_DESTINATION_EXISTS | FF_MOVE );
			if( pxDestFile != NULL )
			{
				FF_Close( pxDestFile );
				if( xDeleteIfExists != pdFALSE )
				{
					xError = FF_RmFile( pxIOManager, szDestinationFile );
				}
			}
		}
		else
		{
			/* Discard the error set by FF_Open().
			The target file (or directory) is not found: continue renaming. */
			xError = FF_ERR_NONE;
		}
	}

	if( FF_isERR( xError ) == pdFALSE )
	{
		/* About to move/rename 'szSourceFile'.  When opening it with 'FF_MODE_WRITE'
		only succeeds if it has no other open handle to it. */
		pSrcFile = FF_Open( pxIOManager, szSourceFile, FF_MODE_WRITE, &xError );

		if( FF_GETERROR( xError ) == FF_ERR_FILE_OBJECT_IS_A_DIR )
		{
			/* Open a directory for moving! */
			pSrcFile = FF_Open( pxIOManager, szSourceFile, FF_MODE_DIR, &xError );
	#if( ffconfigPATH_CACHE != 0 )
			xIsDirectory = pdTRUE;
	#endif
		}

		if( pSrcFile != NULL )
		{
			/* Collect information about the current directory entry. */
			xError = FF_InitEntryFetch( pxIOManager, pSrcFile->ulDirCluster, &xFetchContext );
			if( FF_isERR( xError ) == pdFALSE )
			{
				xError = FF_FetchEntryWithContext( pxIOManager, pSrcFile->usDirEntry, &xFetchContext, ucEntryBuffer );
				if( FF_isERR( xError ) == pdFALSE )
				{
					xMyFile.ucAttrib = FF_getChar( ucEntryBuffer, ( uint16_t ) ( FF_FAT_DIRENT_ATTRIB ) );
					xMyFile.ulFileSize = pSrcFile->ulFileSize;
					xMyFile.ulObjectCluster = pSrcFile->ulObjectCluster;
					xMyFile.usCurrentItem = 0;

					xIndex = ( BaseType_t ) STRLEN( szDestinationFile );

					while( xIndex != 0 )
					{
						if( ( szDestinationFile[ xIndex ] == '\\' ) || ( szDestinationFile[ xIndex ] == '/' ) )
						{
							break;
						}

						xIndex--;
					}

					/* Copy the base name of the destination file. */
					STRNCPY( xMyFile.pcFileName, ( szDestinationFile + xIndex + 1 ), ffconfigMAX_FILENAME );

					if( xIndex == 0 )
					{
						xIndex = 1;
					}

					/* Find the (cluster of the) directory in which the target file will be located.
					It must exist before calling FF_Move(). */
					ulDirCluster = FF_FindDir( pxIOManager, szDestinationFile, xIndex, &xError );
				}
			}
		}

		if( FF_isERR( xError ) == pdFALSE )
		{
			if( ulDirCluster != 0ul )
			{
				FF_FindParams_t	xFindParams;
				memset( &xFindParams, '\0', sizeof( xFindParams ) );

				/* Clean up because FF_CreateDirent might want to write to the same sector. */
				xError = FF_CleanupEntryFetch( pxIOManager, &xFetchContext );

				if( FF_isERR( xError ) == pdFALSE )
				{
					/* Destination directory was found, we can now create the new entry. */
					xFindParams.ulDirCluster = ulDirCluster;
					xError = FF_CreateDirent( pxIOManager, &xFindParams, &xMyFile );
				}

				if( FF_isERR( xError ) == pdFALSE )
				{
					/* Edit the Directory Entry! (So it appears as deleted); */
					FF_LockDirectory( pxIOManager );
					{
						xError = FF_RmLFNs( pxIOManager, pSrcFile->usDirEntry, &xFetchContext );

						if( FF_isERR( xError ) == pdFALSE )
						{
							xError = FF_FetchEntryWithContext( pxIOManager, pSrcFile->usDirEntry, &xFetchContext, ucEntryBuffer );

							if( FF_isERR( xError ) == pdFALSE )
							{
							FF_Error_t xTempError;
								ucEntryBuffer[0] = FF_FAT_DELETED;
								FF_putShort( ucEntryBuffer, FF_FAT_DIRENT_CLUS_HIGH, ( uint32_t ) 0ul );
								FF_putShort( ucEntryBuffer, FF_FAT_DIRENT_CLUS_LOW,  ( uint32_t ) 0ul );

								xError = FF_PushEntryWithContext( pxIOManager, pSrcFile->usDirEntry, &xFetchContext, ucEntryBuffer );
								/* The contents of 'xFetchContext' has changed, flush it to disk now. */
								xTempError = FF_CleanupEntryFetch( pxIOManager, &xFetchContext );
								if( FF_isERR( xError ) == pdFALSE )
								{
									xError = xTempError;
								}
							}
						}
					}
					FF_UnlockDirectory( pxIOManager );
				}

				#if( ffconfigPATH_CACHE != 0 )
				{
					if( xIsDirectory != 0 )
					{
						/* We've renamed a directory which might contain
						subdirectories.  To avoid having false entries, clear
						the path cache. */
						FF_RmPathCache( pxIOManager, szSourceFile );
					}
				}
				#endif
			}
			else	/* ulDirCluster == 0ul */
			{
				xError = ( FF_Error_t ) ( FF_ERR_FILE_DIR_NOT_FOUND | FF_MOVE );
			}
		}

		if( pSrcFile != NULL )
		{
			/* The source file was opened in WRITE mode just to lock it.
			Now clear the write flags to avoid writing back any changes. */
			pSrcFile->ucMode &= ~( FF_MODE_WRITE | FF_MODE_APPEND | FF_MODE_CREATE );
			FF_Close( pSrcFile );
		}
	}

	{
	FF_Error_t xTempError;

		xTempError = FF_FlushCache( pxIOManager );
		if( FF_isERR( xError ) == pdFALSE )
		{
			xError = xTempError;
		}
		xTempError = FF_CleanupEntryFetch( pxIOManager, &xFetchContext );
		if( FF_isERR( xError ) == pdFALSE )
		{
			xError = xTempError;
		}
	}

	return xError;
}	/* FF_Move() */
/*-----------------------------------------------------------*/

					/**
 *	@public
 *	@brief	Get's the next Entry based on the data recorded in the FF_DirEnt_t object.
 *
 *	@param	pxFile	FF_FILE object that was created by FF_Open().
 *
 *	@return pdTRUE if End of File was reached. pdFALSE if not.
 *	@return pdFALSE if a null pointer was provided.
 *
 **/
BaseType_t FF_isEOF( FF_FILE *pxFile )
{
BaseType_t xReturn;

	if( ( pxFile != NULL ) && ( pxFile->ulFilePointer >= pxFile->ulFileSize ) )
	{
		xReturn = pdTRUE;
	}
	else
	{
		xReturn = pdFALSE;
	}

	return xReturn;
}	/* FF_isEOF() */
/*-----------------------------------------------------------*/

/**
 *	@public
 *	@brief	Checks the number of bytes left on a read handle
 *
 *	@param	pxFile		An open file handle
 *
 *	@return	Less than zero: an error code
 *	@return	Number of bytes left to read from handle
 **/
int32_t FF_BytesLeft( FF_FILE *pxFile )
{
BaseType_t xReturn;

	if( pxFile == NULL )
	{
		xReturn = FF_ERR_NULL_POINTER | FF_BYTESLEFT;
	}
	else if( ( pxFile->ucMode & FF_MODE_READ ) == 0 )
	{
		xReturn = FF_ERR_FILE_NOT_OPENED_IN_READ_MODE | FF_BYTESLEFT;
	}
	else if( pxFile->ulFilePointer >= pxFile->ulFileSize )
	{
		xReturn = 0;
	}
	else
	{
		xReturn = pxFile->ulFileSize - pxFile->ulFilePointer;
	}

	return xReturn;
}	/* FF_BytesLeft() */
/*-----------------------------------------------------------*/

/**
 *	@public
 *	@brief	Returns the file size of a read handle
 *
 *	@param	pxFile		An open file handle
 *
 *	@return	Less than zero: an error code
 *	@return	Number of bytes left to read from handle
 **/
FF_Error_t FF_GetFileSize( FF_FILE *pxFile, uint32_t *pulSize ) /* Writes # of bytes in a file to the parameter. */
{
BaseType_t xReturn;

	if( pxFile == NULL )
	{
		xReturn = ( FF_Error_t ) ( FF_ERR_NULL_POINTER | FF_BYTESLEFT );
		*( pulSize ) = ( uint32_t ) 0u;
	}
	else if( FF_isERR( FF_CheckValid( pxFile ) ) )
	{
		xReturn = ( FF_Error_t ) ( FF_ERR_FILE_BAD_HANDLE | FF_BYTESLEFT );
		*( pulSize ) = ( uint32_t ) 0u;
	}
	else
	{
		xReturn = 0;
		*( pulSize ) = pxFile->ulFileSize;
	}

	return xReturn;
}	/* FF_GetFileSize */

int32_t FF_FileSize( FF_FILE *pxFile )
{
uint32_t ulLength;
FF_Error_t xResult;

	/* Function is deprecated. Please use FF_GetFileSize(). */
	xResult = FF_GetFileSize( pxFile, &( ulLength ) );

	if( FF_isERR( xResult ) == 0 )
	{
		xResult = ( int32_t ) ulLength;
	}

	return ( int32_t ) xResult;
}	/* FF_FileSize() */
/*-----------------------------------------------------------*/

static uint32_t FF_GetSequentialClusters( FF_IOManager_t *pxIOManager, uint32_t ulStartCluster, uint32_t ulLimit, FF_Error_t *pxError )
{
uint32_t ulCurrentCluster;
uint32_t ulNextCluster = ulStartCluster;
uint32_t ulIndex = 0;

	FF_FATBuffers_t xFATBuffers;
	FF_InitFATBuffers( &xFATBuffers, FF_MODE_READ );

	*pxError = FF_ERR_NONE;

	FF_LockFAT( pxIOManager );
	do
	{
		ulCurrentCluster = ulNextCluster;
		ulNextCluster = FF_getFATEntry( pxIOManager, ulCurrentCluster, pxError, &xFATBuffers );
		if( FF_isERR( *pxError ) )
		{
			ulIndex = 0;
			break;
		}

		if( ulNextCluster == ( ulCurrentCluster + 1 ) )
		{
			ulIndex++;
		}
		else
		{
			break;
		}

		if( ( ulLimit != 0 ) && ( ulIndex == ulLimit ) )
		{
			break;
		}
	}
	while( ulNextCluster == ( ulCurrentCluster + 1 ) );

	FF_UnlockFAT( pxIOManager );

	*pxError = FF_ReleaseFATBuffers( pxIOManager, &xFATBuffers );

	return ulIndex;
}	/* FF_GetSequentialClusters() */
/*-----------------------------------------------------------*/

static FF_Error_t FF_ReadClusters( FF_FILE *pxFile, uint32_t ulCount, uint8_t *buffer )
{
uint32_t ulSectors;
uint32_t ulSequentialClusters = 0;
uint32_t ulItemLBA;
FF_Error_t xError = FF_ERR_NONE;

	while( ulCount != 0 )
	{
		if( ( ulCount - 1 ) > 0 )
		{
			ulSequentialClusters =
				FF_GetSequentialClusters( pxFile->pxIOManager, pxFile->ulAddrCurrentCluster, ulCount - 1, &xError );
			if( FF_isERR( xError ) )
			{
				break;
			}
		}

		ulSectors = ( ulSequentialClusters + 1 ) * pxFile->pxIOManager->xPartition.ulSectorsPerCluster;
		ulItemLBA = FF_Cluster2LBA( pxFile->pxIOManager, pxFile->ulAddrCurrentCluster );
		ulItemLBA = FF_getRealLBA( pxFile->pxIOManager, ulItemLBA );

		xError = FF_BlockRead( pxFile->pxIOManager, ulItemLBA, ulSectors, buffer, pdFALSE );
		if( FF_isERR( xError ) )
		{
			break;
		}

		ulCount -= ( ulSequentialClusters + 1 );

		FF_LockFAT( pxFile->pxIOManager );
		{
			pxFile->ulAddrCurrentCluster =
				FF_TraverseFAT( pxFile->pxIOManager, pxFile->ulAddrCurrentCluster, ulSequentialClusters + 1, &xError );
		}
		FF_UnlockFAT( pxFile->pxIOManager );
		if( FF_isERR( xError ) )
		{
			break;
		}

		pxFile->ulCurrentCluster += ( ulSequentialClusters + 1 );
		buffer += ulSectors * pxFile->pxIOManager->usSectorSize;
		ulSequentialClusters = 0;
	}

	return xError;
}	/* FF_ReadClusters ()*/
/*-----------------------------------------------------------*/

static FF_Error_t FF_ExtendFile( FF_FILE *pxFile, uint32_t ulSize )
{
FF_IOManager_t *pxIOManager = pxFile->pxIOManager;
uint32_t ulBytesPerCluster = pxIOManager->xPartition.usBlkSize * pxIOManager->xPartition.ulSectorsPerCluster;
uint32_t ulTotalClustersNeeded = ( ulSize + ulBytesPerCluster - 1 ) / ulBytesPerCluster;
uint32_t ulClusterToExtend;
/* Initialise xIndex just for the compiler. */
BaseType_t xIndex = 0;
FF_DirEnt_t xOriginalEntry;
FF_Error_t xError = FF_ERR_NONE;
FF_FATBuffers_t xFATBuffers;

	if( ( pxFile->ucMode & FF_MODE_WRITE ) != FF_MODE_WRITE )
	{
		xError = ( FF_Error_t ) ( FF_ERR_FILE_NOT_OPENED_IN_WRITE_MODE | FF_EXTENDFILE );
	}
	else
	{
		if( ( pxFile->ulFileSize == 0 ) && ( pxFile->ulObjectCluster == 0 ) )
		{
			/* If there is no object cluster yet, create it.*/
			pxFile->ulAddrCurrentCluster = FF_CreateClusterChain( pxFile->pxIOManager, &xError );

			if( FF_isERR( xError ) == pdFALSE )
			{
				/* The directory denotes the address of the first data cluster of every file.
				Now change it to 'ulAddrCurrentCluster': */
				xError = FF_GetEntry( pxIOManager, pxFile->usDirEntry, pxFile->ulDirCluster, &xOriginalEntry );

				if( FF_isERR( xError ) == pdFALSE )
				{
					xOriginalEntry.ulObjectCluster = pxFile->ulAddrCurrentCluster;
					xError = FF_PutEntry( pxIOManager, pxFile->usDirEntry, pxFile->ulDirCluster, &xOriginalEntry, NULL );

					if( FF_isERR( xError ) == pdFALSE )
					{
						pxFile->ulObjectCluster = pxFile->ulAddrCurrentCluster;
						pxFile->ulChainLength = 1;
						pxFile->ulCurrentCluster = 0;
						pxFile->ulEndOfChain = pxFile->ulAddrCurrentCluster;
					}
				}
			}
		}
		else
		{
			/* This file already has at least one cluster. */
		}
	}

	if( FF_isERR( xError ) == pdFALSE )
	{
		if( pxFile->ulChainLength == 0 )
		{
			/* This is the first extension requiring the chain length.
			Calculate it now: */
			pxFile->ulChainLength = FF_GetChainLength( pxIOManager, pxFile->ulObjectCluster, &pxFile->ulEndOfChain, &xError );
		}
	}

	if( ( FF_isERR( xError ) == pdFALSE ) && ( ulTotalClustersNeeded > pxFile->ulChainLength ) )
	{
	uint32_t ulCurrentCluster, ulNextCluster;

		ulClusterToExtend = ( ulTotalClustersNeeded - pxFile->ulChainLength );
		/* Now the file has at least 1 cluster, but it needs more clusters. */
		ulNextCluster = pxFile->ulAddrCurrentCluster;
		FF_LockFAT( pxIOManager );

		ulCurrentCluster = FF_FindEndOfChain( pxIOManager, ulNextCluster, &xError );

		if( FF_isERR( xError ) == pdFALSE )
		{
			for( xIndex = 0; xIndex < ( BaseType_t ) ulClusterToExtend; xIndex++ )
			{
				/* In FF_ExtendFile() */
				ulNextCluster = FF_FindFreeCluster( pxIOManager, &xError, pdTRUE );
				if( ( FF_isERR( xError ) == pdFALSE ) && ( ulNextCluster == 0UL ) )
				{
					xError = ( FF_Error_t ) ( FF_ERR_FAT_NO_FREE_CLUSTERS | FF_EXTENDFILE );
				}

				if( FF_isERR( xError ) )
				{
					break;
				}

				/* Can not use this buffer earlier because of FF_FindEndOfChain/FF_FindFreeCluster */
				FF_InitFATBuffers( &xFATBuffers, FF_MODE_WRITE );
				xError = FF_putFATEntry( pxIOManager, ulCurrentCluster, ulNextCluster, &xFATBuffers );
				if( FF_isERR( xError ) )
				{
					break;
				}
				xError = FF_ReleaseFATBuffers( pxIOManager, &xFATBuffers );
				if( FF_isERR( xError ) )
				{
					break;
				}
				ulCurrentCluster = ulNextCluster;
			}

			if( FF_isERR( xError ) == pdFALSE )
			{
				pxFile->ulEndOfChain = ulCurrentCluster;
			}
			pxFile->ulChainLength += xIndex;
		}
		FF_UnlockFAT( pxIOManager );

		{
		FF_Error_t xTempError;
			xTempError = FF_DecreaseFreeClusters( pxIOManager, ( uint32_t ) xIndex );	/* Keep Tab of Numbers for fast FreeSize() */
			if( FF_isERR( xError ) == pdFALSE )
			{
				xError = xTempError;
			}
		}

		/* We must ensure that the ulAddrCurrentCluster is not out-of-sync with the CurrentCluster number.
		This could have occurred in append mode, where the file was opened with a filesize % clustersize == 0
		because of a seek, where the ulAddrCurrentCluster was not updated after extending. This caused the data to
		be written to the previous cluster(s). */
		if( ( pxFile->ulCurrentCluster == pxFile->ulChainLength - 1 ) &&
			( pxFile->ulAddrCurrentCluster != pxFile->ulEndOfChain ) )
		{
			pxFile->ulAddrCurrentCluster = pxFile->ulEndOfChain;
		}

		/* By default, 'ffconfigFILE_EXTEND_FLUSHES_BUFFERS' is
		defined as 1.
		Users may set it to zero in order to increase the
		speed of writing to disk. */

		#if( ffconfigFILE_EXTEND_FLUSHES_BUFFERS != 0 )
		{
		FF_Error_t xTempError;

			xTempError = FF_FlushCache( pxIOManager );
			if( FF_isERR( xError ) == pdFALSE )
			{
				xError = xTempError;
			}
		}
		#endif	/* ffconfigFILE_EXTEND_FLUSHES_BUFFERS */
	} /* if( ulTotalClustersNeeded > pxFile->ulChainLength ) */

	return xError;
}	/* FF_ExtendFile() */
/*-----------------------------------------------------------*/

static FF_Error_t FF_WriteClusters( FF_FILE *pxFile, uint32_t ulCount, uint8_t *buffer )
{
uint32_t ulSectors;
uint32_t ulSequentialClusters = 0;
uint32_t ulItemLBA;
FF_Error_t xError = FF_ERR_NONE;

	while( ulCount != 0 )
	{
		if( ( ulCount - 1 ) > 0 )
		{
			ulSequentialClusters =
				FF_GetSequentialClusters( pxFile->pxIOManager, pxFile->ulAddrCurrentCluster, ulCount - 1, &xError );
			if( FF_isERR( xError ) )
			{
				break;
			}
		}

		ulSectors = ( ulSequentialClusters + 1 ) * pxFile->pxIOManager->xPartition.ulSectorsPerCluster;
		ulItemLBA = FF_Cluster2LBA( pxFile->pxIOManager, pxFile->ulAddrCurrentCluster );
		ulItemLBA = FF_getRealLBA( pxFile->pxIOManager, ulItemLBA );

		xError = FF_BlockWrite( pxFile->pxIOManager, ulItemLBA, ulSectors, buffer, pdFALSE );

		if( FF_isERR( xError ) )
		{
			break;
		}

		ulCount -= ulSequentialClusters + 1;

		FF_LockFAT( pxFile->pxIOManager );
		{
			pxFile->ulAddrCurrentCluster =
				FF_TraverseFAT( pxFile->pxIOManager, pxFile->ulAddrCurrentCluster, ulSequentialClusters + 1, &xError );
		}
		FF_UnlockFAT( pxFile->pxIOManager );
		if( FF_isERR( xError ) )
		{
			break;
		}

		pxFile->ulCurrentCluster += ( ulSequentialClusters + 1 );
		buffer += ulSectors * pxFile->pxIOManager->usSectorSize;
		ulSequentialClusters = 0;
	}

	return xError;
}	/* FF_WriteClusters */
/*-----------------------------------------------------------*/

/**
 *	@private
 *	@brief	Calculate the Logical Block Address (LBA)
 *
 *	@param	pxFile       The file handle
 *
 *	@return	LBA
 *
 *  Must be set:
 *    - pxFile->ulFilePointer        : byte offset in file
 *    - pxFile->ulAddrCurrentCluster : physical cluster on the partition
 **/
static uint32_t FF_FileLBA( FF_FILE *pxFile )
{
	uint32_t	ulItemLBA;
	ulItemLBA = FF_Cluster2LBA( pxFile->pxIOManager, pxFile->ulAddrCurrentCluster );
	ulItemLBA += FF_getMajorBlockNumber( pxFile->pxIOManager, pxFile->ulFilePointer, 1 );
	ulItemLBA = FF_getRealLBA( pxFile->pxIOManager, ulItemLBA );
	ulItemLBA += FF_getMinorBlockNumber( pxFile->pxIOManager, pxFile->ulFilePointer, 1 );

	return ulItemLBA;
}	/* FF_FileLBA() */
/*-----------------------------------------------------------*/

/**
 *	@private
 *	@brief	Depending on FilePointer, calculate CurrentCluster
 *  @brief	and traverse the FAT to find the right ulAddrCurrentCluster
 *
 *	@param	pxFile       The file handle
 *
 *	@return	FF_ERR_NONE on success
 *	@return	Possible error returned by FF_TraverseFAT() or END_OF_DIR
 *
 *  Side effects:
 *    - pxFile->ulCurrentCluster     : relative cluster number (0 <= Num < ulChainLength)
 *    - pxFile->ulAddrCurrentCluster : fysical cluster on the partition
 **/
static uint32_t FF_SetCluster( FF_FILE *pxFile, FF_Error_t *pxError )
{
FF_IOManager_t *pxIOManager = pxFile->pxIOManager;
uint32_t ulNewCluster = FF_getClusterChainNumber( pxIOManager, pxFile->ulFilePointer, 1 );
FF_Error_t xResult = FF_ERR_NONE;
uint32_t ulReturn;

	if( ulNewCluster > pxFile->ulCurrentCluster )
	{
		FF_LockFAT( pxIOManager );
		{
			pxFile->ulAddrCurrentCluster = FF_TraverseFAT( pxIOManager, pxFile->ulAddrCurrentCluster,
				ulNewCluster - pxFile->ulCurrentCluster, &xResult );
		}
		FF_UnlockFAT( pxIOManager );
	}
	else if( ulNewCluster < pxFile->ulCurrentCluster )
	{
		FF_LockFAT( pxIOManager );
		{
			pxFile->ulAddrCurrentCluster = FF_TraverseFAT( pxIOManager, pxFile->ulObjectCluster, ulNewCluster, &xResult );
		}
		FF_UnlockFAT( pxIOManager );
	}
	else
	{
		/* Well positioned. */
	}

	if( FF_isERR( xResult ) == pdFALSE )
	{
		pxFile->ulCurrentCluster = ulNewCluster;
		ulReturn = FF_FileLBA( pxFile );
	}
	else
	{
		ulReturn = 0;
	}
	*pxError = xResult;

	return ulReturn;
}	/* FF_SetCluster() */
/*-----------------------------------------------------------*/

static int32_t FF_ReadPartial( FF_FILE *pxFile, uint32_t ulItemLBA, uint32_t ulRelBlockPos, uint32_t ulCount,
	uint8_t *pucBuffer, FF_Error_t *pxError )
{
FF_Error_t xError = FF_ERR_NONE;
uint32_t ulBytesRead;

	/* Bytes to read are within a block and less than a block size. */
	#if( ffconfigOPTIMISE_UNALIGNED_ACCESS != 0 )
	{
	BaseType_t xLastRead;

		/* Optimised method: each file handle holds one data block
		in cache: 'pxFile->pucBuffer'. */
		/* See if the current block will be accessed after this read: */
		if( ( ulRelBlockPos + ulCount ) >= ( uint32_t ) pxFile->pxIOManager->usSectorSize )
		{
			/* After this read, ulFilePointer will point to the next block/sector. */
			xLastRead = pdTRUE;
		}
		else
		{
			/* It is not the last read within this block/sector. */
			xLastRead = pdFALSE;
		}

		if( ( pxFile->ucState & FF_BUFSTATE_VALID ) == 0 )
		{
			xError = FF_BlockRead( pxFile->pxIOManager, ulItemLBA, 1, pxFile->pucBuffer, pdFALSE );
			if( FF_isERR( xError ) == pdFALSE )
			{
				pxFile->ucState = FF_BUFSTATE_VALID;
			}
		}

		if( ( pxFile->ucState & FF_BUFSTATE_VALID ) != 0 )
		{
			memcpy( pucBuffer, pxFile->pucBuffer + ulRelBlockPos, ulCount );
			pxFile->ulFilePointer += ulCount;
			ulBytesRead = ulCount;
			if( ( xLastRead == pdTRUE ) && ( ( pxFile->ucState & FF_BUFSTATE_WRITTEN ) != 0 ) )
			{
				/* If the data was changed (file in 'update' mode), store the changes: */
				xError = FF_BlockWrite( pxFile->pxIOManager, ulItemLBA, 1, pxFile->pucBuffer, pdFALSE );
			}
		}
		else
		{
			ulBytesRead = 0ul;
		}
		if( xLastRead == pdTRUE )
		{
			/* As the next FF_Read() will go passed the current block, invalidate the buffer now. */
			pxFile->ucState = FF_BUFSTATE_INVALID;
		}
	}
	#else
	{
	FF_Buffer_t *pxBuffer;
		/* Reading in the standard way, using FF_Buffer_t. */
		pxBuffer = FF_GetBuffer( pxFile->pxIOManager, ulItemLBA, FF_MODE_READ );
		if( pxBuffer == NULL )
		{
			xError = ( FF_Error_t ) ( FF_ERR_DEVICE_DRIVER_FAILED | FF_READ );
			ulBytesRead = 0ul;
		}
		else
		{
			memcpy( pucBuffer, pxBuffer->pucBuffer + ulRelBlockPos, ulCount );
			/* Releasing a buffer in FF_MODE_READ mode will not lead to an error,
			because no disk access is needed. */
			xError = FF_ReleaseBuffer( pxFile->pxIOManager, pxBuffer );
			pxFile->ulFilePointer += ulCount;
			ulBytesRead = ulCount;
		}
	}
	#endif

	*pxError = xError;

	return ulBytesRead;
}	/* FF_ReadPartial() */
/*-----------------------------------------------------------*/

/**
 *	@public
 *	@brief	Equivalent to fread()
 *
 *	@param	pxFile			FF_FILE object that was created by FF_Open().
 *	@param	ulElementSize	The size of an element to read.
 *	@param	ulCount			The number of elements to read.
 *	@param	buffer			A pointer to a buffer of adequate size to be filled with the requested data.
 *
 *	@return Number of bytes read.
 *
 * FF_Read() and FF_Write() work very similar. They both complete their task in 5 steps:
 *	1. Read bytes up to a sector border:  FF_ReadPartial()
 *	2. Read sectors up to cluster border: FF_BlockRead()
 *	3. Read complete clusters:            FF_ReadClusters()
 *	4. Read remaining sectors:            FF_BlockRead()
 *	5. Read remaining bytes:              FF_ReadPartial()
 **/
int32_t FF_Read( FF_FILE *pxFile, uint32_t ulElementSize, uint32_t ulCount, uint8_t *pucBuffer )
{
uint32_t ulBytesLeft = ulElementSize * ulCount;
uint32_t ulBytesRead = 0;
uint32_t ulBytesToRead;
FF_IOManager_t *pxIOManager;
uint32_t ulRelBlockPos;
uint32_t ulItemLBA;
int32_t lResult;
uint32_t ulSectors;
uint32_t ulRelClusterPos;
uint32_t ulBytesPerCluster;
FF_Error_t xError;

	if( pxFile == NULL )
	{
		xError = ( FF_Error_t ) ( FF_ERR_NULL_POINTER | FF_READ );
	}
	else
	{
		/* Check validity of the handle and the current position within the file. */
		xError = FF_CheckValid( pxFile );
		if( FF_isERR( xError ) == pdFALSE )
		{
			if( ( pxFile->ucMode & FF_MODE_READ ) == 0 )
			{
				/* File was not opened with READ mode access. */
				xError = ( FF_Error_t ) ( FF_ERR_FILE_NOT_OPENED_IN_READ_MODE | FF_READ );
			}
			else if( pxFile->ulFilePointer >= pxFile->ulFileSize )
			{
				/* The end-of-file is reached.  The error READ_ZERO will not be
				returned, it is just used to avoid further processing. */
				xError = ( FF_Error_t ) ( FF_ERR_FILE_READ_ZERO | FF_READ );
			}
			else if( ( pxFile->ulFilePointer + ulBytesLeft ) > pxFile->ulFileSize )
			{
				/* Note that many bytes can be read. */
				ulBytesLeft = pxFile->ulFileSize - pxFile->ulFilePointer;
			}
		}
		else
		{
			/* The file handle is not valid. */
		}
	}	/* else pxFile != NULL */

	if( FF_isERR( xError ) == pdFALSE )
	{
		pxIOManager = pxFile->pxIOManager;

		/* And calculate the Logical Block Address. */
		ulItemLBA = FF_SetCluster( pxFile, &xError );

		/* Get the position within a block. */
		ulRelBlockPos = FF_getMinorBlockEntry( pxIOManager, pxFile->ulFilePointer, 1 );
		/* Open a do {} while( 0 ) loop to allow easy breaks: */
		do
		{
			if( ( ulRelBlockPos + ulBytesLeft ) <= ( uint32_t ) pxIOManager->usSectorSize )
			{
				/*---------- A small read within the current block only. */
				ulBytesRead = FF_ReadPartial( pxFile, ulItemLBA, ulRelBlockPos, ulBytesLeft, pucBuffer, &xError );
				break;
			}
			/*---------- Read (memcpy) to a Sector Boundary. */
			if( ulRelBlockPos != 0 )
			{
				/* Not on a sector boundary, at this point the LBA is known. */
				ulBytesToRead = pxIOManager->usSectorSize - ulRelBlockPos;
				ulBytesRead = FF_ReadPartial( pxFile, ulItemLBA, ulRelBlockPos, ulBytesToRead, pucBuffer, &xError );
				if( FF_isERR( xError ) )
				{
					break;
				}
				ulBytesLeft -= ulBytesRead;
				pucBuffer += ulBytesRead;
			}

			/*---------- Read sectors, up to a Cluster Boundary. */
			ulBytesPerCluster = ( pxIOManager->xPartition.ulSectorsPerCluster * pxIOManager->usSectorSize );
			ulRelClusterPos = pxFile->ulFilePointer % ( ulBytesPerCluster * pxIOManager->xPartition.ucBlkFactor );

			if( ( ulRelClusterPos != 0 ) && ( ( ulRelClusterPos + ulBytesLeft ) >= ulBytesPerCluster ) )
			{
				/* Need to get to cluster boundary. */
				ulItemLBA = FF_SetCluster( pxFile, &xError );
				if( FF_isERR( xError ) )
				{
					break;
				}
				ulSectors = pxIOManager->xPartition.ulSectorsPerCluster - ( ulRelClusterPos / pxIOManager->usSectorSize );
				xError = FF_BlockRead( pxIOManager, ulItemLBA, ulSectors, pucBuffer, pdFALSE );
				if( FF_isERR( xError ) )
				{
					break;
				}
				ulBytesToRead = ulSectors * pxIOManager->usSectorSize;
				ulBytesLeft -= ulBytesToRead;
				pucBuffer += ulBytesToRead;
				ulBytesRead += ulBytesToRead;
				pxFile->ulFilePointer += ulBytesToRead;
			}

			/*---------- Read entire clusters. */
			if( ulBytesLeft >= ulBytesPerCluster )
			{
			uint32_t ulClusters;

			FF_SetCluster( pxFile, &xError );
				if( FF_isERR( xError ) )
				{
					break;
				}

				ulClusters = ulBytesLeft / ulBytesPerCluster;

				xError = FF_ReadClusters( pxFile, ulClusters, pucBuffer );
				if( FF_isERR( xError ) )
				{
					break;
				}
				ulBytesToRead = ulBytesPerCluster * ulClusters;
				pxFile->ulFilePointer += ulBytesToRead;
				ulBytesLeft -= ulBytesToRead;
				pucBuffer += ulBytesToRead;
				ulBytesRead += ulBytesToRead;
			}

			/*---------- Read Remaining Blocks. */
			while( ulBytesLeft >= ( uint32_t ) pxIOManager->usSectorSize )
			{
				ulSectors = ulBytesLeft / pxIOManager->usSectorSize;
				{
					/* HT: I'd leave these pPart/ulOffset for readability */
					/* and shorter code lines */
					FF_Partition_t *pPart = &( pxIOManager->xPartition );
					uint32_t ulOffset = ( pxFile->ulFilePointer / pxIOManager->usSectorSize ) % pPart->ulSectorsPerCluster;
					uint32_t ulRemain = pPart->ulSectorsPerCluster - ulOffset;
					if( ulSectors > ulRemain )
					{
						ulSectors = ulRemain;
					}
				}

				ulItemLBA = FF_SetCluster( pxFile, &xError );
				if( FF_isERR( xError ) )
				{
					break;
				}
				xError = FF_BlockRead( pxIOManager, ulItemLBA, ulSectors, pucBuffer, pdFALSE );

				if( FF_isERR( xError ) )
				{
					break;
				}
				ulBytesToRead = ulSectors * pxIOManager->usSectorSize;
				pxFile->ulFilePointer += ulBytesToRead;
				ulBytesLeft -= ulBytesToRead;
				pucBuffer += ulBytesToRead;
				ulBytesRead += ulBytesToRead;
			}

			/*---------- Read (memcpy) Remaining Bytes */
			if( ulBytesLeft == 0 )
			{
				break;
			}
			ulItemLBA = FF_SetCluster( pxFile, &xError );
			if( FF_isERR( xError ) )
			{
				break;
			}
			/* Bytes to read are within a block and less than a block size. */
			FF_ReadPartial( pxFile, ulItemLBA, 0, ulBytesLeft, pucBuffer, &xError );
			if( FF_isERR( xError ) == pdFALSE )
			{
				ulBytesRead += ulBytesLeft;
			}
		}
		while( pdFALSE );
	} /* if( FF_isERR( xError ) == pdFALSE ) */

	if( FF_GETERROR( xError ) == FF_ERR_FILE_READ_ZERO )
	{
		lResult = 0;
	}
	else if( FF_isERR( xError ) )
	{
		lResult = xError;
	}
	else
	{
		lResult = ( int32_t )( ulBytesRead / ulElementSize );
	}

	return lResult;
}	/* FF_Read() */
/*-----------------------------------------------------------*/

/**
*	@public
*	@brief	Equivalent to fgetc()
*
*	@param	pxFile		FF_FILE object that was created by FF_Open().
*
*	@return The character that was read (cast as a 32-bit interger). -1 on EOF.
*	@return FF_Error_t code. (Check with if(FF_isERR(xRetVal)) {}).
*	@return -1 EOF (end of file).
*
**/
int32_t FF_GetC( FF_FILE *pxFile )
{
uint32_t ulItemLBA;
uint8_t ucReturnedChar;
uint32_t ulRelBlockPos;
FF_Error_t xResult;

	if( pxFile == NULL )
	{
		xResult = FF_ERR_NULL_POINTER | FF_GETC;	/* Ensure this is a signed error. */
	}
	else if( ( pxFile->ucMode & FF_MODE_READ ) == 0 )
	{
		xResult = FF_ERR_FILE_NOT_OPENED_IN_READ_MODE | FF_GETC;
	}
	else if( pxFile->ulFilePointer >= pxFile->ulFileSize )
	{
		/* The end-of-file is reached.  The error READ_ZERO will not be
		returned, it is just used to avoid further processing. */
		xResult = FF_ERR_FILE_READ_ZERO | FF_READ;
	}
	else
	{
		ulRelBlockPos = FF_getMinorBlockEntry( pxFile->pxIOManager, pxFile->ulFilePointer, 1 );

		ulItemLBA = FF_SetCluster( pxFile, &xResult );
		if( FF_isERR( xResult ) == pdFALSE )
		{
			FF_ReadPartial( pxFile, ulItemLBA, ulRelBlockPos, 1, &ucReturnedChar, &xResult );
			if( FF_isERR( xResult ) == pdFALSE )
			{
				xResult = ( int32_t ) ( ( uint32_t ) ucReturnedChar );
			}
		}
	}

	return ( int32_t ) xResult;
}	/* FF_GetC() */
/*-----------------------------------------------------------*/

/**
* @public
* @brief	Gets a Line from a Text File, but no more than ulLimit characters. The line will be NULL terminated.
*
*			The behaviour of this function is undefined when called on a binary file.
*			It should just read in ulLimit bytes of binary, and ZERO terminate the line.
*
*			This function works for both UNIX line feeds, and Windows CRLF type files.
*
* @param	pxFile	The FF_FILE object pointer.
* @param	szLine	The character buffer where the line should be stored.
* @param	ulLimit	This should be the max number of characters that szLine can hold.
*
* @return	The number of characters read from the line, on success.
* @return	0 when no more lines are available, or when ulLimit is 0.
* @return	FF_ERR_NULL_POINTER if pxFile or szLine are NULL;
*
**/
int32_t FF_GetLine( FF_FILE *pxFile, char *pcLine, uint32_t ulLimit )
{
int32_t iChar = 0;
BaseType_t xIndex;
FF_Error_t xResult = FF_ERR_NONE;

	if( ( pxFile == NULL ) || ( pcLine == NULL ) )
	{
		xResult = FF_ERR_NULL_POINTER | FF_GETLINE;
	}
	else
	{
		for( xIndex = 0; xIndex < ( BaseType_t ) ( ulLimit - 1 ); ++xIndex )
		{
			iChar = FF_GetC( pxFile );

			if( FF_isERR( iChar ) == pdFALSE )
			{
				pcLine[ xIndex ] = ( char ) iChar;

				if( iChar == '\n' )
				{
					/* Read until the first linefeed.  Move xIndex forward so the
					null terminator does not overwrite the \n.  xIndex must be less
					thank ( ulLimit - 1 ), so incrementing it here cannot make it
					greater than ulLimit - 1, so the NULL can be inserted without
					overflowing the buffer. */
					xIndex++;
					break;
				}
			}
			else
			{
				if( ( FF_GETERROR( iChar ) == FF_ERR_FILE_READ_ZERO ) && ( xIndex > 0 ) )
				{
					/* Although FF_GetC() returns an End Of File,
					the last few characters will be returned first. */
					iChar = xIndex;
				}
				break;
			}
		}

		/* Make sure that the resulting string always ends with a zero: */
		pcLine[ xIndex ] = '\0';

		/*_RB_ In some paths this will be the second time FF_isERR() is called
		on the same value. */
		if( FF_isERR( iChar ) == pdFALSE )
		{
			/* Return the number of bytes read. */
			xResult = xIndex;
		}
		else
		{
			/* Return iChar as an error code (see FF_GetC()). */
			xResult = iChar;
		}
	}

	return xResult;
}	/* FF_GetLine() */
/*-----------------------------------------------------------*/

static int32_t FF_WritePartial( FF_FILE *pxFile, uint32_t ulItemLBA, uint32_t ulRelBlockPos, uint32_t ulCount,
	const uint8_t *pucBuffer, FF_Error_t *pxError )
{
FF_Error_t xError;
uint32_t ulBytesWritten;

	#if( ffconfigOPTIMISE_UNALIGNED_ACCESS != 0 )
	{
		BaseType_t xLastRead;
		if( ( ulRelBlockPos + ulCount ) >= ( uint32_t ) pxFile->pxIOManager->usSectorSize )
		{
			/* After this read, ulFilePointer will point to the next block/sector. */
			xLastRead = pdTRUE;
		}
		else
		{
			/* It is not the last read within this block/sector. */
			xLastRead = pdFALSE;
		}

		if( ( ( pxFile->ucState & FF_BUFSTATE_VALID ) == 0 ) &&
			( ( ulRelBlockPos != 0 ) || ( pxFile->ulFilePointer < pxFile->ulFileSize ) ) )
		{
			xError = FF_BlockRead( pxFile->pxIOManager, ulItemLBA, 1, pxFile->pucBuffer, pdFALSE );
			/* pxFile->ucState will be set later on. */
		}
		else
		{
			xError = FF_ERR_NONE;
			/* the buffer is valid or a whole block/sector will be written, so it is
			not necessary to read the contents first. */
		}
		if( FF_isERR( xError ) == pdFALSE )
		{
			memcpy( pxFile->pucBuffer + ulRelBlockPos, pucBuffer, ulCount );
			if( xLastRead == pdTRUE )
			{
				xError = FF_BlockWrite( pxFile->pxIOManager, ulItemLBA, 1, pxFile->pucBuffer, pdFALSE );
				pxFile->ucState = FF_BUFSTATE_INVALID;
			}
			else
			{
				pxFile->ucState |= FF_BUFSTATE_WRITTEN | FF_BUFSTATE_VALID;
			}
		}
		else
		{
			pxFile->ucState = FF_BUFSTATE_INVALID;
		}
	}
	#else
	{
	FF_Buffer_t *pxBuffer;
		if( ( ulRelBlockPos == 0 ) && ( pxFile->ulFilePointer >= pxFile->ulFileSize ) )
		{
			/* An entire sector will be written. */
			pxBuffer = FF_GetBuffer( pxFile->pxIOManager, ulItemLBA, FF_MODE_WR_ONLY );
		}
		else
		{
			/* A partial write will be done, make sure to read the contents before
			changing anything. */
			pxBuffer = FF_GetBuffer( pxFile->pxIOManager, ulItemLBA, FF_MODE_WRITE );
		}

		if( pxBuffer == NULL )
		{
			xError = ( FF_Error_t ) ( FF_ERR_DEVICE_DRIVER_FAILED | FF_WRITE );
		}
		else
		{
			/* Here we copy to the sector boundary. */
			memcpy( ( pxBuffer->pucBuffer + ulRelBlockPos ), pucBuffer, ulCount );

			xError = FF_ReleaseBuffer( pxFile->pxIOManager, pxBuffer );
		}
	}
	#endif
	if( FF_isERR( xError ) == pdFALSE )
	{
		pxFile->ulFilePointer += ulCount;
		ulBytesWritten = ulCount;

		if( pxFile->ulFilePointer > pxFile->ulFileSize )
		{
			pxFile->ulFileSize = pxFile->ulFilePointer;
		}
	}
	else
	{
		ulBytesWritten = 0ul;
	}
	*pxError = xError;

	return ulBytesWritten;
}	/* FF_WritePartial() */
/*-----------------------------------------------------------*/

/**
 *	@public
 *	@brief	Writes data to a File.
 *
 *	@param	pxFile			FILE Pointer.
 *	@param	ulElementSize		Size of an Element of Data to be copied. (in bytes).
 *	@param	ulCount			Number of Elements of Data to be copied. (ulElementSize * ulCount must not exceed ((2^31)-1) bytes. (2GB). For best performance, multiples of 512 bytes or Cluster sizes are best.
 *	@param	pucBuffer			Byte-wise pucBuffer containing the data to be written.
 *
 * FF_Read() and FF_Write() work very similar. They both complete their task in 5 steps:
 *	1. Write bytes up to a sector border:  FF_WritePartial()
 *	2. Write sectors up to cluster border: FF_BlockWrite()
 *	3. Write complete clusters:            FF_WriteClusters()
 *	4. Write remaining sectors:            FF_BlockWrite()
 *	5. Write remaining bytes:              FF_WritePartial()
 *	@return
**/
int32_t FF_Write( FF_FILE *pxFile, uint32_t ulElementSize, uint32_t ulCount, uint8_t *pucBuffer )
{
uint32_t ulBytesLeft = ulElementSize * ulCount;
uint32_t nBytesWritten = 0;
uint32_t nBytesToWrite;
FF_IOManager_t *pxIOManager;
uint32_t ulRelBlockPos;
uint32_t ulItemLBA;
int32_t lResult;
uint32_t ulSectors;
uint32_t ulRelClusterPos;
uint32_t ulBytesPerCluster;
FF_Error_t xError;

	if( pxFile == NULL )
	{
		xError = ( FF_Error_t ) ( FF_ERR_NULL_POINTER | FF_READ );
	}
	else
	{
		/* Check validity of the handle and the current position within the file. */
		xError = FF_CheckValid( pxFile );
		if( FF_isERR( xError ) == pdFALSE )
		{
			if( ( pxFile->ucMode & FF_MODE_WRITE ) == 0 )
			{
				xError = ( FF_Error_t ) ( FF_ERR_FILE_NOT_OPENED_IN_WRITE_MODE | FF_WRITE );
			}
			/* Make sure a write is after the append point. */
			else if( ( pxFile->ucMode & FF_MODE_APPEND ) != 0 )
			{
				if( pxFile->ulFilePointer < pxFile->ulFileSize )
				{
					xError = FF_Seek( pxFile, 0, FF_SEEK_END );
				}
			}
		}
	}

	if( FF_isERR( xError ) == pdFALSE )
	{
		pxIOManager = pxFile->pxIOManager;

		/* Open a do{} while( 0 ) loop to allow the use of breaks */
		do
		{
			/* Extend File for at least ulBytesLeft!
			Handle file-space allocation
			+ 1 byte because the code assumes there is always a next cluster */
			xError = FF_ExtendFile( pxFile, pxFile->ulFilePointer + ulBytesLeft + 1 );
			if( FF_isERR( xError ) )
			{
				/* On every error, break from the while( 0 ) loop. */
				break;
			}

			ulRelBlockPos = FF_getMinorBlockEntry( pxIOManager, pxFile->ulFilePointer, 1 );	/* Get the position within a block. */
			ulItemLBA = FF_SetCluster( pxFile, &xError );
			if( FF_isERR( xError ) )
			{
				break;
			}

			if( ( ulRelBlockPos + ulBytesLeft ) <= ( uint32_t ) pxIOManager->usSectorSize )
			{
				/* Bytes to write are within a block and and do not go passed the current block. */
				nBytesWritten = FF_WritePartial( pxFile, ulItemLBA, ulRelBlockPos, ulBytesLeft, pucBuffer, &xError );
				break;
			}

			/*---------- Write (memcpy) to a Sector Boundary. */
			if( ulRelBlockPos != 0 )
			{
				/* Not writing on a sector boundary, at this point the LBA is known. */
				nBytesToWrite = pxIOManager->usSectorSize - ulRelBlockPos;
				nBytesWritten = FF_WritePartial( pxFile, ulItemLBA, ulRelBlockPos, nBytesToWrite, pucBuffer, &xError );
				if( FF_isERR( xError ) )
				{
					break;
				}

				ulBytesLeft -= nBytesWritten;
				pucBuffer += nBytesWritten;
			}

			/*---------- Write sectors, up to a Cluster Boundary. */
			ulBytesPerCluster = ( pxIOManager->xPartition.ulSectorsPerCluster * pxIOManager->usSectorSize );
			ulRelClusterPos = FF_getClusterPosition( pxIOManager, pxFile->ulFilePointer, 1 );

			if( ( ulRelClusterPos != 0 ) && ( ( ulRelClusterPos + ulBytesLeft ) >= ulBytesPerCluster ) )
			{
				/* Need to get to cluster boundary */
				ulItemLBA = FF_SetCluster( pxFile, &xError );
				if( FF_isERR( xError ) )
				{
					break;
				}

				ulSectors = pxIOManager->xPartition.ulSectorsPerCluster - ( ulRelClusterPos / pxIOManager->usSectorSize );
				xError = FF_BlockWrite( pxIOManager, ulItemLBA, ulSectors, pucBuffer, pdFALSE );
				if( FF_isERR( xError ) )
				{
					break;
				}

				nBytesToWrite = ulSectors * pxIOManager->usSectorSize;
				ulBytesLeft -= nBytesToWrite;
				pucBuffer += nBytesToWrite;
				nBytesWritten += nBytesToWrite;
				pxFile->ulFilePointer += nBytesToWrite;
				if( pxFile->ulFilePointer > pxFile->ulFileSize )
				{
					pxFile->ulFileSize = pxFile->ulFilePointer;
				}
			}

			/*---------- Write entire Clusters. */
			if( ulBytesLeft >= ulBytesPerCluster )
			{
			uint32_t ulClusters;

				FF_SetCluster( pxFile, &xError );
				if( FF_isERR( xError ) )
				{
					break;
				}

				ulClusters = ( ulBytesLeft / ulBytesPerCluster );

				xError = FF_WriteClusters( pxFile, ulClusters, pucBuffer );
				if( FF_isERR( xError ) )
				{
					break;
				}

				nBytesToWrite = ulBytesPerCluster * ulClusters;
				ulBytesLeft -= nBytesToWrite;
				pucBuffer += nBytesToWrite;
				nBytesWritten += nBytesToWrite;
				pxFile->ulFilePointer += nBytesToWrite;
				if( pxFile->ulFilePointer > pxFile->ulFileSize )
				{
					pxFile->ulFileSize = pxFile->ulFilePointer;
				}
			}

			/*---------- Write Remaining Blocks */
			while( ulBytesLeft >= ( uint32_t ) pxIOManager->usSectorSize )
			{
				ulSectors = ulBytesLeft / pxIOManager->usSectorSize;
				{
					/* HT: I'd leave these pPart/ulOffset for readability... */
					FF_Partition_t	*pPart = &( pxIOManager->xPartition );
					uint32_t ulOffset = ( pxFile->ulFilePointer / pxIOManager->usSectorSize ) % pPart->ulSectorsPerCluster;
					uint32_t ulRemain = pPart->ulSectorsPerCluster - ulOffset;
					if( ulSectors > ulRemain )
					{
						ulSectors = ulRemain;
					}
				}

				ulItemLBA = FF_SetCluster( pxFile, &xError );
				if( FF_isERR( xError ) )
				{
					break;
				}

				xError = FF_BlockWrite( pxIOManager, ulItemLBA, ulSectors, pucBuffer, pdFALSE );
				if( FF_isERR( xError ) )
				{
					break;
				}

				nBytesToWrite = ulSectors * pxIOManager->usSectorSize;
				ulBytesLeft -= nBytesToWrite;
				pucBuffer += nBytesToWrite;
				nBytesWritten += nBytesToWrite;
				pxFile->ulFilePointer += nBytesToWrite;
				if( pxFile->ulFilePointer > pxFile->ulFileSize )
				{
					pxFile->ulFileSize = pxFile->ulFilePointer;
				}
			}

			/*---------- Write (memcpy) Remaining Bytes */
			if( ulBytesLeft == 0 )
			{
				break;
			}

			ulItemLBA = FF_SetCluster( pxFile, &xError );
			if( FF_isERR( xError ) )
			{
				break;
			}
			FF_WritePartial( pxFile, ulItemLBA, 0, ulBytesLeft, pucBuffer, &xError );
			nBytesWritten += ulBytesLeft;
		}
		while( pdFALSE );
	}

	if( FF_isERR( xError ) )
	{
		lResult = xError;
	}
	else
	{
		lResult = ( int32_t )( nBytesWritten / ulElementSize );
	}

	return lResult;
}	/* FF_Write() */
/*-----------------------------------------------------------*/

/**
*	@public
*	@brief	Writes a char to a FILE.
*
*	@param	pxFile		FILE Pointer.
*	@param	ucValue	Char to be placed in the file.
*
*	@return	Returns the value written to the file, or a value less than 0.
*
**/
int32_t FF_PutC( FF_FILE *pxFile, uint8_t ucValue )
{
uint32_t ulItemLBA;
uint32_t ulRelBlockPos;
FF_Error_t xResult;

	if( pxFile == NULL )
	{	/* Ensure we don't have a Null file pointer on a Public interface. */
		xResult = FF_ERR_NULL_POINTER | FF_PUTC;
	}
	else if( ( pxFile->ucMode & FF_MODE_WRITE ) == 0 )
	{
		xResult = FF_ERR_FILE_NOT_OPENED_IN_WRITE_MODE | FF_PUTC;
	}
	else
	{
		xResult = FF_ERR_NONE;
		do
		{
			/* Make sure a write is after the append point. */
			if( ( pxFile->ucMode & FF_MODE_APPEND ) != 0 )
			{
				if( pxFile->ulFilePointer < pxFile->ulFileSize )
				{
					xResult = FF_Seek( pxFile, 0, FF_SEEK_END );
					if( FF_isERR( xResult ) )
					{
						break;
					}
				}
			}

			ulRelBlockPos = FF_getMinorBlockEntry( pxFile->pxIOManager, pxFile->ulFilePointer, 1 );

			/* Handle File Space Allocation. */
			/* We'll write 1 byte and always have a next cluster reserved. */
			xResult = FF_ExtendFile( pxFile, pxFile->ulFilePointer + 2 );
			if( FF_isERR( xResult ) )
			{
				break;
			}

			ulItemLBA = FF_SetCluster( pxFile, &xResult );
			if( FF_isERR( xResult ) )
			{
				break;
			}
			FF_WritePartial( pxFile, ulItemLBA, ulRelBlockPos, 1, &ucValue, &xResult );

			if( FF_isERR( xResult ) == pdFALSE )
			{
				xResult = ( FF_Error_t ) ucValue;
			}

		} while( pdFALSE );
	}

	return xResult;
}	/* FF_PutC() */
/*-----------------------------------------------------------*/

/**
*	@public
*	@brief	Equivalent to fseek()
*
*	@param	pxFile		FF_FILE object that was created by FF_Open().
*	@param	ulOffset	An integer (+/-) to seek to, from the specified origin.
*	@param	xOrigin		Where to seek from. (FF_SEEK_SET seek from start, FF_SEEK_CUR seek from current position, or FF_SEEK_END seek from end of file).
*
*	@return 0 on Sucess,
*	@return -2 if offset results in an invalid position in the file.
*	@return FF_ERR_NULL_POINTER if a FF_FILE pointer was not received.
*	@return -3 if an invalid origin was provided.
*
**/
FF_Error_t FF_Seek( FF_FILE *pxFile, int32_t lOffset, BaseType_t xOrigin )
{
FF_Error_t xError;
uint32_t ulPosition = 0ul;

	xError = FF_CheckValid( pxFile );

	if( FF_isERR( xError ) == pdFALSE )
	{
		xError = FF_FlushCache( pxFile->pxIOManager );

		#if( ffconfigOPTIMISE_UNALIGNED_ACCESS != 0 )
		{
			if( FF_isERR( xError ) == pdFALSE )
			{
				/* Here we must ensure that if the user tries to seek, and we had data in the file's
				write buffer that this is written to disk. */
				if( ( pxFile->ucState & FF_BUFSTATE_WRITTEN ) != 0 )
				{
					xError = FF_BlockWrite( pxFile->pxIOManager, FF_FileLBA( pxFile ), 1, pxFile->pucBuffer, pdFALSE );
				}
				pxFile->ucState = FF_BUFSTATE_INVALID;
			}
		}
		#endif	/* ffconfigOPTIMISE_UNALIGNED_ACCESS */

		if( FF_isERR( xError ) == pdFALSE )
		{
			if( xOrigin == FF_SEEK_SET )
			{
				ulPosition = ( uint32_t )lOffset;
			}
			else if( xOrigin == FF_SEEK_CUR )
			{
				if( lOffset >= ( int32_t ) 0 )
				{
					ulPosition = pxFile->ulFilePointer + ( ( uint32_t ) lOffset );
				}
				else
				{
					ulPosition = pxFile->ulFilePointer - ( ( uint32_t ) ( -lOffset ) );
				}
			}
			else if( xOrigin == FF_SEEK_END )
			{
				/* 'FF_SEEK_END' only allows zero or negative values. */
				if( lOffset <= ( int32_t ) 0 )
				{
					ulPosition = pxFile->ulFileSize - ( ( uint32_t ) ( -lOffset ) );
				}
			}
			else
			{
				xError = ( FF_Error_t ) ( FF_SEEK | FF_ERR_FILE_SEEK_INVALID_ORIGIN );
				/* To supress a compiler warning. */
				ulPosition = ( uint32_t ) 0u;
			}

			if( FF_isERR( xError ) == pdFALSE )
			{
				if( ulPosition <= ( uint32_t ) pxFile->ulFileSize )
				{
					if( ulPosition != ( uint32_t ) pxFile->ulFilePointer )
					{
						pxFile->ulFilePointer = ulPosition;
						FF_SetCluster( pxFile, &xError );
					}
				}
				else
				{
					xError = ( FF_Error_t ) ( FF_SEEK | FF_ERR_FILE_SEEK_INVALID_POSITION );
				}
			}
		}
	}

	return xError;
}	/* FF_Seek() */
/*-----------------------------------------------------------*/

#if( ffconfigREMOVABLE_MEDIA != 0 )
	/**
	*	@public
	*	@brief	Invalidate all file handles belonging to pxIOManager
	*
	*	@param	pIoMan		FF_IOManager_t object that was created by FF_CreateIOManger().
	*
	*	@return 0 if no handles were open
	*	@return >0 the amount of handles that were invalidated
	*	@return <0 probably an invalid FF_IOManager_t pointer
	*
	**/
	int32_t FF_Invalidate( FF_IOManager_t *pxIOManager )
	{
	int32_t xResult;
	FF_FILE *pxFileChain;

		if( pxIOManager == NULL )
		{
			xResult = FF_ERR_NULL_POINTER | FF_INVALIDATE;
		}
		else
		{
			xResult = 0;
			FF_PendSemaphore( pxIOManager->pvSemaphore );
			{
				pxIOManager->ucFlags |= FF_IOMAN_DEVICE_IS_EXTRACTED;
				/* Semaphore is required, or linked list might change */
				pxFileChain = ( FF_FILE * ) pxIOManager->FirstFile;
				if( pxFileChain != NULL )
				{
					/* Count elements in FirstFile */
					do
					{
						pxFileChain->ulValidFlags |= FF_VALID_FLAG_INVALID;
						xResult++;
						pxFileChain = pxFileChain->pxNext;
					}
					while( pxFileChain != NULL );
				}
			}

			FF_ReleaseSemaphore( pxIOManager->pvSemaphore );
		}

		return xResult;
	}	/* FF_Invalidate() */
#endif /* ffconfigREMOVABLE_MEDIA */
/*-----------------------------------------------------------*/

/**
*	@public
*	@brief	Check validity of file handle
*
*	@param	pxFile		FF_FILE object that was created by FF_Open().
*
*	@return 0 on sucess.
*	@return FF_ERR_NULL_POINTER       if a null pointer was provided.
*	@return FF_ERR_FILE_BAD_HANDLE    if handle is not recognized
*	@return FF_ERR_FILE_MEDIA_REMOVED please call FF_Close
*
**/
FF_Error_t FF_CheckValid( FF_FILE *pxFile )
{
	FF_FILE		*pxFileChain;
	FF_Error_t	xError;

	if( ( pxFile == NULL ) || ( pxFile->pxIOManager == NULL ) )
	{
		xError = ( FF_Error_t ) ( FF_ERR_NULL_POINTER | FF_CHECKVALID );
	}
	else
	{
		FF_PendSemaphore( pxFile->pxIOManager->pvSemaphore );
		{
			pxFileChain = ( FF_FILE * ) pxFile->pxIOManager->FirstFile;
			xError = ( FF_Error_t ) ( FF_ERR_FILE_BAD_HANDLE | FF_CHECKVALID );
			while( pxFileChain != NULL )
			{
				if( pxFileChain == pxFile )
				{
				#if( ffconfigREMOVABLE_MEDIA != 0 )
					if( ( pxFileChain->ulValidFlags & FF_VALID_FLAG_INVALID ) != 0 )
					{
						/* The medium has been removed while this file handle was open. */
						xError = ( FF_Error_t ) ( FF_ERR_FILE_MEDIA_REMOVED | FF_CHECKVALID );
					}
					else
				#endif
					{
						/* Found the handle, so it is a valid / existing handle. */
						xError = FF_ERR_NONE;
					}

					break;
				}

				pxFileChain = pxFileChain->pxNext;
			}
		}
		FF_ReleaseSemaphore( pxFile->pxIOManager->pvSemaphore );
	}

	return xError;
}	/* FF_CheckValid() */
/*-----------------------------------------------------------*/

#if( ffconfigTIME_SUPPORT != 0 )
	/**
	*	@public
	*	@brief	Set the time-stamp(s) of a file entry
	*
	*	@param	pxFile		FF_FILE object that was created by FF_Open().
	*	@param	pxTime      FF_SystemTime_t the time stamp
	*	@param	uxWhat       UBaseType_t a combination of enum ETimeMask
	*
	*	@return 0 or FF_Error_t
	*
	**/
	FF_Error_t FF_SetFileTime( FF_FILE *pxFile, FF_SystemTime_t *pxTime, UBaseType_t uxWhat )
	{
	FF_DirEnt_t	xOriginalEntry;
	FF_Error_t	xError;

		xError = FF_CheckValid( pxFile );
		if( FF_isERR( xError ) == pdFALSE )
		{
			if( pxFile->ulValidFlags & FF_VALID_FLAG_DELETED )
			{	/*if (pxFile->FileDeleted) */
				xError = ( FF_Error_t ) ( FF_ERR_FILE_NOT_FOUND | FF_SETFILETIME );
			}
			else if( ( pxFile->ucMode & ( FF_MODE_WRITE | FF_MODE_APPEND ) ) == 0 )
			{
				xError = ( FF_Error_t ) ( FF_ERR_FILE_NOT_OPENED_IN_WRITE_MODE | FF_SETFILETIME );
			}
			else
			{
				/* Update the Dirent! */
				xError = FF_GetEntry( pxFile->pxIOManager, pxFile->usDirEntry, pxFile->ulDirCluster, &xOriginalEntry );
				if( FF_isERR( xError ) == pdFALSE )
				{
					if( uxWhat & ETimeCreate )
					{
						xOriginalEntry.xCreateTime = *pxTime;		/*/< Date and Time Created. */
					}

					if( uxWhat & ETimeMod )
					{
						xOriginalEntry.xModifiedTime = *pxTime;	/*/< Date and Time Modified. */
					}

					if( uxWhat & ETimeAccess )
					{
						xOriginalEntry.xAccessedTime = *pxTime;	/*/< Date of Last Access. */
					}

					xError = FF_PutEntry( pxFile->pxIOManager, pxFile->usDirEntry, pxFile->ulDirCluster, &xOriginalEntry, NULL );
				}

				if( FF_isERR( xError ) == pdFALSE )
				{
					xError = FF_FlushCache( pxFile->pxIOManager );		/* Ensure all modfied blocks are flushed to disk! */
				}
			}
		}

		return xError;
	}	/* FF_SetFileTime() */
#endif /* ffconfigTIME_SUPPORT */
/*-----------------------------------------------------------*/

#if( ffconfigTIME_SUPPORT != 0 )
	/**
	*	@public
	*	@brief	Set the time-stamp(s) of a file entry (by name)
	*
	*	@param	pxIOManager		FF_IOManager_t device handle
	*	@param	pcPath		int8_t/FF_T_WCHAR name of the file
	*	@param	pxTime       FF_SystemTime_t the time stamp
	*	@param	uxWhat       UBaseType_t a combination of enum ETimeMask
	*
	*	@return 0 or FF_Error_t
	*
	**/
	#if( ffconfigUNICODE_UTF16_SUPPORT != 0 )
	FF_Error_t FF_SetTime ( FF_IOManager_t * pxIOManager, const FF_T_WCHAR * pcPath, FF_SystemTime_t *pxTime, UBaseType_t uxWhat )
	#else
	FF_Error_t FF_SetTime ( FF_IOManager_t * pxIOManager, const char *pcPath, FF_SystemTime_t *pxTime, UBaseType_t uxWhat )
	#endif	/* ffconfigUNICODE_UTF16_SUPPORT */
	{
	FF_DirEnt_t xOriginalEntry;
	FF_Error_t xError;
	uint32_t ulFileCluster;
	BaseType_t xIndex;
	FF_FindParams_t xFindParams;
	#if( ffconfigUNICODE_UTF16_SUPPORT != 0 )
		FF_T_WCHAR pcFileName[ffconfigMAX_FILENAME];
	#else
		char pcFileName[ffconfigMAX_FILENAME];
	#endif	/* ffconfigUNICODE_UTF16_SUPPORT */

		xIndex = ( BaseType_t ) STRLEN( pcPath );

		memset( &xFindParams, '\0', sizeof( xFindParams ) );

		while( xIndex != 0 )
		{
			if( pcPath[ xIndex ] == '\\' || pcPath[ xIndex ] == '/' )
			{
				break;
			}

			xIndex--;
		}

		STRNCPY( pcFileName, ( pcPath + xIndex + 1 ), ffconfigMAX_FILENAME );

		if( xIndex == 0 )
		{
			xIndex = 1;
		}

		xFindParams.ulDirCluster = FF_FindDir( pxIOManager, pcPath, ( uint16_t ) xIndex, &xError );
		if( FF_isERR( xError ) == pdFALSE )
		{
			if( xFindParams.ulDirCluster == 0 )
			{
				xError = ( FF_Error_t ) ( FF_ERR_FILE_NOT_FOUND | FF_SETTIME );
			}
			else
			{
				ulFileCluster = FF_FindEntryInDir( pxIOManager, &xFindParams, pcFileName, 0, &xOriginalEntry, &xError );
				if( ( FF_isERR( xError ) == pdFALSE ) || ( FF_GETERROR( xError ) == FF_ERR_DIR_END_OF_DIR ) )
				{
					if( ulFileCluster == 0ul )
					{
						/*FF_PRINTF ("FF_SetTime: Can not find '%s'\n", pcFileName); */
						xError = ( FF_Error_t ) ( FF_ERR_FILE_NOT_FOUND | FF_SETTIME );
					}
				}
			}
		}

		if( FF_isERR( xError ) == pdFALSE )
		{
			/* Update the Dirent! */
			if( uxWhat & ETimeCreate )
			{
				xOriginalEntry.xCreateTime = *pxTime;			/*/< Date and Time Created. */
			}

			if( uxWhat & ETimeMod )
			{
				xOriginalEntry.xModifiedTime = *pxTime;		/*/< Date and Time Modified. */
			}

			if( uxWhat & ETimeAccess )
			{
				xOriginalEntry.xAccessedTime = *pxTime;		/*/< Date of Last Access. */
			}

			xError = FF_PutEntry( pxIOManager, xOriginalEntry.usCurrentItem - 1, xFindParams.ulDirCluster, &xOriginalEntry, NULL );

			if( FF_isERR( xError ) == pdFALSE )
			{
				xError = FF_FlushCache( pxIOManager );			/* Ensure all modified blocks are flushed to disk! */
			}
		}

		return xError;
	}	/* FF_SetTime() */
#endif /* ffconfigTIME_SUPPORT */
/*-----------------------------------------------------------*/

#if( ffconfigUNICODE_UTF16_SUPPORT != 0 )
FF_Error_t FF_SetPerm( FF_IOManager_t * pxIOManager, const FF_T_WCHAR * pcPath, UBaseType_t aPerm )
#else
FF_Error_t FF_SetPerm( FF_IOManager_t * pxIOManager, const char *pcPath, UBaseType_t aPerm )
#endif
{
FF_DirEnt_t xOriginalEntry;
FF_Error_t xError;
uint32_t ulFileCluster;
BaseType_t xIndex;
#if( ffconfigUNICODE_UTF16_SUPPORT != 0 )
	FF_T_WCHAR pcFileName[ffconfigMAX_FILENAME];
#else
	char pcFileName[ffconfigMAX_FILENAME];
#endif
FF_FindParams_t xFindParams;

	xIndex = ( BaseType_t ) STRLEN( pcPath );

	memset( &xFindParams, '\0', sizeof( xFindParams ) );

	while( xIndex != 0 )
	{
		if( pcPath[ xIndex ] == '\\' || pcPath[ xIndex ] == '/' )
		{
			break;
		}

		xIndex--;
	}

	STRNCPY( pcFileName, ( pcPath + xIndex + 1 ), ffconfigMAX_FILENAME );

	if( xIndex == 0 )
	{
		xIndex = 1;
	}

	/* Open a do {} while( pdFALSE ) loop to allow the use of break statements. */
	do
	{
		xFindParams.ulDirCluster = FF_FindDir( pxIOManager, pcPath, ( uint16_t ) xIndex, &xError );
		if( xError )
		{
			break;
		}

		if( !xFindParams.ulDirCluster )
		{
			xError = ( FF_Error_t ) ( FF_ERR_FILE_NOT_FOUND | FF_SETTIME );
			break;
		}

		ulFileCluster = FF_FindEntryInDir( pxIOManager, &xFindParams, pcFileName, 0, &xOriginalEntry, &xError );
		if( FF_isERR( xError ) )
		{
			break;
		}

		if( ulFileCluster == 0ul )
		{
			/*FF_PRINTF ("FF_SetTime: Can not find '%s'\n", pcFileName); */
			xError = ( FF_Error_t ) ( FF_ERR_FILE_NOT_FOUND | FF_SETTIME );
			break;
		}

		/*	#define FF_FAT_ATTR_READONLY		0x01 */
		/*	#define FF_FAT_ATTR_HIDDEN			0x02 */
		/*	#define FF_FAT_ATTR_SYSTEM			0x04 */
		/*	#define FF_FAT_ATTR_VOLID			0x08 */
		/*	#define FF_FAT_ATTR_DIR				0x10 */
		/*	#define FF_FAT_ATTR_ARCHIVE			0x20 */
		/*	#define FF_FAT_ATTR_LFN				0x0F */
	#define FF_FAT_ATTR_USER	( ( uint8_t ) FF_FAT_ATTR_READONLY | FF_FAT_ATTR_HIDDEN | FF_FAT_ATTR_SYSTEM | FF_FAT_ATTR_ARCHIVE )
		/* Update the Dirent! */
		xOriginalEntry.ucAttrib &= ~FF_FAT_ATTR_USER;
		xOriginalEntry.ucAttrib |= ( aPerm & FF_FAT_ATTR_USER );
		xError = FF_PutEntry( pxIOManager, xOriginalEntry.usCurrentItem - 1, xFindParams.ulDirCluster, &xOriginalEntry, NULL );

		if( FF_isERR( xError ) == pdFALSE )
		{
			xError = FF_FlushCache( pxIOManager );			/* Ensure all modfied blocks are flushed to disk! */
		}
	}
	while( pdFALSE );

	return xError;
}	/* FF_SetPerm() */
/*-----------------------------------------------------------*/

/**
*	@public
*	@brief	Equivalent to fclose()
*
*	@param	pxFile		FF_FILE object that was created by FF_Open().
*
*	@return 0 on sucess.
*	@return -1 if a null pointer was provided.
*
**/
FF_Error_t FF_Close( FF_FILE *pxFile )
{
FF_FILE *pxFileChain;
FF_DirEnt_t xOriginalEntry;
FF_Error_t xError;

	/* Opening a do {} while( 0 )  loop to allow the use of the break statement. */
	do
	{
		if( pxFile == NULL )
		{
			xError = ( FF_Error_t ) ( FF_ERR_NULL_POINTER | FF_CLOSE );
			break;
		}

		/* It is important to check that user doesn't supply invalid
		handle or a handle invalid because of "media removed" */
		xError = FF_CheckValid( pxFile );

		#if( ffconfigREMOVABLE_MEDIA != 0 )
		{
			if( FF_GETERROR( xError ) == FF_ERR_FILE_MEDIA_REMOVED )
			{
				FF_PendSemaphore( pxFile->pxIOManager->pvSemaphore );
				{
					pxFileChain = ( FF_FILE * ) pxFile->pxIOManager->FirstFile;
					if( pxFileChain == pxFile )
					{
						pxFile->pxIOManager->FirstFile = pxFile->pxNext;
					}
					else
					{
						while( pxFileChain )
						{
							if( pxFileChain->pxNext == pxFile )
							{
								pxFileChain->pxNext = pxFile->pxNext;
								break;
							}

							pxFileChain = pxFileChain->pxNext;	/* Forgot this one */
						}
					}
				}					/* Semaphore released, linked list was shortened! */

				FF_ReleaseSemaphore( pxFile->pxIOManager->pvSemaphore );
				#if( ffconfigOPTIMISE_UNALIGNED_ACCESS != 0 )
				{
					ffconfigFREE( pxFile->pucBuffer );
				}
				#endif	/* ffconfigOPTIMISE_UNALIGNED_ACCESS */
				ffconfigFREE( pxFile );	/* So at least we have freed the pointer. */
				xError = FF_ERR_NONE;
				break;
			}
		}
		#endif	/* ffconfigREMOVABLE_MEDIA */

		if( FF_isERR( xError ) )
		{
			/* FF_ERR_FILE_BAD_HANDLE or FF_ERR_NULL_POINTER */
			break;
		}

		/* So here we have a normal valid file handle. */

		/* Sometimes FreeRTOS+FAT will leave a trailing cluster on the end of a cluster chain.
		To ensure we're compliant we shall now check for this condition and truncate it. */
		if( ( ( pxFile->ulValidFlags & FF_VALID_FLAG_DELETED ) == 0 ) &&
			( ( pxFile->ucMode & ( FF_MODE_WRITE | FF_MODE_APPEND | FF_MODE_CREATE ) ) != 0 ) )
		{
		uint32_t ulClusterSize;

			/* File is not deleted and it was opened for writing or updating */
			ulClusterSize = pxFile->pxIOManager->xPartition.usBlkSize * pxFile->pxIOManager->xPartition.ulSectorsPerCluster;

			if( ( ( pxFile->ulFileSize % ulClusterSize ) == 0 ) && ( pxFile->ulObjectCluster != 0ul ) )
			{
				/* The file's length is a multiple of cluster size.  This means
				that an extra cluster has been reserved, which wasn't necessary. */
				xError = FF_Truncate( pxFile, pdTRUE );
			}

			/* Get the directory entry and update it to show the new file size */
			if( FF_isERR( xError ) == pdFALSE )
			{
				xError = FF_GetEntry( pxFile->pxIOManager, pxFile->usDirEntry, pxFile->ulDirCluster, &xOriginalEntry );

				/* Now update the directory entry */
				if( ( FF_isERR( xError ) == pdFALSE ) &&
					( ( pxFile->ulFileSize != xOriginalEntry.ulFileSize ) || ( pxFile->ulFileSize == 0UL ) ) )
				{
					if( pxFile->ulFileSize == 0UL )
					{
						xOriginalEntry.ulObjectCluster = 0;
					}

					xOriginalEntry.ulFileSize = pxFile->ulFileSize;
					xError = FF_PutEntry( pxFile->pxIOManager, pxFile->usDirEntry, pxFile->ulDirCluster, &xOriginalEntry, NULL );
				}
			}
		}

		/* Handle Linked list! */
		FF_PendSemaphore( pxFile->pxIOManager->pvSemaphore );
		{	/* Semaphore is required, or linked list could become corrupted. */
			pxFileChain = ( FF_FILE * ) pxFile->pxIOManager->FirstFile;
			if( pxFileChain == pxFile )
			{
				pxFile->pxIOManager->FirstFile = pxFile->pxNext;
			}
			else
			{
				while( pxFileChain )
				{
					if( pxFileChain->pxNext == pxFile )
					{
						/* Found it, remove it from the list. */
						pxFileChain->pxNext = pxFile->pxNext;
						break;
					}
					pxFileChain = pxFileChain->pxNext;
				}
			}
		}	/* Semaphore released, linked list was shortened! */
		FF_ReleaseSemaphore( pxFile->pxIOManager->pvSemaphore );

		#if( ffconfigOPTIMISE_UNALIGNED_ACCESS != 0 )
		{
			if( pxFile->pucBuffer != NULL )
			{
				/* Ensure any unaligned points are pushed to the disk! */
				if( pxFile->ucState & FF_BUFSTATE_WRITTEN )
				{
				FF_Error_t xTempError;

					xTempError = FF_BlockWrite( pxFile->pxIOManager, FF_FileLBA( pxFile ), 1, pxFile->pucBuffer, pdFALSE );
					if( FF_isERR( xError ) == pdFALSE )
					{
						xError = xTempError;
					}
				}

				ffconfigFREE( pxFile->pucBuffer );
			}
		}
		#endif
		if( FF_isERR( xError ) == pdFALSE )
		{
			xError = FF_FlushCache( pxFile->pxIOManager ); /* Ensure all modified blocks are flushed to disk! */
		}
		ffconfigFREE( pxFile );
	}
	while( pdFALSE );

	return xError;
}	/* FF_Close() */
/*-----------------------------------------------------------*/

/**
*	@public
*	@brief	Make Filesize equal to the FilePointer and truncates the file to this position
*
*	@param	pxFile		FF_FILE object that was created by FF_Open().
*
*	@return 0 on sucess.
*	@return negative if some error occurred
*
**/
FF_Error_t FF_SetEof( FF_FILE *pxFile )
{
	FF_Error_t xError;

	/* Check if the file was not deleted and if it was opened with write permissions: */
	if( ( ( pxFile->ulValidFlags & FF_VALID_FLAG_DELETED ) == 0 ) &&
		( ( pxFile->ucMode & ( FF_MODE_WRITE | FF_MODE_APPEND | FF_MODE_CREATE ) ) != 0 ) )
	{
		pxFile->ulFileSize = pxFile->ulFilePointer;
		if( pxFile->ulObjectCluster != 0ul )
		{
			xError = FF_Truncate( pxFile, pdFALSE );
		}
		else
		{
			xError = FF_ERR_NONE;
		}
	}
	else
	{
		xError = ( FF_Error_t ) ( FF_ERR_FILE_NOT_OPENED_IN_WRITE_MODE | FF_SETEOF );
	}

	return xError;
}	/* FF_SetEof() */
/*-----------------------------------------------------------*/

/**
*	@public
*	@brief	Truncate a file to 'pxFile->ulFileSize'
*
*	@param	pxFile		FF_FILE object that was created by FF_Open().
*
*	@return 0 on sucess.
*	@return negative if some error occurred
*
**/
static FF_Error_t FF_Truncate( FF_FILE *pxFile, BaseType_t bClosing )
{
FF_Error_t xError;
FF_IOManager_t *pxIOManager = pxFile->pxIOManager;

uint32_t ulClusterSize;
uint32_t ulClusterCount;
uint32_t ulClustersNeeded;

	/* The number of bytes contained in a cluster. */
	ulClusterSize = pxIOManager->xPartition.usBlkSize * pxIOManager->xPartition.ulSectorsPerCluster;

	/* See how many clusters have been allocated. */
	ulClusterCount = FF_GetChainLength( pxIOManager, pxFile->ulObjectCluster, NULL, &xError );

	/* Calculate the actual number of clusters needed, rounding up */
	ulClustersNeeded = ( pxFile->ulFileSize + ulClusterSize - 1 ) / ulClusterSize;
	if( bClosing != pdFALSE )
	{
		/* The handle will be closed after truncating.  This function is called
		because Filesize is an exact multiple of ulClusterSize. */
		ulClustersNeeded = pxFile->ulFileSize / ulClusterSize;
	}
	else
	{
		/* This function is called to make the file size equal to the current
		position within the file. Always keep an extra cluster to write to. */
		ulClustersNeeded = ( pxFile->ulFileSize + ulClusterSize ) / ulClusterSize;
	}

	/* First change the FAT chain. */
	if( ( FF_isERR( xError ) == pdFALSE ) && ( ulClusterCount > ulClustersNeeded ) )
	{
		if( ulClustersNeeded == 0ul )
		{
			FF_LockFAT( pxIOManager );
			{
				/* In FF_Truncate() */
				xError = FF_UnlinkClusterChain( pxIOManager, pxFile->ulObjectCluster, 0 );
			}
			FF_UnlockFAT( pxIOManager );

			if( FF_isERR( xError ) == pdFALSE )
			{
			FF_DirEnt_t xOriginalEntry;

				/* The directory denotes the address of the first data cluster of every file.
				Now change it to 'ulAddrCurrentCluster': */
				xError = FF_GetEntry( pxIOManager, pxFile->usDirEntry, pxFile->ulDirCluster, &xOriginalEntry );

				if( FF_isERR( xError ) == pdFALSE )
				{
					xOriginalEntry.ulObjectCluster = 0ul;
					xError = FF_PutEntry( pxIOManager, pxFile->usDirEntry, pxFile->ulDirCluster, &xOriginalEntry, NULL );

					if( FF_isERR( xError ) == pdFALSE )
					{
						pxFile->ulObjectCluster = 0ul;
						pxFile->ulChainLength = 0ul;
						pxFile->ulCurrentCluster = 0ul;
						pxFile->ulEndOfChain = 0ul;
					}
				}
			}
		}
		else
		{
			FF_LockFAT( pxIOManager );
			{
				uint32_t ulTruncateCluster = FF_TraverseFAT( pxIOManager, pxFile->ulObjectCluster, ulClustersNeeded - 1, &xError );

				if( FF_isERR( xError ) == pdFALSE )
				{
					xError = FF_UnlinkClusterChain( pxIOManager, ulTruncateCluster, 1 );
				}
			}
			FF_UnlockFAT( pxIOManager );
		}
	}

	return xError;
}	/* FF_Truncate() */
/*-----------------------------------------------------------*/