summaryrefslogtreecommitdiffstats
path: root/libvideoeditor/osal/src/M4OSA_FileCache.c
blob: a8041234bf4ed996f17df5c826df20752077fde7 (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
/*
 * Copyright (C) 2004-2011 NXP Software
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 *************************************************************************
 * @file         M4OSA_FileCache.c
 *
 * @brief        Osal File Reader and Writer with cache
 * @note         This file implements functions to manipulate
 *               filesystem access with intermediate buffers used to
 *               read and to write.
 *************************************************************************
*/

/**
 *************************************************************************
 * File cache buffers parameters (size, number of buffers, etc)
 *************************************************************************
*/
#define M4OSA_CACHEBUFFER_SIZE    (8*1024)
#define M4OSA_CACHEBUFFER_NB    6
#define M4OSA_CACHEBUFFER_NONE    -1
#define M4OSA_CACHEBUFFER_ALL    -2
#define M4OSA_EOF               -1

/** Strategy used by Osal File Cache to flush the buffers to disk.
Depending on the service, the strategy will have more or less success */
//#define BUFFER_SELECT_INITIAL        /** Initial implementation of Osal File Reader optim */
//#define BUFFER_SELECT_WITH_TIME    /** To flush in priority the buffers which have not been used for a certain time */
//#define BUFFER_SELECT_WITH_SPACE    /** To flush in priority the buffers which have not been used a lot of times */
#define BUFFER_SELECT_WITH_POS    /** To flush in priority the buffers which have the smallest position on the file */

/* to measure success of cache operations */
//#define FILECACHE_STATS

/* For performance measure */
//#define M4OSA_FILE_CACHE_TIME_MEAS

/***  To debug */
//#define NO_STRATEGY
//#define BUFFER_DISPLAY

#ifdef M4OSA_FILE_CACHE_TIME_MEAS
#include "M4OSA_clock.h"

typedef enum
{
    fileOpentime,
    fileClosetime,
    fileReadDatatime,
    fileWriteDatatime,
    fileSeektime,
    fileGetOptiontime,
    fileSetOptiontime,
    fileExternalFlushtime,
    enum_size    /* for enum size */
} M4OSA_filetimeType;

typedef    M4OSA_Time TabFiletime[enum_size+1];

void M4OSA_FileCache_initTimeMeas(M4OSA_Context pContext);
void M4OSA_FileCache_displayTimeMeas(M4OSA_Context pContext);

#endif /* M4OSA_FILE_CACHE_TIME_MEAS */

/* ANSI C*/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
/* End: ANSI C includes */

#include "M4OSA_FileCommon.h"
#include "M4OSA_FileReader.h"
#include "M4OSA_FileWriter.h"

#include "M4OSA_FileCache.h"

#include "M4OSA_Memory.h"
#include "M4OSA_Debug.h"
#include "M4OSA_CharStar.h"
#include "M4OSA_Mutex.h"


#define LOCK \
    M4OSA_mutexLock(apContext->m_mutex, M4OSA_WAIT_FOREVER);

#define UNLOCK \
    M4OSA_mutexUnlock(apContext->m_mutex);

typedef struct
{
    M4OSA_Void*                FileDesc;
} M4OSA_FileSystem_FFS_t_cache;

typedef struct
{
    M4OSA_Void*        (*pFctPtr_Open)( M4OSA_Void* fd,
                                       M4OSA_UInt32 FileModeAccess,
                                       M4OSA_UInt16* errno_ffs );
    M4OSA_FilePosition (*pFctPtr_Read)( M4OSA_Void* fd,
                                       M4OSA_UInt8* data,
                                       M4OSA_FilePosition size,
                                       M4OSA_UInt16* errno_ffs );
    M4OSA_FilePosition (*pFctPtr_Write)( M4OSA_Void* fd,
                                         M4OSA_UInt8* data,
                                         M4OSA_FilePosition size,
                                         M4OSA_UInt16* errno_ffs );
    M4OSA_FilePosition (*pFctPtr_Seek)( M4OSA_Void* fd,
                                        M4OSA_FilePosition pos,
                                        M4OSA_FileSeekAccessMode mode,
                                        M4OSA_UInt16* errno_ffs );
    M4OSA_FilePosition (*pFctPtr_Tell)( M4OSA_Void* fd,
                                        M4OSA_UInt16* errno_ffs );
    M4OSA_Int32        (*pFctPtr_Close)( M4OSA_Void* fd,
                                         M4OSA_UInt16* errno_ffs );
    M4OSA_Void         (*pFctPtr_AccessType)( M4OSA_UInt32 FileModeAccess_In,
                                             M4OSA_Void* FileModeAccess_Out );

} M4OSA_FileSystem_FctPtr_cache;

M4OSA_Void* M4OSA_FileSystem_FFS_Open_cache( M4OSA_Void* pFileDescriptor,
                                             M4OSA_UInt32 FileModeAccess,
                                             M4OSA_UInt16* errno_ffs );
M4OSA_Int32 M4OSA_FileSystem_FFS_Close_cache( M4OSA_Void* pContext,
                                              M4OSA_UInt16* errno_ffs );
M4OSA_FilePosition M4OSA_FileSystem_FFS_Read_cache( M4OSA_Void* pContext,
                                                    M4OSA_UInt8* data,
                                                    M4OSA_FilePosition size,
                                                    M4OSA_UInt16* errno_ffs );
M4OSA_FilePosition M4OSA_FileSystem_FFS_Write_cache( M4OSA_Void* pContext,
                                                     M4OSA_UInt8* data,
                                                     M4OSA_FilePosition size,
                                                     M4OSA_UInt16* errno_ );
M4OSA_Int32 M4OSA_FileSystem_FFS_Seek_cache( M4OSA_Void* pContext,
                                             M4OSA_FilePosition pos,
                                             M4OSA_FileSeekAccessMode mode,
                                             M4OSA_UInt16* errno_ffs );
M4OSA_FilePosition M4OSA_FileSystem_FFS_Tell_cache( M4OSA_Void* pContext,
                                                    M4OSA_UInt16* errno_ffs );

M4OSA_ERR M4OSA_fileOpen_cache_internal(M4OSA_Context* pContext,
                                        M4OSA_Void* pFileDescriptor,
                                        M4OSA_UInt32 FileModeAccess,
                                        M4OSA_FileSystem_FctPtr_cache *FS);

/*
------------------User--------------------
                   ^
                   |
--------    --------    ----------
|Filled|    |Copied|    |Modified|
--------    --------    ----------
  ^
  |
------------------Disk--------------------

Atomic states for a buffer:

0x00    initialized or flushed (When it is initialized again, it is flushed if necessary)
0x01    Filled from disk
0x03    Filled and Copied to user

0x80    Modified and newly created (does not exist on disk) => must be flushed
0x83    Modified after having been read from disk => must be flushed

*/

typedef enum
{
    M4OSA_kInitialized = 0,
    M4OSA_kFilled = 0x1,
    M4OSA_kCopied = 0x2,
    M4OSA_kModified = 0x80
} M4OSA_FileCacheStateAtomic;


/**
 ******************************************************************************
 * structure    M4OSA_FileCache_Buffer
 * @brief       This structure defines the File Buffers context (private)
 ******************************************************************************
*/
typedef struct
{
    M4OSA_MemAddr8      data;        /**< buffer data */
    M4OSA_FilePosition  size;        /**< size of the buffer */
    M4OSA_FilePosition  filepos;    /**< position in the file of the buffer's first octet */
    M4OSA_FilePosition  remain;        /**< data amount not already copied from buffer */

    M4OSA_UInt32        nbFillSinceLastAcess;    /**< To know since how many time we didn't use this buffer. to detect  dead buffers */

    M4OSA_UInt32        nbAccessed;            /**< nb of times the buffer has been accessed without being reinitialized */
    M4OSA_Time            timeAccessed;         /**< last time at which the buffer has been accessed without being reinitialized */

    M4OSA_UInt8            state;
} M4OSA_FileCache_Buffer;

/**
 ******************************************************************************
 * structure    M4OSA_FileCache_Context
 * @brief       This structure defines the File context (private)
 * @note        This structure is used for all File calls to store the context
 ******************************************************************************
*/
typedef struct
{
    M4OSA_Bool          IsOpened;               /**< Micro state machine */
    M4OSA_FileAttribute FileAttribute;          /**< Opening mode */
    M4OSA_FilePosition     readFilePos;            /**< Effective position of the file pointer */
    M4OSA_FilePosition     absolutePos;            /**< Virtual position for next reading */
    M4OSA_FilePosition     absoluteWritePos;        /**< Virtual position for next writing */
    M4OSA_FilePosition     fileSize;                /**< Size of the file */
    M4OSA_FilePosition     virtualFileSize;        /**< Size of the file */

    M4OSA_FileCache_Buffer buffer[M4OSA_CACHEBUFFER_NB];  /**< buffers */

    M4OSA_Void*             aFileDesc;          /**< File descriptor */
    M4OSA_FileSystem_FctPtr_cache *FS;                /**< Filesystem interface */

#ifdef FILECACHE_STATS
    M4OSA_UInt32        cacheSuccessRead;
    M4OSA_UInt32        cacheSuccessWrite;
    M4OSA_UInt32        nbReadCache;
    M4OSA_UInt32        nbWriteCache;

    M4OSA_UInt32        nbReadFFS;
    M4OSA_UInt32        nbWriteFFS;
#endif /* FILECACHE_STATS */
    M4OSA_Context        m_mutex;

    M4OSA_Time            chrono;
    M4OSA_Char            m_filename[256];

#ifdef M4OSA_FILE_CACHE_TIME_MEAS
    TabFiletime            gMyPerfFileTab;
#endif /* M4OSA_FILE_CACHE_TIME_MEAS */

} M4OSA_FileCache_Context;


#define M4ERR_CHECK_NULL_RETURN_VALUE(retval, pointer) if ((pointer) == M4OSA_NULL) return (retval);

/* used to detect dead buffers */
#define MAX_FILLS_SINCE_LAST_ACCESS    M4OSA_CACHEBUFFER_NB*2


/* __________________________________________________________ */
/*|                                                          |*/
/*|        Quick Sort function    (private)                     |*/
/*|__________________________________________________________|*/

M4OSA_Void M4OSA_FileCache_internalQuicksort(M4OSA_Int32* const table,
                               const M4OSA_Int32 first , const M4OSA_Int32 last)
 {
    M4OSA_Int32 startIndex;
    M4OSA_Int32 endIndex;
    M4OSA_Int32 begin;
    M4OSA_Int32 end;
    M4OSA_Int32 pivot;
    M4OSA_Int32 temp;
    M4OSA_Int32 index=0;
    M4OSA_Int32 size=0;
    M4OSA_Int32 capacity = M4OSA_CACHEBUFFER_NB * 5;
    //allocation of the fifo
    M4OSA_Int32* queue = M4OSA_NULL;
    M4OSA_Int32* cursor;
    M4OSA_Int32* indexc;

    queue = (M4OSA_Int32*)M4OSA_malloc(capacity*sizeof(M4OSA_Int32), 0,
                                   (M4OSA_Char*) "quicksort FIFO of FileCache");

    if(queue == M4OSA_NULL)
        return;
    cursor = queue;
    indexc = queue;
    *(cursor++) = first; //remember the array first element
    *(cursor++) = last;    //remember the array end
    index = 0;
    size = 2;
    do
    {
        startIndex   = *(indexc++);
        endIndex    = *(indexc++);
        index+=2;
        if(startIndex < endIndex)
        {
            begin    = startIndex;
            end        = endIndex;
            pivot    = table[endIndex];
            do
            {
                while ( (begin < endIndex) && (table[begin]<=pivot) )
                    begin++;
                while ( (end > begin) && (table[end]>=pivot) )
                    end--;
                if (begin < end)
                {
                    temp            = table[end];
                    table[end]        = table[begin];
                    table[begin]    = temp;
                }
            }while(begin < end);

            temp            = table[endIndex];
            table[endIndex]        = table[begin];
            table[begin]    = temp;
            *(cursor++) = startIndex;
            *(cursor++) = begin-1;
            *(cursor++) = begin+1;
            *(cursor++) =  endIndex;
            size+=4;
            if(size==capacity)
            {
                M4OSA_TRACE1_0("Overflow in quickSort. increase capacity size");
                return;
            }
        }
    }
    while(index<size);
    cursor = NULL;
    indexc = NULL;
    M4OSA_free(queue);
}

M4OSA_Void M4OSA_FileCache_internalQuicksort64(M4OSA_Int64* const table,
                               const M4OSA_Int32 first , const M4OSA_Int32 last)
 {
    M4OSA_Int32 startIndex;
    M4OSA_Int32 endIndex;
    M4OSA_Int32 begin;
    M4OSA_Int32 end;
    M4OSA_Int64 pivot;
    M4OSA_Int64 temp;
    M4OSA_Int32 index=0;
    M4OSA_Int32 size=0;
    M4OSA_Int32 capacity = M4OSA_CACHEBUFFER_NB * 5;
    //allocation of the fifo
    M4OSA_Int32* queue = M4OSA_NULL;
    M4OSA_Int32* cursor;
    M4OSA_Int32* indexc;

    queue = (M4OSA_Int32*)M4OSA_malloc(capacity*sizeof(M4OSA_Int32), 0,
                                   (M4OSA_Char*) "quicksort FIFO of FileCache");

    if(queue == M4OSA_NULL)
        return;
    cursor = queue;
    indexc = queue;
    *(cursor++) = first; //remember the array first element
    *(cursor++) = last;    //remember the array end
    index = 0;
    size = 2;
    do
    {
        startIndex   = *(indexc++);
        endIndex    = *(indexc++);
        index+=2;
        if(startIndex < endIndex)
        {
            begin    = startIndex;
            end        = endIndex;
            pivot    = table[endIndex];
            do
            {
                while ( (begin < endIndex) && (table[begin]<=pivot) )
                    begin++;
                while ( (end > begin) && (table[end]>=pivot) )
                    end--;
                if (begin < end)
                {
                    temp            = table[end];
                    table[end]        = table[begin];
                    table[begin]    = temp;
                }
            }while(begin < end);

            temp            = table[endIndex];
            table[endIndex]        = table[begin];
            table[begin]    = temp;
            *(cursor++) = startIndex;
            *(cursor++) = begin-1;
            *(cursor++) = begin+1;
            *(cursor++) =  endIndex;
            size+=4;
            if(size==capacity)
            {
                M4OSA_TRACE1_0("Overflow in quickSort. increase capacity size");
                return;
            }
        }
    }
    while(index<size);
    cursor = NULL;
    indexc = NULL;
    M4OSA_free(queue);
}

/* Sorts an array of size size */
M4OSA_Void M4OSA_FileCache_QS_quickSort (M4OSA_FilePosition array[],
                                                              M4OSA_UInt32 size)
{
    if (size==1 || size==0)
    {
        M4OSA_TRACE3_0("Sort not necessary");
        return;
    }

    M4OSA_FileCache_internalQuicksort(array,0,size-1);
}

M4OSA_Void M4OSA_FileCache_QS_quickSort64 (M4OSA_Time array[], M4OSA_UInt32 size)
{
    if (size==1 || size==0)
    {
        M4OSA_TRACE3_0("Sort not necessary");
        return;
    }

    M4OSA_FileCache_internalQuicksort64(array,0,size-1);
}

/* __________________________________________________________ */
/*|                                                          |*/
/*|   Buffer handling functions for RW access  (private)     |*/
/*|__________________________________________________________|*/

/**************************************************************/
M4OSA_ERR M4OSA_FileCache_BuffersInit(M4OSA_FileCache_Context* apContext)
/**************************************************************/
{
    M4OSA_UInt8 i;

    for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
    {
        apContext->buffer[i].state = M4OSA_kInitialized;
        M4OSA_memset((M4OSA_MemAddr8)&(apContext->buffer[i]),
                                            sizeof(M4OSA_FileCache_Buffer) , 0);
    }

    for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
    {
        apContext->buffer[i].data = (M4OSA_MemAddr8) M4OSA_malloc(M4OSA_CACHEBUFFER_SIZE,
                  M4OSA_FILE_READER, (M4OSA_Char*)"M4OSA_FileCache_BufferInit");
        M4ERR_CHECK_NULL_RETURN_VALUE(M4ERR_ALLOC, apContext->buffer[i].data);
        apContext->buffer[i].filepos = M4OSA_EOF;

    }

    return M4NO_ERROR;
}

/**************************************************************/
M4OSA_Void M4OSA_FileCache_BuffersFree(M4OSA_FileCache_Context* apContext)
/**************************************************************/
{
    M4OSA_UInt8 i;

    for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
    {
        if(apContext->buffer[i].data != M4OSA_NULL)
        {
            M4OSA_free((M4OSA_MemAddr32)apContext->buffer[i].data);
            apContext->buffer[i].data = M4OSA_NULL;
        }
    }
}

#ifdef BUFFER_DISPLAY
M4OSA_Void M4OSA_FileCache_BufferDisplay(M4OSA_FileCache_Context* apContext)
{
    M4OSA_UInt32 i;

    M4OSA_TRACE1_0("------ Buffers display ");
    for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
    {
        M4OSA_TRACE1_5("------ Buf%d : FilePos=%d state=0x%x nbAccessed=%d -- timeAccessed=%d",
                                                i, apContext->buffer[i].filepos,
                                                apContext->buffer[i].state,
                                                apContext->buffer[i].nbAccessed,
                                                apContext->buffer[i].timeAccessed);
    }
    M4OSA_TRACE1_0("---------------------- ");
}
#endif


/* reads from an existing buffer (number i) at absolute position pos and fills pData. it reads maximum one bloc */
/**************************************************************/
M4OSA_FilePosition M4OSA_FileCache_BufferCopy(M4OSA_FileCache_Context* apContext,
                                              M4OSA_Int8 i, M4OSA_FilePosition pos,
                                              M4OSA_FilePosition size,
                                              M4OSA_MemAddr8 pData)
/**************************************************************/
{
    M4OSA_FilePosition copysize;
    M4OSA_FilePosition offset;

    M4OSA_TRACE3_2("BufferCopy of %d, pos=%d", i, pos);

    if(apContext->buffer[i].size == M4OSA_EOF) return M4OSA_EOF;

    /* verification pos is inside buffer i*/
    if(   (pos < apContext->buffer[i].filepos)
       || (pos > (apContext->buffer[i].filepos + apContext->buffer[i].size - 1)) )
    {
        return 0; /* nothing copied */
    }

    offset = pos - apContext->buffer[i].filepos;    /* offset to read from in the buffer */

    copysize = apContext->buffer[i].size - offset;    /* buffer size - offset, it is the maximum we can read from a buffer */
    copysize = (size < copysize) ? size : copysize; /* adjust in case user wants to read less than the data available in the buffer (copysize)
                                                        in that case, take the min(copysize, size)*/

    M4OSA_memcpy(pData, apContext->buffer[i].data + offset, copysize);

    apContext->buffer[i].remain -= copysize;
    apContext->buffer[i].nbFillSinceLastAcess = 0;


    /* it is a read access */
    apContext->buffer[i].nbAccessed++;
    apContext->buffer[i].timeAccessed = apContext->chrono;
    apContext->chrono++;


    apContext->buffer[i].state |= M4OSA_kCopied;

    return copysize;
}

/* writes on cache. at absolute position pos and writes pData to the buffer. it writes maximum one bloc */
/**************************************************************/
M4OSA_FilePosition M4OSA_FileCache_BufferModifyContent(M4OSA_FileCache_Context* apContext,
                                                       M4OSA_Int8 i, M4OSA_FilePosition pos,
                                                       M4OSA_FilePosition size,
                                                       M4OSA_MemAddr8 pData)
/**************************************************************/
{
    M4OSA_FilePosition copysize;
    M4OSA_FilePosition offset, gridPos;

    M4OSA_TRACE3_2("BufferModify of %d, pos=%d", i, pos);

    /* Relocate to absolute postion if necessary */
    gridPos = (pos / M4OSA_CACHEBUFFER_SIZE) * M4OSA_CACHEBUFFER_SIZE;

    apContext->buffer[i].filepos = gridPos;

    /* in case of an existing block (not at eof) */
    if    (apContext->buffer[i].size != 0)
    {
        /* test if we are already inside this buffer */
        if (   (pos < apContext->buffer[i].filepos)
           || (pos > (apContext->buffer[i].filepos + M4OSA_CACHEBUFFER_SIZE)) )
        {
            M4OSA_TRACE1_0("BufferModify ERR nothing copied, should never happen");
            return 0; /* nothing copied */
        }
    }

    offset = pos - apContext->buffer[i].filepos;    /* offset to write to, in the buffer */

    /* buffer size - offset, it is the maximum we can write into a buffer */
    copysize = M4OSA_CACHEBUFFER_SIZE - offset;
    /* adjust in case user wants to write less than the data available in the buffer (copysize) in that case, take the min(copysize, size)*/
    copysize = (copysize < size) ? copysize : size;

    M4OSA_memcpy(apContext->buffer[i].data + offset, pData, copysize);

    /* update buffer size if it is a new buffer or expanded one*/
    if (apContext->buffer[i].size < copysize+offset)
    {
        apContext->buffer[i].size = copysize+offset;
    }

    apContext->buffer[i].remain = M4OSA_CACHEBUFFER_SIZE - apContext->buffer[i].size; /* not temporary */

    /* mark this buffer as modified */
    apContext->buffer[i].state |= M4OSA_kModified;

    apContext->buffer[i].nbFillSinceLastAcess = 0;
    apContext->buffer[i].nbAccessed++;
    apContext->buffer[i].timeAccessed = apContext->chrono;
    apContext->chrono++;

    return copysize;
}


/* writes in a buffer (number i) with the data read from disk*/
/**************************************************************/
M4OSA_ERR M4OSA_FileCache_BufferFill(M4OSA_FileCache_Context* apContext,
                                     M4OSA_Int8 i, M4OSA_FilePosition pos)
/**************************************************************/
{
    M4OSA_FilePosition gridPos;
    M4OSA_FilePosition diff;
    M4OSA_FilePosition size;
    M4OSA_ERR err = M4NO_ERROR;
    M4OSA_Int32 ret_val;
    M4OSA_UInt16 errReturned;

    M4OSA_TRACE3_2("BufferFill  i = %d  pos = %d", i, pos);

    /* Avoid cycling statement because of EOF */
    if(pos > apContext->virtualFileSize)
            return M4WAR_NO_MORE_AU;

    /* Relocate to absolute postion if necessary */
    gridPos = (pos / M4OSA_CACHEBUFFER_SIZE) * M4OSA_CACHEBUFFER_SIZE;

    /* diff is how much shall we fs_seek from current position to reach gridPos*/
    diff = gridPos - apContext->readFilePos;

    /* on some filesystems it is necessary to do a seek between an ffs read and ffs write even if it is same pos */
        ret_val = apContext->FS->pFctPtr_Seek(apContext->aFileDesc,
                                    diff, M4OSA_kFileSeekCurrent, &errReturned);
        apContext->readFilePos = gridPos;

        if(ret_val != 0)
        {
            err = M4OSA_ERR_CREATE(M4_ERR, M4OSA_FILE_READER, errReturned);
            M4OSA_TRACE2_1("M4OSA_FileCache_BufferFill ERR1 = 0x%x", err);
            return err;
        }
    /* end. on some */

/* the buffer will be reused to be filled with another filepos so reinit counters of access */
    if (apContext->buffer[i].filepos  != gridPos)
    {
        apContext->buffer[i].nbAccessed = 0;
        apContext->buffer[i].timeAccessed = 0;
    }

    /* stores the information relative to this buffer */
    apContext->buffer[i].filepos = gridPos;

    /* Read Data */
    size = apContext->FS->pFctPtr_Read(apContext->aFileDesc,
                                       (M4OSA_UInt8*)apContext->buffer[i].data,
                                        M4OSA_CACHEBUFFER_SIZE, &errReturned);

#ifdef FILECACHE_STATS
    apContext->nbReadFFS++;
#endif /* FILECACHE_STATS */

    if(size == -1)
    {
        apContext->buffer[i].size = M4OSA_EOF;
        apContext->buffer[i].remain = 0;

        err = M4OSA_ERR_CREATE(M4_ERR, M4OSA_FILE_READER, errReturned);
        M4OSA_TRACE2_1("M4OSA_FileCache_BufferFill ERR2 = 0x%x", err);
        return err;
    }

    apContext->buffer[i].size = size;
    apContext->buffer[i].remain = size;
    apContext->buffer[i].nbFillSinceLastAcess = 0;


    /* Retrieve current position */
    apContext->readFilePos = apContext->FS->pFctPtr_Tell(apContext->aFileDesc,
                                                                  &errReturned);

    if(   (apContext->buffer[i].size >= 0)
       && (apContext->buffer[i].size < M4OSA_CACHEBUFFER_SIZE) )
    {
        err = M4WAR_NO_DATA_YET;
        M4OSA_TRACE2_1("M4OSA_FileCache_BufferFill ERR3 = 0x%x", err);
        return err;
    }

    /* mark this buffer as modified */
    apContext->buffer[i].state |= M4OSA_kFilled;

    /* it is a write access */
    apContext->buffer[i].nbAccessed++;
    apContext->buffer[i].timeAccessed = apContext->chrono;
    apContext->chrono++;

    /* Return without error */
    return M4NO_ERROR;
}

/*  Reinitializes a buffer for filling it for data at end of file. fileposition is given */
/**************************************************************/
M4OSA_ERR M4OSA_FileCache_BufferReinitialize(M4OSA_FileCache_Context* apContext,
                                           M4OSA_Int8 i, M4OSA_FilePosition pos)
/**************************************************************/
{
    M4OSA_FilePosition gridPos;
    M4OSA_ERR err = M4NO_ERROR;

    M4OSA_MemAddr8 saveDataAddress;

    M4OSA_TRACE3_2("BufferReinitialize i = %d  pos = %d", i, pos);

    /* Relocate to absolute postion if necessary */
    if (pos != -1)
        gridPos = (pos / M4OSA_CACHEBUFFER_SIZE) * M4OSA_CACHEBUFFER_SIZE;
    else
        gridPos = -1;

    /* RAZ the buffer, only "data address" stays*/
    saveDataAddress = apContext->buffer[i].data;

    M4OSA_memset((M4OSA_MemAddr8)&(apContext->buffer[i]),
                                            sizeof(M4OSA_FileCache_Buffer) , 0);

    /* put again the precious "data address" previously allocated */
    apContext->buffer[i].data = saveDataAddress;

    /* initializations already done in the memset: */
    /* mark this buffer as initialized*/
    apContext->buffer[i].state= M4OSA_kInitialized;
    apContext->buffer[i].nbAccessed = 0;
    apContext->buffer[i].timeAccessed = 0;

    /* Relocate to absolute postion if necessary */
    apContext->buffer[i].filepos = gridPos;

    /* Return without error */
    return M4NO_ERROR;
}


/* flushes a buffer (number i) to the disk*/
/**************************************************************/
M4OSA_ERR M4OSA_FileCache_BufferFlush(M4OSA_FileCache_Context* apContext,
                                                                  M4OSA_UInt8 i)
/**************************************************************/
{
    M4OSA_FilePosition gridPos, pos;
    M4OSA_FilePosition diff;
    M4OSA_FilePosition size;
    M4OSA_ERR err = M4NO_ERROR;
    M4OSA_Int32 ret_val;
    M4OSA_UInt16 errReturned;

    M4OSA_TRACE3_2("BufferFlush of buffer i=%d its pos=%d", i,
                                                  apContext->buffer[i].filepos);

    pos = apContext->buffer[i].filepos;

    /* Relocate to absolute postion if necessary */
    gridPos = (pos / M4OSA_CACHEBUFFER_SIZE) * M4OSA_CACHEBUFFER_SIZE;

    /* diff is how much shall we fs_seek from current position to reach gridPos*/
    diff = gridPos - apContext->readFilePos;

    if (pos > apContext->fileSize)
    {
        M4OSA_TRACE1_2("M4OSA_FileCache_BufferFlush: Error! Attempt to seek at pos=%d, whilst fileSize=%d ",
                                                      pos, apContext->fileSize);
        return M4WAR_NO_MORE_AU;
    }

    /* on some filesystems it is necessary to do a seek between an ffs read and ffs write even if it is same pos */
        ret_val = apContext->FS->pFctPtr_Seek(apContext->aFileDesc, diff,
                                          M4OSA_kFileSeekCurrent, &errReturned);
        apContext->readFilePos = gridPos;

        if(ret_val != 0)
        {
            err = M4OSA_ERR_CREATE(M4_ERR, M4OSA_FILE_READER, errReturned);
            M4OSA_TRACE1_1("M4OSA_FileCache_BufferFill ERR1 = 0x%x", err);
            return err;
        }
    /* end: on some filesystems*/

    /* update the read file pos after the seek */
    apContext->readFilePos = apContext->buffer[i].filepos;

    /* Write Data */
    size = apContext->FS->pFctPtr_Write(apContext->aFileDesc,
                                        (M4OSA_UInt8*)apContext->buffer[i].data,
                                        apContext->buffer[i].size, &errReturned);
#ifdef FILECACHE_STATS
    apContext->nbWriteFFS++;
#endif /* FILECACHE_STATS */
     /* verify if all data requested to be written, has been written */
    if(size < apContext->buffer[i].size)
    {
        apContext->buffer[i].size = M4OSA_EOF;
        apContext->buffer[i].remain = 0;

        err = M4OSA_ERR_CREATE(M4_ERR, M4OSA_FILE_READER, errReturned);
        M4OSA_TRACE1_1("M4OSA_FileCache_BufferFlush ERR2 = 0x%x", err);
        return err;
    }

    /* Retrieve current position */
    apContext->readFilePos = apContext->FS->pFctPtr_Tell(apContext->aFileDesc,
                                                                  &errReturned);

    apContext->fileSize = (apContext->readFilePos > apContext->fileSize) ? apContext->readFilePos : apContext->fileSize;

    /* mark this buffer as not modified */
    apContext->buffer[i].state &= ~(M4OSA_kModified);

    /* Return without error */
    return M4NO_ERROR;
}

/* flushes all modified buffers until the position of buffer i
if index is M4OSA_CACHEBUFFER_ALL then flush all*/
/**************************************************************/
M4OSA_ERR M4OSA_FileCache_BuffersFlushUntil(M4OSA_FileCache_Context* apContext,
                                                               M4OSA_Int8 index)
/**************************************************************/
{
    M4OSA_UInt8 i, j, howManyToFlush;
    M4OSA_FilePosition bufPos[M4OSA_CACHEBUFFER_NB];
    M4OSA_Bool flushed = M4OSA_FALSE;
    M4OSA_ERR err = M4NO_ERROR;


    i=0;
    for(j=0; j<M4OSA_CACHEBUFFER_NB; j++)
    {
        if ( ((apContext->buffer[j].state & M4OSA_kModified) == M4OSA_kModified)                    )
        {
            bufPos[i] = apContext->buffer[j].filepos;
            i++;
        }
    }
    howManyToFlush = i;

    if (howManyToFlush == 0)
    {
        M4OSA_TRACE2_0("BuffersFlush : no flush needed");
        return M4NO_ERROR;
    }
    else if (howManyToFlush == 1)
    {
        goto flushing;
    }

    M4OSA_FileCache_QS_quickSort(bufPos, howManyToFlush);

flushing:
    if (index == M4OSA_CACHEBUFFER_ALL)
    {/* simply flush all buffers in order of positions */
        for(j=0; j<howManyToFlush; j++)
        {
            for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
            if (apContext->buffer[i].filepos == bufPos[j] )
            {
                M4OSA_TRACE2_2("M4OSA_FileCache_BuffersFlushUntil(1) : We Need to Flush buffer %d its pos=%d",
                                               i, apContext->buffer[i].filepos);
                err = M4OSA_FileCache_BufferFlush(apContext, i);
                if (M4NO_ERROR!= err)
                {
                    return err;
                }
                break;
            }
        }
    }
    else
    { /* there is a given index to flush until it*/
        for(j=0; j<howManyToFlush; j++)
        {
            for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
            {
                if (
                        apContext->buffer[i].filepos == bufPos[j]
                        && apContext->buffer[i].filepos <= apContext->buffer[index].filepos
                        && apContext->buffer[i].filepos >= apContext->fileSize - M4OSA_CACHEBUFFER_SIZE
                    )
                    {
                        M4OSA_TRACE2_2("M4OSA_FileCache_BuffersFlushUntil(2) : We Need to Flush buffer %d its pos=%d",
                                               i, apContext->buffer[i].filepos);
                        err = M4OSA_FileCache_BufferFlush(apContext, i);
                        if (M4NO_ERROR!= err)
                        {
                            return err;
                        }
                        if (i==index)
                        {    /* the buffer with the given index has been flushed */
                            flushed = M4OSA_TRUE;
                        }
                        break;
                    }
            }

        }

        if (M4OSA_TRUE == flushed)
        {
            err = M4NO_ERROR;
        }
        else
        {
            M4OSA_TRACE1_1("M4OSA_FileCache_BuffersFlushUntil err=0x%x", err);
            err = M4ERR_BAD_CONTEXT;
        }

    }

    return err;

}

#ifdef BUFFER_DISPLAY
M4OSA_Void M4OSA_FileCache_BufferDisplay(M4OSA_FileCache_Context* apContext)
{
    M4OSA_UInt32 i;

    M4OSA_TRACE1_0("------ Buffers display ");
    for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
    {
        M4OSA_TRACE1_3("------ Buf%d : FilePos=%d state=0x%x ",
                   i, apContext->buffer[i].filepos, apContext->buffer[i].state);
#ifdef BUFFER_DATE
        M4OSA_TRACE1_2("nbAccessed=%d - nbModified =%d",
              apContext->buffer[i].nbAccessed, apContext->buffer[i].nbModified);
        M4OSA_TRACE1_2("timeAccessed=%d - timeModified =%d",
                                              apContext->buffer[i].timeAccessed,
                                               apContext->buffer[i].timeModified);
#endif /* BUFFER_DATE */
    }
    M4OSA_TRACE1_0("---------------------- ");
}
#endif


/* provides the buffer corresponding to a position pos
and with pos inside the read data into this buffer
else returns CACHE_BUFFER_NONE*/
/**************************************************************/
M4OSA_Int8 M4OSA_FileCache_BufferMatchToRead(M4OSA_FileCache_Context* apContext,
                                                         M4OSA_FilePosition pos)
/**************************************************************/
{
    M4OSA_Int8 i;

    /* Select the buffer which matches with given pos */
    for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
    {
        if(   (pos >= apContext->buffer[i].filepos)
            && (pos < apContext->buffer[i].filepos + apContext->buffer[i].size)
            && (apContext->buffer[i].filepos != M4OSA_EOF)                     )
        {
            M4OSA_TRACE3_1("BufferMatch returns  i = %d", i);
            return i;
        }
    }

    M4OSA_TRACE3_1("BufferMatch returns  N O N E !!!", i);
    return M4OSA_CACHEBUFFER_NONE;
}


/* provides the buffer corresponding to a position pos
and with pos inside its maximum capacity
else returns CACHE_BUFFER_NONE*/
/**************************************************************/
M4OSA_Int8 M4OSA_FileCache_BufferMatchToWrite(M4OSA_FileCache_Context* apContext,
                                                         M4OSA_FilePosition pos)
/**************************************************************/
{
    M4OSA_Int8 i;

    /* Select the buffer which matches with given pos */
    for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
    {
        if(   (pos >= apContext->buffer[i].filepos)
           && (pos < apContext->buffer[i].filepos + M4OSA_CACHEBUFFER_SIZE)
            && (apContext->buffer[i].filepos != M4OSA_EOF)                )
        {
            M4OSA_TRACE3_1("BufferMatch returns  i = %d", i);
            return i;
        }
    }

    M4OSA_TRACE3_1("BufferMatch returns  N O N E !!!", i);
    return M4OSA_CACHEBUFFER_NONE;
}

/* chooses a buffer by overwriting an existing one and returns i */
/**************************************************************/
M4OSA_Int8 M4OSA_FileCache_BufferSelectForWrite(M4OSA_FileCache_Context* apContext)
/**************************************************************/
{
    M4OSA_Int8 i;
    M4OSA_UInt8 selected = 0;
    M4OSA_UInt32 j, toSort;
    M4OSA_FilePosition bufPos[M4OSA_CACHEBUFFER_NB];
    M4OSA_ERR err;

    // update nbFillSinceLastAcess field
    for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
    {
        apContext->buffer[i].nbFillSinceLastAcess ++;
    }
#ifdef NO_STRATEGY
    goto end_selection;
#endif

    /*********************************************/
    /* 1/ if there is still a new buffer, use it */

    for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
    {
        if(apContext->buffer[i].state == M4OSA_kInitialized)
        {
            selected = i;
            goto end_selection;
        }
    }

    /*********************************************/
    /* 2/ Choose a filled and copied buffer      */

    for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
    {
        if( ((apContext->buffer[i].state & M4OSA_kFilled) == M4OSA_kFilled)
            && ((apContext->buffer[i].state & M4OSA_kCopied) == M4OSA_kCopied)
            && ((apContext->buffer[i].state & M4OSA_kModified) != M4OSA_kModified)   /* bug fix modified */
           )
        {
            selected = i;
            goto end_selection;
        }
    }

    /****************************************************************/
    /* 3/ Choose a modified buffer with filepos>threshold and min   */
    i=0;

    /* sort the buffers by filepos and choose the min and not < threshold*/
    for(j=0; j<M4OSA_CACHEBUFFER_NB; j++)
    {
        if  (
             ((apContext->buffer[j].state & M4OSA_kModified) == M4OSA_kModified)
             && (apContext->buffer[j].filepos > -1) /* not EOF */
             )
        {
            bufPos[i] = apContext->buffer[j].filepos;
            i++;
        }
    }

    toSort = i;
    if (toSort == 0 )
    {
        selected = 0;
        goto end_selection;
    }
    else if (toSort ==1 )
    {
        goto skip_sort;
    }
    else
    {
        M4OSA_FileCache_QS_quickSort(bufPos, toSort);
    }

skip_sort:
    /* take the smallest filepos */
    for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
    {
        if (apContext->buffer[i].filepos == bufPos[0])
        {
            selected = i;
            goto end_selection;
        }
    }

end_selection:
    if (apContext->buffer[selected].filepos > apContext->fileSize )
    {
        /* in case it selects a modified buffer outside real file size,
        in that case, flush all buffers before this one
        unless there will be a seek outside filesize*/
        M4OSA_FileCache_BuffersFlushUntil(apContext, selected);
    }
    else if ((apContext->buffer[selected].state & M4OSA_kModified) == M4OSA_kModified )
    {
        /* in case it selects a modified buffer inside filesize, simply flush it*/
        err = M4OSA_FileCache_BufferFlush(apContext, selected);
        if (M4NO_ERROR!= err)
        {
            return M4OSA_CACHEBUFFER_NONE;
        }
    }

#ifdef NO_STRATEGY
    /* selected stays 0 */
    err = M4OSA_FileCache_BuffersFlushUntil(apContext, M4OSA_CACHEBUFFER_ALL);
    if (M4NO_ERROR!= err)
    {
        return M4OSA_FILE_CACHE_BUFFER_NONE;
    }
#endif

    M4OSA_TRACE3_1("---------- BufferSelect returns  i = %d", selected);
     return selected;
}


/* chooses a buffer by overwriting an existing one and returns i */
/**************************************************************/
M4OSA_Int8 M4OSA_FileCache_BufferSelectWithTime(M4OSA_FileCache_Context* apContext)
/**************************************************************/
{
    M4OSA_Int8 i;
    M4OSA_UInt8 selected = 0;
    M4OSA_UInt32 j, toSort;
    M4OSA_Time bufTime[M4OSA_CACHEBUFFER_NB];
    M4OSA_ERR err;

    /*********************************************/
    /* 1/ if there is still a new buffer, use it */

    for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
    {
        if(apContext->buffer[i].state == M4OSA_kInitialized)
        {
            selected = i;
            goto end_selection;
        }
    }

    i=0;
    /* sort all buffers with order of timeAccessed */
    for(j=0; j<M4OSA_CACHEBUFFER_NB; j++)
    {
        bufTime[i] = apContext->buffer[j].timeAccessed;
        i++;
    }

    toSort = i;
    if (toSort == 0 )
    {
        selected = 0;
        goto end_selection;
    }
    else if (toSort ==1 )
    {
        goto skip_sort;
    }
    else
    {
        M4OSA_FileCache_QS_quickSort64(bufTime, toSort);
    }

skip_sort:
    /* take the smallest timeAccessed */
    for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
    {
        if (apContext->buffer[i].timeAccessed == bufTime[0])
        {
            selected = i;
            goto end_selection;
        }
    }

end_selection:
    if (apContext->buffer[selected].filepos > apContext->fileSize )
    {
        /* in case it selects a modified buffer outside real file size,
        in that case, flush all buffers before this one
        unless there will be a seek outside filesize*/
        M4OSA_FileCache_BuffersFlushUntil(apContext, selected);
    }
    else if ((apContext->buffer[selected].state & M4OSA_kModified) == M4OSA_kModified )
    {
        /* in case it selects a modified buffer inside filesize, simply flush it*/
        err = M4OSA_FileCache_BufferFlush(apContext, selected);
        if (M4NO_ERROR!= err)
        {
            return M4OSA_CACHEBUFFER_NONE;
        }
    }
    M4OSA_TRACE3_1("---------- BufferSelect returns  i = %d", selected);
     return selected;
}

/* chooses a buffer by overwriting an existing one and returns i */
/**************************************************************/
M4OSA_Int8 M4OSA_FileCache_BufferSelectWithPos(M4OSA_FileCache_Context* apContext)
/**************************************************************/
{
    M4OSA_Int8 i;
    M4OSA_UInt8 selected = 0, j;
    M4OSA_ERR err;
    M4OSA_FilePosition minPos;

    /*********************************************/
    /* 1/ if there is still a new buffer, use it */

    for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
    {
        if(apContext->buffer[i].state == M4OSA_kInitialized)
        {
            selected = i;
            goto end_selection;
        }
    }

    minPos = apContext->buffer[0].filepos;
    selected = 0;
    for(j=1; j<M4OSA_CACHEBUFFER_NB; j++)
    {
        if (apContext->buffer[j].filepos < minPos)
        {
            minPos = apContext->buffer[j].filepos;
            selected = j;
        }
    }

end_selection:
    if (apContext->buffer[selected].filepos > apContext->fileSize )
    {
        /* in case it selects a modified buffer outside real file size,
        in that case, flush all buffers before this one
        unless there will be a seek outside filesize*/
        M4OSA_TRACE3_2("BufferSelectWithPos selected buffer is ouside file b.filepos=%d > fileSize=%d",
                                            apContext->buffer[selected].filepos,
                                             apContext->fileSize );
        M4OSA_FileCache_BuffersFlushUntil(apContext, selected);
    }
    else if ((apContext->buffer[selected].state & M4OSA_kModified) == M4OSA_kModified )
    {
        /* in case it selects a modified buffer inside filesize, simply flush it*/
        err = M4OSA_FileCache_BufferFlush(apContext, selected);
        if (M4NO_ERROR!= err)
        {
            return M4OSA_CACHEBUFFER_NONE;
        }
    }
    M4OSA_TRACE3_1("---------- BufferSelectWithPos returns  i = %d", selected);
     return selected;
}


/* chooses a buffer by overwriting an existing one and returns i */
/**************************************************************/
M4OSA_Int8 M4OSA_FileCache_BufferSelectWithSpace(M4OSA_FileCache_Context* apContext)
/**************************************************************/
{
    M4OSA_Int8 i;
    M4OSA_UInt8 selected = 0;
    M4OSA_UInt32 j, toSort;
    M4OSA_FilePosition bufStat[M4OSA_CACHEBUFFER_NB];
    M4OSA_ERR err;

    /*********************************************/
    /* 1/ if there is still a new buffer, use it */

    for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
    {
        if(apContext->buffer[i].state == M4OSA_kInitialized)
        {
            selected = i;
            goto end_selection;
        }
    }

    i=0;
    /* sort all buffers with order of nbAccessed */
    for(j=0; j<M4OSA_CACHEBUFFER_NB; j++)
    {
        bufStat[i] = apContext->buffer[j].nbAccessed + apContext->buffer[j].timeAccessed*2; /* try hybrid */
        i++;
    }

    toSort = i;
    if (toSort == 0 )
    {
        selected = 0;
        goto end_selection;
    }
    else if (toSort ==1 )
    {
        goto skip_sort;
    }
    else
    {
        M4OSA_FileCache_QS_quickSort(bufStat, toSort);
    }

skip_sort:
    /* take the smallest nbAccessed */
    for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
    {
        if ((M4OSA_Int64) apContext->buffer[i].nbAccessed  + apContext->buffer[i].timeAccessed*2 == bufStat[0]) /* hybrid */
        {
            selected = i;
            goto end_selection;
        }
    }

end_selection:
    if (apContext->buffer[selected].filepos > apContext->fileSize )
    {
        /* in case it selects a modified buffer outside real file size,
        in that case, flush all buffers before this one
        unless there will be a seek outside filesize*/
        M4OSA_FileCache_BuffersFlushUntil(apContext, selected);
    }
    else if ((apContext->buffer[selected].state & M4OSA_kModified) == M4OSA_kModified )
    {
        /* in case it selects a modified buffer inside filesize, simply flush it*/
        err = M4OSA_FileCache_BufferFlush(apContext, selected);
        if (M4NO_ERROR!= err)
        {
            return M4OSA_CACHEBUFFER_NONE;
        }
    }
    M4OSA_TRACE3_1("---------- BufferSelect returns  i = %d", selected);
     return selected;
}


/**************************************************************/
M4OSA_Int8 M4OSA_FileCache_BufferSelectForRead(M4OSA_FileCache_Context* apContext)
/**************************************************************/
{
    M4OSA_Int8 i,j, selected;
    M4OSA_FilePosition min_amount,max_amount;
    M4OSA_Int8 min_i,max_count;
    M4OSA_ERR err;

    /* update nbFillSinceLastAcess field */
    for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
    {
        apContext->buffer[i].nbFillSinceLastAcess ++;
    }

    /**************************************************/
    /* Plan A/ if there is still a new buffer, use it */

    for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
    {
        if(apContext->buffer[i].state == M4OSA_kInitialized)
        {
            selected = i;
            goto end_selection;
        }
    }

    max_count = M4OSA_CACHEBUFFER_NB;
    max_amount = MAX_FILLS_SINCE_LAST_ACCESS;

    /* Plan B : Scan for dead buffer */
    for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
    {
        if(apContext->buffer[i].nbFillSinceLastAcess >= (M4OSA_UInt32) max_amount)
        {
            max_amount = apContext->buffer[i].nbFillSinceLastAcess;
            max_count = i;
        }
    }
    if(max_count<M4OSA_CACHEBUFFER_NB)
    {
        M4OSA_TRACE3_2("DEAD BUFFER: %d, %d",max_count,apContext->buffer[max_count].nbFillSinceLastAcess);
        selected = max_count;
        goto end_selection;
    }

    min_i = 0;
    min_amount = M4OSA_CACHEBUFFER_NB;

    /* Select the buffer which is the most "empty" */
    for(i=0; i<M4OSA_CACHEBUFFER_NB; i++)
    {
        j = i % M4OSA_CACHEBUFFER_NB;

        if(apContext->buffer[j].remain < min_amount)
        {
            min_amount = apContext->buffer[j].remain;
            min_i = j;
        }
    }
    selected = min_i;

end_selection:
    if (apContext->buffer[selected].filepos > apContext->fileSize )
    {
        /* in case it selects a modified buffer outside real file size,
        in that case, flush all buffers before this one
        unless there will be a seek outside filesize*/
        M4OSA_FileCache_BuffersFlushUntil(apContext, selected);
    }
    else if ((apContext->buffer[selected].state & M4OSA_kModified) == M4OSA_kModified )
    {
        /* in case it selects a modified buffer inside filesize, simply flush it*/
        err = M4OSA_FileCache_BufferFlush(apContext, selected);
        if (M4NO_ERROR!= err)
        {
            return M4OSA_CACHEBUFFER_NONE;
        }
    }

    return selected;
}


/**************************************************************/
M4OSA_ERR M4OSA_FileCache_CalculateSize(M4OSA_FileCache_Context* apContext)
/**************************************************************/
{
    M4OSA_ERR    err = M4NO_ERROR;
    M4OSA_Int32  ret_val;
    M4OSA_UInt16 errReturned;

    /* go to the end of file*/
    ret_val = apContext->FS->pFctPtr_Seek(apContext->aFileDesc, 0,
                                          M4OSA_kFileSeekEnd,
                                          &errReturned);

    if (ret_val != 0)
    {
        apContext->readFilePos = M4OSA_EOF;
        err = M4OSA_ERR_CREATE(M4_ERR, M4OSA_FILE_READER, errReturned);
        M4OSA_TRACE2_1("M4OSA_FileCache_CalculateSize ERR = 0x%x", err);
    }
    else
    {
        /* Retrieve size of the file */
        apContext->fileSize = apContext->FS->pFctPtr_Tell(apContext->aFileDesc,
                                                                  &errReturned);
        apContext->readFilePos = apContext->fileSize;
    }

    return err;
}

/* _____________________________________________________________  */
/*|                                                             | */
/*| OSAL filesystem functions dependent on Platform FileSystem  | */
/*|_____________________________________________________________| */

/**
 ************************************************************************
 * @brief   Opens a file
 * @note
 * @param   pFileDescriptor :    IN    url of the file
 *          FileModeAccess  :    IN    access mode for opening the file
 *          errno_ffs           :   OUT internal error returned by the filesystem
 * @return  pC              :   internal context
 ************************************************************************
*/
M4OSA_Void* M4OSA_FileSystem_FFS_Open_cache( M4OSA_Void* pFileDescriptor,
                                             M4OSA_UInt32 FileModeAccess,
                                             M4OSA_UInt16* errno_ffs )
{

    M4OSA_FileSystem_FFS_t_cache     *pC = M4OSA_NULL;
    FILE* fp;

    M4OSA_Char  mode[4]            = "";
    M4OSA_Char* pReadString        = (M4OSA_Char*)"r";
    M4OSA_Char* pWriteString    = (M4OSA_Char*)"w";
    M4OSA_Char* pAppendString    = (M4OSA_Char*)"a";
    M4OSA_Char* pBinaryString    = (M4OSA_Char*)"b";
    M4OSA_Char* pPlusString        = (M4OSA_Char*)"+";

    fp = M4OSA_NULL;
    *errno_ffs = 0;

    M4OSA_TRACE3_0("M4OSA_FileSystem_FFS_Open_cache : Open **** \n");

     /************************/
     /*  Verify access mode  */
     /************************/

    /*
    All possible file accesses:

        r : Read only, file must exist

        w : Write only. If the file exists, it is overwritten. If it does not exist, it is created.

        a : write at end of file (append). If the file exists, it is extended. If the file does not exist, it is created.

        r+ : update (i.e. read and write). The file must exist. It is not possible to do a read after a write (or a write after a read)
        unless we reposition the file pointer.

        w+ : creation, to update. If the file exists, it is overwritten. If the files does not exist, it is created.
        a+ : extension and update. If the file does not exist, it is created. If the file exists, the file pointer is put at end of file.

    All possible cases for fileModeAccess parameter:

        Write(2)            w
        WriteRead(3)        r+    // r+b Used by MM
        WriteReadCreate(11)    w+    // w+b Used by MM
        WriteReadAppend(7)    a+
        WriteCreate(10)        w
        WriteAppend(12)        a
        Read                r    // rb Used by MM
        Error
    */


    if ((FileModeAccess & M4OSA_kFileWrite) && (FileModeAccess & M4OSA_kFileRead) && (FileModeAccess & M4OSA_kFileCreate)) /* Used by MM */
    {
        /** "w+" */
        M4OSA_chrNCat(mode, pWriteString, 1);
        M4OSA_chrNCat(mode, pPlusString, 1);
    }
    else if ((FileModeAccess & M4OSA_kFileWrite) && (FileModeAccess & M4OSA_kFileRead) && (FileModeAccess & M4OSA_kFileAppend))
    {
        /** "a+" */
        M4OSA_chrNCat(mode, pAppendString, 1);
        M4OSA_chrNCat(mode, pPlusString, 1);
    }
    else if ((FileModeAccess & M4OSA_kFileWrite) && (FileModeAccess & M4OSA_kFileRead))    /* Used by MM */
    {
        /** "r+" */
        M4OSA_chrNCat(mode, pReadString, 1);
        M4OSA_chrNCat(mode, pPlusString, 1);
    }
    else if ((FileModeAccess & M4OSA_kFileWrite) && (FileModeAccess & M4OSA_kFileCreate))
    {
        /** "w" */
        M4OSA_chrNCat(mode, pWriteString, 1);
    }
    else if ((FileModeAccess & M4OSA_kFileWrite) && (FileModeAccess & M4OSA_kFileAppend))
    {
        /** "a" */
        M4OSA_chrNCat(mode, pAppendString, 1);
    }
    else if (FileModeAccess & M4OSA_kFileRead)
    {
        /** "r" */
        M4OSA_chrNCat(mode, pReadString, 1);
    }
    else if (FileModeAccess & M4OSA_kFileWrite)
    {
        /** "w" */
        M4OSA_chrNCat(mode, pWriteString, 1);
    }
    else
    {
        M4OSA_TRACE1_1("M4OSA_FileSystem_FFS_Open_cache : invalid FileModeAccess = %x", FileModeAccess);
        *errno_ffs = (M4OSA_UInt16)M4ERR_FILE_BAD_MODE_ACCESS;
    }

    /* add the b */
    M4OSA_chrNCat(mode, pBinaryString, 1);

    fp = fopen((const char *) pFileDescriptor, (const char *)mode); /* Open in rb or in r+b*/
    if( fp != NULL )
    {
        pC = (M4OSA_FileSystem_FFS_t_cache *) M4OSA_malloc(sizeof * pC, M4OSA_FILE_READER, (M4OSA_Char*)"M4OSA_FileSystem_FFS_Open_cache");

        if (pC == M4OSA_NULL) return M4OSA_NULL; /*error occured => return NULL pointer*/

        pC->FileDesc = fp;
    }
    else
    {
        switch(errno)
        {
            case ENOENT:
                 M4OSA_DEBUG(M4ERR_FILE_NOT_FOUND, "M4OSA_fileReadOpen: No such file or directory");
                 *errno_ffs=(M4OSA_UInt16)M4ERR_FILE_NOT_FOUND;
                 break;

            case EACCES:
                M4OSA_DEBUG(M4ERR_FILE_LOCKED, "M4OSA_fileReadOpen: Permission denied");
                *errno_ffs=(M4OSA_UInt16)M4ERR_FILE_LOCKED;
                break;

            case EINVAL:
                M4OSA_DEBUG(M4ERR_FILE_BAD_MODE_ACCESS, "M4OSA_fileReadOpen: Invalid Argument");
                *errno_ffs=(M4OSA_UInt16)M4ERR_FILE_BAD_MODE_ACCESS;
                break;

             case EMFILE:
             case ENOSPC:
             case ENOMEM:
                M4OSA_DEBUG(M4ERR_ALLOC, "M4OSA_fileReadOpen: Too many open files");
                *errno_ffs=(M4OSA_UInt16)M4ERR_ALLOC;
                break;

             default:
                M4OSA_DEBUG(M4ERR_NOT_IMPLEMENTED, "M4OSA_fileReadOpen");
                *errno_ffs=(M4OSA_UInt16)M4ERR_NOT_IMPLEMENTED;

        } /* end switch */
    } /* end else */

    return (M4OSA_Void*)pC;
}

/**
 ************************************************************************
 * @brief   Reads data from file
 * @note
 * @param   pContext        :   IN  internal context
 *          data            :    IN  buffer for reading data
 *          size            :    IN    amount of bytes to read
 *          errno_ffs           :   OUT internal error returned by the filesystem
 * @return  ret             :   effective amount of bytes read / -1 if an error occurs
 ************************************************************************
*/
M4OSA_FilePosition M4OSA_FileSystem_FFS_Read_cache( M4OSA_Void* pContext,
                                                    M4OSA_UInt8* data,
                                                    M4OSA_FilePosition size,
                                                    M4OSA_UInt16* errno_ffs )
{
    M4OSA_FileSystem_FFS_t_cache *pC = (M4OSA_FileSystem_FFS_t_cache *)pContext;
    M4OSA_Int32    res;

    M4OSA_TRACE2_1("M4OSA_FileSystem_FFS_Read  size = %ld", size);

    res = -1;

    res = fread(data,sizeof(M4OSA_Char), size, pC->FileDesc);
    if( -1 < res )
    {
        *errno_ffs = M4NO_ERROR;
    }
    else
    {
        *errno_ffs = errno;
    }

    return (M4OSA_FilePosition)res;
}



/**
 ************************************************************************
 * @brief   Writes data to file
 * @note
 * @param   pContext        :   IN  internal context
 *          data            :    IN  buffer with data to write
 *          size            :    IN    amount of bytes to read
 *          errno_ffs           :   OUT internal error returned by the filesystem
 * @return  ret             :   effective amount of bytes read / an error code if an error occurs
 ************************************************************************
*/
M4OSA_FilePosition M4OSA_FileSystem_FFS_Write_cache( M4OSA_Void* pContext,
                                                     M4OSA_UInt8* data,
                                                     M4OSA_FilePosition size,
                                                     M4OSA_UInt16* errno_ffs )
{
    M4OSA_FileSystem_FFS_t_cache *pC = (M4OSA_FileSystem_FFS_t_cache *)pContext;
    M4OSA_Int32    res;

    M4OSA_TRACE2_1("M4OSA_FileSystem_FFS_Write  size = %ld", size);

    res = 0;

    res = fwrite(data,sizeof(M4OSA_Char), size, pC->FileDesc);
    if( -1 < res )
    {
        *errno_ffs = M4NO_ERROR;
    }
    else
    {
        *errno_ffs = errno;
        M4OSA_TRACE1_1("M4OSA_FileSystem_FFS_Write  error", *errno_ffs);
    }

    fflush(pC->FileDesc);

    return (M4OSA_FilePosition)res;
}

/**
 ************************************************************************
 * @brief   Seeks at given position in a file
 * @note
 * @param   pContext        :   IN  internal context
 *          pos             :    IN  amount of bytes for the move
 *          mode            :    IN    kind of seek to perform
 *          errno_ffs           :   OUT internal error returned by the filesystem
 * @return  ret             :   0 on success / any other value if an error occurs
 ************************************************************************
*/
M4OSA_Int32 M4OSA_FileSystem_FFS_Seek_cache( M4OSA_Void* pContext,
                                             M4OSA_FilePosition pos,
                                             M4OSA_FileSeekAccessMode mode,
                                             M4OSA_UInt16* errno_ffs )
{
    M4OSA_FileSystem_FFS_t_cache *pC = (M4OSA_FileSystem_FFS_t_cache *)pContext;

    M4OSA_TRACE2_2("M4OSA_FileSystem_FFS_Seek  pos = %ld  mode = %d", pos, mode);

    switch(mode)
    {
        case M4OSA_kFileSeekBeginning :
            *errno_ffs = fseek(pC->FileDesc, pos, SEEK_SET);
            break;

        case M4OSA_kFileSeekCurrent :
            *errno_ffs= fseek(pC->FileDesc, pos, SEEK_CUR);
            break;

        case M4OSA_kFileSeekEnd :
            *errno_ffs = fseek(pC->FileDesc, pos, SEEK_END);
            break;
    }

    return *errno_ffs;

}

/**
 ************************************************************************
 * @brief   Tells the position of the file pointer
 * @note
 * @param   pContext        :   IN  internal context
 *          errno_ffs           :   OUT internal error returned by the filesystem
 * @return  ret             :   position of the file pointer/ -1 if an error occurs
 ************************************************************************
*/
M4OSA_FilePosition M4OSA_FileSystem_FFS_Tell_cache( M4OSA_Void* pContext,
                                                       M4OSA_UInt16* errno_ffs )
{
    M4OSA_FileSystem_FFS_t_cache *pC = (M4OSA_FileSystem_FFS_t_cache *)pContext;
    M4OSA_FilePosition pos;

    pos = ftell(pC->FileDesc);

    *errno_ffs = 0;

    return pos;
}

/**
 ************************************************************************
 * @brief   Closes the file
 * @note
 * @param   pContext        :   IN  internal context
 *          errno_ffs           :   OUT internal error returned by the filesystem
 * @return  ret             :   0 on success / any other value if an error occurs
 ************************************************************************
*/
M4OSA_Int32 M4OSA_FileSystem_FFS_Close_cache( M4OSA_Void* pContext,
                                                       M4OSA_UInt16* errno_ffs )
{
    M4OSA_FileSystem_FFS_t_cache *pC = (M4OSA_FileSystem_FFS_t_cache *)pContext;

    *errno_ffs = fclose(pC->FileDesc);

    return *errno_ffs;
}

/* __________________________________________________________ */
/*|                                                          |*/
/*|                    OSAL fileCache                        |*/
/*|__________________________________________________________|*/

/**************************************************************/
M4OSA_ERR M4OSA_fileOpen_cache(M4OSA_Context* pContext,
                               M4OSA_Void* pFileDescriptor,
                               M4OSA_UInt32 FileModeAccess)
/**************************************************************/
{
    M4OSA_FileSystem_FctPtr_cache *FS;

    /* Allocate memory for the File System interface */
    FS = (M4OSA_FileSystem_FctPtr_cache *)M4OSA_malloc(sizeof * FS,
                M4OSA_FILE_READER,(M4OSA_Char*)"M4OSA_FileSystem_FctPtr_cache");

    if(M4OSA_NULL == FS)
        return M4ERR_ALLOC;

    FS->pFctPtr_Open = M4OSA_FileSystem_FFS_Open_cache;
    FS->pFctPtr_Read = M4OSA_FileSystem_FFS_Read_cache;
    FS->pFctPtr_Write = M4OSA_FileSystem_FFS_Write_cache;
    FS->pFctPtr_Seek = M4OSA_FileSystem_FFS_Seek_cache;
    FS->pFctPtr_Tell = M4OSA_FileSystem_FFS_Tell_cache;
    FS->pFctPtr_Close = M4OSA_FileSystem_FFS_Close_cache;

    return M4OSA_fileOpen_cache_internal(pContext, pFileDescriptor,
                                                            FileModeAccess, FS);
}

/**
******************************************************************************
* @brief       This method opens the provided fileDescriptor and returns its context.
* @param       pContext:       (OUT) File Cache context.
* @param       pFileDescriptor :       (IN) File Descriptor of the input file.
* @param       FileModeAccess :        (IN) File mode access.
* @return      M4NO_ERROR: there is no error
* @return      M4ERR_PARAMETER pContext or fileDescriptor is NULL
* @return      M4ERR_ALLOC     there is no more memory available
* @return      M4ERR_FILE_BAD_MODE_ACCESS      the file mode access is not correct
* @return      M4ERR_FILE_NOT_FOUND The file can not be opened.
******************************************************************************
*/
M4OSA_ERR M4OSA_fileOpen_cache_internal(M4OSA_Context* pContext,
                                        M4OSA_Void* pFileDescriptor,
                                        M4OSA_UInt32 FileModeAccess,
                                        M4OSA_FileSystem_FctPtr_cache *FS)
{
    M4OSA_FileCache_Context* apContext = M4OSA_NULL;

    M4OSA_ERR   err       = M4NO_ERROR;
    M4OSA_Void* aFileDesc = M4OSA_NULL;
    M4OSA_Bool  buffers_allocated = M4OSA_FALSE;
    M4OSA_UInt16 errReturned = 0;
    M4OSA_Int32 len,name_len;
    M4OSA_Char* pCharFileDesc = (M4OSA_Char*)pFileDescriptor;

#ifdef M4OSA_FILE_CACHE_TIME_MEAS
    M4OSA_Time time1 = 0;
    M4OSA_Time time2 = 0;
#endif /* M4OSA_FILE_CACHE_TIME_MEAS */

    M4OSA_TRACE2_2("M4OSA_fileOpen_cache fd = %s mode = %d", pFileDescriptor,
                                                                FileModeAccess);

    /*      Check input parameters */
    M4ERR_CHECK_NULL_RETURN_VALUE(M4ERR_PARAMETER, pContext);
    M4ERR_CHECK_NULL_RETURN_VALUE(M4ERR_PARAMETER, pFileDescriptor);
    M4ERR_CHECK_NULL_RETURN_VALUE(M4ERR_PARAMETER, FS);

    *pContext = M4OSA_NULL;

    /* Allocate memory for the File reader context. */
    apContext = (M4OSA_FileCache_Context *)M4OSA_malloc(sizeof(M4OSA_FileCache_Context),
                     M4OSA_FILE_READER, (M4OSA_Char*)"M4OSA_FileCache_Context");

    M4ERR_CHECK_NULL_RETURN_VALUE(M4ERR_ALLOC, apContext);


#ifdef M4OSA_FILE_CACHE_TIME_MEAS
        M4OSA_FileCache_initTimeMeas(apContext);
        M4OSA_clockGetTime(&time1,1000);
#endif /* M4OSA_FILE_CACHE_TIME_MEAS */

    /* Set filesystem interface */
    apContext->FS = FS;

    if (M4OSA_kFileWrite == FileModeAccess)
    {
        FileModeAccess |= M4OSA_kFileWrite | M4OSA_kFileCreate;    /* for VA in case of open with only Write flag, we add the Create */
    }

    /* For VA and VES, we need to add access in read, to write the moov for example */
    /* Add the flag Read in all cases, because Osal File Cache uses read at the same time */
    FileModeAccess |= M4OSA_kFileRead;

    aFileDesc = apContext->FS->pFctPtr_Open(pFileDescriptor, FileModeAccess,
                                                                  &errReturned);

    if (aFileDesc != M4OSA_NULL)
    {
        apContext->IsOpened = M4OSA_TRUE;
    }
    else
    {
        /* converts the error to PSW format*/
        err = M4OSA_ERR_CREATE(M4_ERR, M4OSA_FILE_READER, errReturned);
        M4OSA_TRACE1_2("M4OSA_fileOpen_cache error 0x%x for fd = %s", err,
                                                               pFileDescriptor);
        apContext->IsOpened = M4OSA_FALSE;

        /*free the context and associated FS pointers*/
        if (M4OSA_NULL != apContext) /*should never be null*/
        {
            if (M4OSA_NULL != apContext->FS) /*should never be null*/
            {
                M4OSA_free((M4OSA_MemAddr32)apContext->FS);
            }

            M4OSA_free((M4OSA_MemAddr32)apContext);
            apContext = M4OSA_NULL;
        }

        if (M4NO_ERROR != err) goto cleanup;
    }

    /* Allocate buffers */
    err = M4OSA_FileCache_BuffersInit(apContext);
    buffers_allocated = M4OSA_TRUE;

    if (M4NO_ERROR != err) goto cleanup;

    /* Initialize parameters */
    apContext->fileSize = 0;
    apContext->virtualFileSize = 0;
    apContext->absolutePos = 0;
    apContext->absoluteWritePos = 0;


    apContext->readFilePos = 0;

    /* Retrieve the File Descriptor*/
    apContext->aFileDesc = aFileDesc;

    /* Retrieve the File mode Access */
    apContext->FileAttribute.modeAccess = (M4OSA_FileModeAccess)FileModeAccess;

    apContext->chrono = 0;

#ifdef FILECACHE_STATS
    apContext->nbReadCache = 0;
    apContext->nbWriteCache = 0;

    apContext->nbReadFFS = 0;
    apContext->nbWriteFFS = 0;
#endif

    /*Retrieve the File reader context */
    *pContext= (M4OSA_Context)apContext;

    /* Compute file size */
    err = M4OSA_FileCache_CalculateSize(apContext);

    if (M4NO_ERROR != err) goto cleanup;

    apContext->virtualFileSize = apContext->fileSize;

#ifdef M4OSA_FILE_CACHE_TIME_MEAS
    M4OSA_clockGetTime(&time2,1000);
    if (time2>time1)
        apContext->gMyPerfFileTab[fileOpentime] += time2-time1;
#endif /* M4OSA_FILE_CACHE_TIME_MEAS */

    M4OSA_mutexOpen(&(apContext->m_mutex));

    /* filename extraction, just for traces  */
    M4OSA_memset(apContext->m_filename, 256, 0);
    len=( M4OSA_chrLength(pCharFileDesc) )+1;
    for( --len ; (len >= 0 && pCharFileDesc[len] != '\\' && pCharFileDesc[len] != '/') ; len-- );
    name_len=M4OSA_chrLength( &pCharFileDesc[len+1] );
    err=M4OSA_chrNCopy(apContext->m_filename, &pCharFileDesc[len+1], name_len);

    M4OSA_TRACE2_2("M4OSA_fileOpen_cache of %s has pC = 0x%x", apContext->m_filename, apContext);

    return M4NO_ERROR;

cleanup:

    /* free context */
    if (M4OSA_NULL != apContext)
    {
        if(buffers_allocated == M4OSA_TRUE)
        {
            M4OSA_FileCache_BuffersFree(apContext);
        }

        if (M4OSA_NULL != apContext)
        {
            M4OSA_free((M4OSA_MemAddr32)apContext);
            apContext = M4OSA_NULL;
        }
        *pContext = M4OSA_NULL;
    }

    return err;
}

/**
******************************************************************************
* @brief       This method reads the 'size' bytes in the core file reader (selected by its 'context')
*                      and writes the data to the 'data' pointer. If 'size' byte can not be read in the core file reader,
*                      'size' parameter is updated to match the correct number of read bytes.
* @param       pContext:       (IN) File reader context.
* @param       pData : (OUT) Data pointer of the read data.
* @param       pSize : (INOUT) Size of the data to read (in byte).
* @return      M4NO_ERROR: there is no error
* @return      M4ERR_PARAMETER pSize, fileDescriptor or pData is NULL
* @return      M4ERR_ALLOC     there is no more memory available
* @return      M4ERR_BAD_CONTEXT       provided context is not a valid one.
******************************************************************************
*/
M4OSA_ERR M4OSA_fileReadData_cache(M4OSA_Context pContext,M4OSA_MemAddr8 pData,
                                                           M4OSA_UInt32* pSize)
{
    M4OSA_FileCache_Context* apContext = (M4OSA_FileCache_Context*) pContext;

    M4OSA_ERR err;
    M4OSA_FilePosition aSize;
    M4OSA_FilePosition copiedSize;
    M4OSA_Int8 selected_buffer, current_buffer;
    M4OSA_Int32 castedSize;

#ifdef M4OSA_FILE_CACHE_TIME_MEAS
    M4OSA_Time time1 = 0;
    M4OSA_Time time2 = 0;

    M4OSA_clockGetTime(&time1,1000);
#endif /* M4OSA_FILE_CACHE_TIME_MEAS */

    M4OSA_TRACE2_3("M4OSA_fileReadData_cache of %s size=%d at pos=%d  ",
                         apContext->m_filename, *pSize, apContext->absolutePos);

    /* Check input parameters */
    M4ERR_CHECK_NULL_RETURN_VALUE(M4ERR_BAD_CONTEXT, apContext);
    M4ERR_CHECK_NULL_RETURN_VALUE(M4ERR_PARAMETER, pData);
    M4ERR_CHECK_NULL_RETURN_VALUE(M4ERR_PARAMETER, pSize);

    if (apContext->IsOpened != M4OSA_TRUE)
    {
        return M4ERR_BAD_CONTEXT;
    }

LOCK

/* 20080125 Start : if *pSize is too high, adjust it to the size left in the file. MI-958*/
    castedSize = * pSize;
    if (castedSize < 0)
    {
        copiedSize = 0;
        err = M4WAR_NO_MORE_AU;
#ifdef M4OSA_FILECACHE_MM
        err = M4WAR_NO_DATA_YET; /* no_data_yet for MM */
#endif
        goto cleanup;
    }
/* 20080125 End : if *pSize is too high, adjust it to the size left in the file. MI-958*/

    /* Prevent reading beyond EOF */
    if((*pSize > 0) && (apContext->absolutePos >= apContext->virtualFileSize)) /* virtual FSize*/
    {
        copiedSize = 0;
        err = M4WAR_NO_MORE_AU; /* for VA and VPS */
#ifdef M4OSA_FILECACHE_MM
        err = M4WAR_NO_DATA_YET; /* no_data_yet for MM */
#endif
        goto cleanup;
    }

/* 20080125 Start : if *pSize is too high, adjust it to the size left in the file. MI-958*/
    if (*pSize > (M4OSA_UInt32)(apContext->virtualFileSize - apContext->absolutePos))
    {
        M4OSA_TRACE1_0("M4OSA_fileReadData_cache : Attempted to read beyond file size, adjusted size");
        *pSize = apContext->virtualFileSize - apContext->absolutePos;
    }
/* 20080125 End : if *pSize is too high, adjust it to the size left in the file. MI-958*/

    /* Check if data can be read from a buffer */
    /* If not, fill one according to quantized positions */
    copiedSize = 0;
    err = M4NO_ERROR;

    selected_buffer = M4OSA_FileCache_BufferMatchToRead(apContext,
                                                        apContext->absolutePos);

    if(selected_buffer == M4OSA_CACHEBUFFER_NONE)
    {

#if defined(BUFFER_SELECT_INITIAL)
        selected_buffer = M4OSA_FileCache_BufferSelectForRead(apContext);
#elif defined(BUFFER_SELECT_WITH_TIME)
        selected_buffer = M4OSA_FileCache_BufferSelectWithTime(apContext);
#elif defined(BUFFER_SELECT_WITH_SPACE)
        selected_buffer = M4OSA_FileCache_BufferSelectWithSpace(apContext);
#elif defined(BUFFER_SELECT_WITH_POS)
        selected_buffer = M4OSA_FileCache_BufferSelectWithPos(apContext);
#endif

        if (M4OSA_CACHEBUFFER_NONE == selected_buffer)
        {
            err = M4ERR_BAD_CONTEXT; /* temporary error code */
            goto cleanup;
        }

        err = M4OSA_FileCache_BufferFill(apContext, selected_buffer,
                                                        apContext->absolutePos);
    }
#ifdef FILECACHE_STATS
    else
    {
        /* bufferMatch has success in read  */
        apContext->nbReadCache++;
    }
#endif /* FILECACHE_STATS */

    if(err != M4NO_ERROR)
    {
        if((err == M4WAR_NO_DATA_YET) && (*pSize <= (M4OSA_UInt32)apContext->buffer[selected_buffer].size))
             err = M4NO_ERROR;
        else goto cleanup;
    }

    M4OSA_TRACE3_3("readData  size = %d  buffer = %d  pos = %d",
                               *pSize, selected_buffer, apContext->absolutePos);

    /* Copy buffer into pData */
    while(((M4OSA_UInt32)copiedSize < *pSize) && (err == M4NO_ERROR))
    {
        aSize = M4OSA_FileCache_BufferCopy(apContext, selected_buffer,
                                           apContext->absolutePos+copiedSize,
                                           *pSize-copiedSize, pData+copiedSize);
        copiedSize += aSize;

        if(aSize == 0)
        {
            err = M4WAR_NO_DATA_YET;
        }
        else
        {
            if((M4OSA_UInt32)copiedSize < *pSize)
            {
                current_buffer = selected_buffer;
                selected_buffer = M4OSA_FileCache_BufferMatchToRead(apContext,
                                             apContext->absolutePos+copiedSize);

                if(selected_buffer == M4OSA_CACHEBUFFER_NONE)
                {
#if defined(BUFFER_SELECT_INITIAL)
                    selected_buffer = M4OSA_FileCache_BufferSelectForRead(apContext);
#elif defined(BUFFER_SELECT_WITH_TIME)
                    selected_buffer = M4OSA_FileCache_BufferSelectWithTime(apContext);
#elif defined(BUFFER_SELECT_WITH_SPACE)
                    selected_buffer = M4OSA_FileCache_BufferSelectWithSpace(apContext);
#elif defined(BUFFER_SELECT_WITH_POS)
                    selected_buffer = M4OSA_FileCache_BufferSelectWithPos(apContext);
#endif

                    if (M4OSA_CACHEBUFFER_NONE == selected_buffer)
                    {
                        err = M4ERR_BAD_CONTEXT; /* temporary error code */
                        goto cleanup;
                    }

                    err = M4OSA_FileCache_BufferFill(apContext, selected_buffer,
                                             apContext->absolutePos+copiedSize);

                    if(err != M4NO_ERROR)
                    {
                        if((err == M4WAR_NO_DATA_YET) && ((*pSize-copiedSize) <= (M4OSA_UInt32)apContext->buffer[selected_buffer].size))
                             err = M4NO_ERROR;
                        else goto cleanup;
                    }
                }
#ifdef FILECACHE_STATS
                else
                {
                    /* bufferMatch has success in read  */
                    apContext->nbReadCache++;
                }
#endif /* FILECACHE_STATS */

            }
        }
    }

cleanup :

    /* Update the new position of the pointer */
    apContext->absolutePos = apContext->absolutePos + copiedSize;

#ifdef M4OSA_FILECACHE_MM
    apContext->absoluteWritePos = apContext->absolutePos;
#endif /* M4OSA_FILECACHE_MM */

    if(err != M4NO_ERROR)
    {
        M4OSA_TRACE1_3("M4OSA_fileReadData_cache size = %d  copied = %d  err = 0x%x",
                                                       *pSize, copiedSize, err);
    }

    /* Effective copied size must be returned */
    *pSize = copiedSize;

#ifdef M4OSA_FILE_CACHE_TIME_MEAS
    M4OSA_clockGetTime(&time2,1000);
    if (time2>time1)
        apContext->gMyPerfFileTab[fileReadDatatime] += time2-time1;
#endif /* M4OSA_FILE_CACHE_TIME_MEAS */

UNLOCK

    /* Read is done */
    return err;
}


/**
 ************************************************************************
 * @brief      This function writes the 'size' bytes stored at 'data' memory
 *             in the file selected by its context.
 * @note       The caller is responsible for allocating/de-allocating the
 *             memory for 'data' parameter.
 * @note       Moreover the data pointer must be allocated to store at least
 *             'size' bytes.
 * @param      pContext: (IN/OUT) Context of the core file reader
 * @param      pData: (IN) Data pointer of the write data
 * @param      size: (IN) Size of the data to write (in bytes)
 * @return     M4NO_ERROR: there is no error
 * @return     M4ERR_PARAMETER: at least one parameter is NULL
 * @return     M4ERR_BAD_CONTEXT: provided context is not a valid one
 * @return     M4ERR_ALLOC: there is no more memory available
 ************************************************************************/

M4OSA_ERR M4OSA_fileWriteData_cache(M4OSA_Context pContext,M4OSA_MemAddr8 pData,
                                                              M4OSA_UInt32 size)
{
    M4OSA_FileCache_Context* apContext = (M4OSA_FileCache_Context*) pContext;

    M4OSA_ERR err;
    M4OSA_FilePosition aSize;
    M4OSA_FilePosition copiedSize;
    M4OSA_Int8 selected_buffer, current_buffer;

#ifdef M4OSA_FILE_CACHE_TIME_MEAS
    M4OSA_Time time1 = 0;
    M4OSA_Time time2 = 0;

    M4OSA_clockGetTime(&time1,1000);
#endif /* M4OSA_FILE_CACHE_TIME_MEAS */

    M4OSA_TRACE2_3("M4OSA_fileWriteData_cache of %s size=%d at pos=%d   ",
                      apContext->m_filename, size, apContext->absoluteWritePos);

    /* Check input parameters */
    M4ERR_CHECK_NULL_RETURN_VALUE(M4ERR_BAD_CONTEXT, apContext);
    M4ERR_CHECK_NULL_RETURN_VALUE(M4ERR_PARAMETER, pData);


    if (apContext->IsOpened != M4OSA_TRUE)
    {
        return M4ERR_BAD_CONTEXT;
    }

    /*protection*/
    if (apContext->absoluteWritePos > apContext->virtualFileSize)
    {
        M4OSA_TRACE1_0("M4OSA_fileWriteData_cache ERROR : attempting to write beyond EOF");
        return M4WAR_NO_DATA_YET;
    }

LOCK

    /* Check if data has been read into a buffer */
    /* If not, we should read that buffer first and then fill it */
    copiedSize = 0;
    err = M4NO_ERROR;

    selected_buffer = M4OSA_FileCache_BufferMatchToWrite(apContext,
                                                   apContext->absoluteWritePos);

    if(selected_buffer == M4OSA_CACHEBUFFER_NONE)
    {
#if defined(BUFFER_SELECT_INITIAL)
        selected_buffer = M4OSA_FileCache_BufferSelectForWrite(apContext);
#elif defined(BUFFER_SELECT_WITH_TIME)
        selected_buffer = M4OSA_FileCache_BufferSelectWithTime(apContext);
#elif defined(BUFFER_SELECT_WITH_SPACE)
        selected_buffer = M4OSA_FileCache_BufferSelectWithSpace(apContext);
#elif defined(BUFFER_SELECT_WITH_POS)
        selected_buffer = M4OSA_FileCache_BufferSelectWithPos(apContext);
#endif

        if (M4OSA_CACHEBUFFER_NONE == selected_buffer)
        {
            M4OSA_TRACE1_1("M4OSA_fileWriteData_cache ERR1 err=0x%x", err);
            err = M4ERR_BAD_CONTEXT; /* temporary error code */
            goto cleanup;
        }

        if (apContext->absoluteWritePos - M4OSA_CACHEBUFFER_SIZE < apContext->fileSize) /* absolutePos not readfilepo strictly < */
        {
            err = M4OSA_FileCache_BufferFill(apContext, selected_buffer,
                                                   apContext->absoluteWritePos);
        }
        else
        {
            err = M4OSA_FileCache_BufferReinitialize(apContext, selected_buffer,
                                                   apContext->absoluteWritePos);
        }

    }
#ifdef FILECACHE_STATS
    else
    {
        /* bufferMatch has success in write */
        apContext->nbWriteCache++;
    }
#endif /* FILECACHE_STATS */

    if(err != M4NO_ERROR)
    {
        if(err == M4WAR_NO_DATA_YET) /* means the buffer is small, it is at EOF, bufferFill didn't fully fill it*/
             err = M4NO_ERROR;
        else goto cleanup;
    }

    M4OSA_TRACE3_3("writeData  size = %d  buffer = %d  pos = %d", size,
                                  selected_buffer, apContext->absoluteWritePos);

    /* Copy buffer into pData */
    while(((M4OSA_UInt32)copiedSize < size) && (err == M4NO_ERROR))
    {
        aSize = M4OSA_FileCache_BufferModifyContent(apContext, selected_buffer,
                                                    apContext->absoluteWritePos+copiedSize,
                                                    size-copiedSize, pData+copiedSize);
        copiedSize += aSize;

        /* update virtualFileSize in case we write at the end  */
        if (apContext->absoluteWritePos+copiedSize>apContext->virtualFileSize)
        {
            apContext->virtualFileSize = apContext->absoluteWritePos+copiedSize;
            M4OSA_TRACE3_1("virtualFileSize incremented to %d", apContext->virtualFileSize);
        }

        if((M4OSA_UInt32)copiedSize < size)
        {
            current_buffer = selected_buffer;
            selected_buffer = M4OSA_FileCache_BufferMatchToWrite(apContext,
                                        apContext->absoluteWritePos+copiedSize);

            if(selected_buffer == M4OSA_CACHEBUFFER_NONE)
            {
#if defined(BUFFER_SELECT_INITIAL)
                selected_buffer = M4OSA_FileCache_BufferSelectForWrite(apContext);
#elif defined(BUFFER_SELECT_WITH_TIME)
                selected_buffer = M4OSA_FileCache_BufferSelectWithTime(apContext);
#elif defined(BUFFER_SELECT_WITH_SPACE)
                selected_buffer = M4OSA_FileCache_BufferSelectWithSpace(apContext);
#elif defined(BUFFER_SELECT_WITH_POS)
                selected_buffer = M4OSA_FileCache_BufferSelectWithPos(apContext);
#endif

                if (M4OSA_CACHEBUFFER_NONE == selected_buffer)
                {
                    M4OSA_TRACE1_1("M4OSA_fileWriteData_cache ERR2 err=0x%x", err);
                    err = M4ERR_BAD_CONTEXT; /* temporary error code */
                    goto cleanup;
                }

                if (apContext->absoluteWritePos+copiedSize < apContext->fileSize) /* absolutePos not readfilepo strictly < */
                {
                    err = M4OSA_FileCache_BufferFill(apContext, selected_buffer,
                                        apContext->absoluteWritePos+copiedSize);
                }
                else
                {
                    err = M4OSA_FileCache_BufferReinitialize(apContext,
                                                             selected_buffer,
                                                             apContext->absoluteWritePos+copiedSize);
                }


                if(err != M4NO_ERROR)
                {
                    if((err == M4WAR_NO_DATA_YET))
                         err = M4NO_ERROR;
                    else goto cleanup;
                }
            }
#ifdef FILECACHE_STATS
    else  /* (selected_buffer == M4OSA_CACHEBUFFER_NONE) */
    {
        /* bufferMatch has success in write */
        apContext->nbWriteCache++;
    }
#endif /* FILECACHE_STATS */

        }

    }

cleanup :

    /* Update the new position of the pointer */
    apContext->absoluteWritePos = apContext->absoluteWritePos + copiedSize;
#ifdef M4OSA_FILECACHE_MM
    apContext->absolutePos = apContext->absoluteWritePos;
#endif /* M4OSA_FILECACHE_MM */

    if(err != M4NO_ERROR)
    {
        M4OSA_TRACE3_3("M4OSA_fileWriteData_cache size = %d  copied = %d  err = 0x%x",
                                                         size, copiedSize, err);
    }

    /* Effective copied size must be returned */
    size = copiedSize;

#ifdef M4OSA_FILE_CACHE_TIME_MEAS
    M4OSA_clockGetTime(&time2,1000);
    if (time2>time1)
        apContext->gMyPerfFileTab[fileWriteDatatime] += time2-time1;
#endif /* M4OSA_FILE_CACHE_TIME_MEAS */

UNLOCK

    /* Read is done */
    return err;
}


/**
******************************************************************************
* @brief       This method seeks at the provided position in the core file reader (selected by its 'context').
*              The position is related to the seekMode parameter it can be either :
*              From the beginning (position MUST be positive) : end position = position
*              From the end (position MUST be negative) : end position = file size + position
*              From the current position (signed offset) : end position = current position + position.
* @param       pContext:       (IN) File reader context.
* @param       SeekMode :      (IN) Seek access mode.
* @param       pPosition :     (IN) Position in the file.
* @return      M4NO_ERROR: there is no error
* @return      M4ERR_PARAMETER Seekmode or fileDescriptor is NULL
* @return      M4ERR_ALLOC     there is no more memory available
* @return      M4ERR_BAD_CONTEXT       provided context is not a valid one.
* @return      M4ERR_FILE_INVALID_POSITION the position cannot be reached.
******************************************************************************
*/
M4OSA_ERR M4OSA_fileReadSeek_cache( M4OSA_Context pContext,
                                    M4OSA_FileSeekAccessMode SeekMode,
                                    M4OSA_FilePosition* pPosition)
{
    M4OSA_FileCache_Context* apContext = (M4OSA_FileCache_Context*) pContext;
    M4OSA_ERR err = M4NO_ERROR;
    M4OSA_FilePosition finalPos;

#ifdef M4OSA_FILE_CACHE_TIME_MEAS
    M4OSA_Time time1 = 0;
    M4OSA_Time time2 = 0;

    M4OSA_clockGetTime(&time1,1000);
#endif /* M4OSA_FILE_CACHE_TIME_MEAS */

    M4OSA_TRACE3_2("M4OSA_fileReadSeek_cache mode = %d pos = %d", SeekMode, *pPosition);

    /* Check input parameters */
    M4ERR_CHECK_NULL_RETURN_VALUE(M4ERR_BAD_CONTEXT, apContext);
    M4ERR_CHECK_NULL_RETURN_VALUE(M4ERR_PARAMETER, pPosition);
    M4ERR_CHECK_NULL_RETURN_VALUE(M4ERR_PARAMETER, SeekMode);

    if (apContext->IsOpened != M4OSA_TRUE)
    {
        return M4ERR_BAD_CONTEXT;       /*< The context can not be correct */
    }

LOCK

    /* Go to the desired position */
    switch(SeekMode)
    {
        case M4OSA_kFileSeekBeginning :
            finalPos = *pPosition;
            break;

        case M4OSA_kFileSeekEnd :
            finalPos = apContext->virtualFileSize + *pPosition;
            break;

        case M4OSA_kFileSeekCurrent :
            finalPos = apContext->absolutePos + *pPosition;
            break;

        default :
            UNLOCK
            return M4ERR_PARAMETER; /**< Bad SeekAcess mode */
            break;
    }

    M4OSA_TRACE2_1("M4OSA_fileReadSeek_cache to absolutePos = %d ", finalPos);

/* 20080125 Start : Protect against seek outside file. MI-958*/
    if (finalPos <= apContext->virtualFileSize && finalPos>=0)
    {
        apContext->absolutePos = finalPos;
        *pPosition = finalPos;
    }
    else
    {
        M4OSA_TRACE1_2("M4OSA_fileReadSeek_cache: attempted to seek at %d whilst filesize=%d",
                                          finalPos, apContext->virtualFileSize);
        *pPosition = apContext->absolutePos;    /* keep the previous position */
        //err = M4ERR_FILE_INVALID_POSITION;
        err = M4NO_ERROR;  /* for VA */
    }
/* 20080125 End : Protect against seek outside file. MI-958*/

#ifdef M4OSA_FILECACHE_MM
        apContext->absoluteWritePos = apContext->absolutePos;
#endif /* M4OSA_FILECACHE_MM */

#ifdef M4OSA_FILE_CACHE_TIME_MEAS
    M4OSA_clockGetTime(&time2,1000);
    if (time2>time1)
        apContext->gMyPerfFileTab[fileSeektime] += time2-time1;
#endif /* M4OSA_FILE_CACHE_TIME_MEAS */

UNLOCK

    /* Return without error */
    return err;
}


/**
******************************************************************************
* @brief       This method seeks at the provided position in the core file reader (selected by its 'context').
*              The position is related to the seekMode parameter it can be either :
*              From the beginning (position MUST be positive) : end position = position
*              From the end (position MUST be negative) : end position = file size + position
*              From the current position (signed offset) : end position = current position + position.
* @param       pContext:       (IN) File reader context.
* @param       SeekMode :      (IN) Seek access mode.
* @param       pPosition :     (IN) Position in the file.
* @return      M4NO_ERROR: there is no error
* @return      M4ERR_PARAMETER Seekmode or fileDescriptor is NULL
* @return      M4ERR_ALLOC     there is no more memory available
* @return      M4ERR_BAD_CONTEXT       provided context is not a valid one.
* @return      M4ERR_FILE_INVALID_POSITION the position cannot be reached.
******************************************************************************
*/
M4OSA_ERR M4OSA_fileWriteSeek_cache( M4OSA_Context pContext,
                                     M4OSA_FileSeekAccessMode SeekMode,
                                     M4OSA_FilePosition* pPosition)
{
    M4OSA_FileCache_Context* apContext = (M4OSA_FileCache_Context*) pContext;
    M4OSA_ERR err = M4NO_ERROR;
    M4OSA_FilePosition finalPos;

#ifdef M4OSA_FILE_CACHE_TIME_MEAS
    M4OSA_Time time1 = 0;
    M4OSA_Time time2 = 0;

    M4OSA_clockGetTime(&time1,1000);
#endif /* M4OSA_FILE_CACHE_TIME_MEAS */

    M4OSA_TRACE3_2("M4OSA_fileWriteSeek_cache mode = %d pos = %d", SeekMode, *pPosition);

    /* Check input parameters */
    M4ERR_CHECK_NULL_RETURN_VALUE(M4ERR_BAD_CONTEXT, apContext);
    M4ERR_CHECK_NULL_RETURN_VALUE(M4ERR_PARAMETER, pPosition);
    M4ERR_CHECK_NULL_RETURN_VALUE(M4ERR_PARAMETER, SeekMode);

    if (apContext->IsOpened != M4OSA_TRUE)
    {
        return M4ERR_BAD_CONTEXT;       /*< The context can not be correct */
    }

LOCK

    /* Go to the desired position */
    switch(SeekMode)
    {
        case M4OSA_kFileSeekBeginning :
            finalPos = *pPosition;
            break;

        case M4OSA_kFileSeekEnd :
            finalPos = apContext->virtualFileSize + *pPosition;
            break;

        case M4OSA_kFileSeekCurrent :
            finalPos = apContext->absoluteWritePos + *pPosition;
            break;

        default :
            UNLOCK
            return M4ERR_PARAMETER; /**< Bad SeekAcess mode */
            break;
    }

    M4OSA_TRACE2_1("M4OSA_fileWriteSeek_cache to absoluteWritePos = %d ", finalPos);

/* 20080125 Start : Protect against seek outside file. MI-958*/
    if (finalPos <= apContext->virtualFileSize && finalPos>=0)
    {
        apContext->absoluteWritePos = finalPos;
        *pPosition = finalPos;
    }
    else
    {
        M4OSA_TRACE1_2("M4OSA_fileWriteSeek_cache: attempted to seek at %d whilst filesize=%d     ",
                                          finalPos, apContext->virtualFileSize);
        *pPosition = apContext->absoluteWritePos;    /* keep the previous position */
        //err = M4ERR_FILE_INVALID_POSITION;
        err = M4NO_ERROR;  /* for VA */
    }
/* 20080125 End : Protect against seek outside file. MI-958*/

#ifdef M4OSA_FILECACHE_MM
    apContext->absolutePos = apContext->absoluteWritePos;
#endif /* M4OSA_FILECACHE_MM */

#ifdef M4OSA_FILE_CACHE_TIME_MEAS
    M4OSA_clockGetTime(&time2,1000);
    if (time2>time1)
        apContext->gMyPerfFileTab[fileSeektime] += time2-time1;
#endif /* M4OSA_FILE_CACHE_TIME_MEAS */

UNLOCK

    /* Return without error */
    return err;
}

M4OSA_ERR M4OSA_fileFlush_cache( M4OSA_Context pContext)
{
    /* Do nothing, M4OSA_fileCache module manages its caches by itself */

    return M4NO_ERROR;
}
/**
******************************************************************************
* @brief       This method asks the core file reader to close the file (associated to the context).
* @param       pContext:       (IN) File reader context.
* @return      M4NO_ERROR: there is no error
* @return      M4ERR_BAD_CONTEXT       provided context is not a valid one.
******************************************************************************
*/
M4OSA_ERR M4OSA_fileClose_cache(M4OSA_Context pContext)
{
    M4OSA_FileCache_Context* apContext = (M4OSA_FileCache_Context*) pContext;

    M4OSA_ERR err = M4NO_ERROR;
    M4OSA_Int32 aRet_Val = 0;
    M4OSA_UInt16 errReturned = 0;


#ifdef M4OSA_FILE_CACHE_TIME_MEAS
    M4OSA_Time time1 = 0;
    M4OSA_Time time2 = 0;

    M4OSA_clockGetTime(&time1,1000);
#endif /* M4OSA_FILE_CACHE_TIME_MEAS */

    M4OSA_TRACE2_1("M4OSA_fileClose_cache pC = 0x%x", pContext);

    /* Check input parameters */
    M4ERR_CHECK_NULL_RETURN_VALUE(M4ERR_BAD_CONTEXT, apContext);

    if (apContext->IsOpened != M4OSA_TRUE)
    {
        return M4ERR_BAD_CONTEXT;       /**< The context can not be correct */
    }

LOCK

#ifdef BUFFER_DISPLAY
    M4OSA_FileCache_BufferDisplay(apContext);
#endif

    M4OSA_FileCache_BuffersFlushUntil(apContext, M4OSA_CACHEBUFFER_ALL);

    /* buffer */
    M4OSA_FileCache_BuffersFree(apContext);

    /* Close the file */
    aRet_Val = apContext->FS->pFctPtr_Close(apContext->aFileDesc, &errReturned);

    if (aRet_Val != 0)
    {
        /* converts the error to PSW format*/
        err = M4OSA_ERR_CREATE(M4_ERR, M4OSA_FILE_READER, errReturned);
        M4OSA_TRACE1_1("M4OSA_fileClose_cache ERR1 = 0x%x", err);
    }
    apContext->IsOpened = M4OSA_FALSE;

    /* Free the context */
    M4OSA_free((M4OSA_MemAddr32)apContext->FS);
    M4OSA_free((M4OSA_MemAddr32)apContext->aFileDesc);

#ifdef FILECACHE_STATS
{
    M4OSA_Int32 successRateRead, successRateWrite;

    successRateRead= (apContext->nbReadFFS + apContext->nbReadCache ==0)? (-1) : (apContext->nbReadCache)*100 / (apContext->nbReadCache + apContext->nbReadFFS);

    successRateWrite = (apContext->nbWriteFFS + apContext->nbWriteCache == 0)? (-1) : (apContext->nbWriteCache)*100 / (apContext->nbWriteCache + apContext->nbWriteFFS);

#if defined(BUFFER_SELECT_INITIAL)
    M4OSA_TRACE1_0("BUFFER_SELECT_INITIAL");
#elif defined(BUFFER_SELECT_WITH_TIME)
    M4OSA_TRACE1_0("BUFFER_SELECT_WITH_TIME");
#elif defined(BUFFER_SELECT_WITH_SPACE)
    M4OSA_TRACE1_0("BUFFER_SELECT_WITH_SPACE");
#elif defined(BUFFER_SELECT_WITH_POS)
    M4OSA_TRACE1_0("BUFFER_SELECT_WITH_POS");
#endif

    M4OSA_TRACE1_1("Osal File Cache Stats for %s", apContext->m_filename);
    M4OSA_TRACE1_2("FILECACHE_STATS: nbReadCache=%d / nbReadFFS=%d",
                                  apContext->nbReadCache, apContext->nbReadFFS);
    M4OSA_TRACE1_2("FILECACHE_STATS: nbWriteCache=%d / nbWriteFFS=%d",
                                apContext->nbWriteCache, apContext->nbWriteFFS);
    M4OSA_TRACE1_2("FILECACHE_STATS: Success in reading : %d percent - Success in writing %d percent",
                                             successRateRead, successRateWrite);
    M4OSA_TRACE1_0("---------------------------------------------------------");
}
#endif /* FILECACHE_STATS */

    UNLOCK

    if (apContext->m_mutex != M4OSA_NULL)
    {
        M4OSA_mutexClose(apContext->m_mutex);
        apContext->m_mutex = M4OSA_NULL;
    }

#ifdef M4OSA_FILE_CACHE_TIME_MEAS
        M4OSA_clockGetTime(&time2,1000);
        if (time2>time1)
            apContext->gMyPerfFileTab[fileClosetime] += time2-time1;

        M4OSA_FileCache_displayTimeMeas(apContext);
#endif /* M4OSA_FILE_CACHE_TIME_MEAS */

    M4OSA_memset((M4OSA_MemAddr8)apContext, sizeof(M4OSA_FileCache_Context), 0);

    M4OSA_free((M4OSA_MemAddr32)apContext);

    M4OSA_TRACE2_1("M4OSA_fileClose_cache leaving with err = 0x%x", err);

    /* Return without error */
    return err;
}

/**
******************************************************************************
* @brief       This method asks the core file reader to set the value associated with the optionID.
*                      The caller is responsible for allocating/de-allocating the memory of the value field.
* @note        The options handled by the component depend on the implementation of the component.
* @param       pContext:       (IN) Execution context.
* @param       OptionId :      (IN) Id of the option to set.
* @param       OptionValue :   (IN) Value of the option.
* @return      M4NO_ERROR: there is no error
* @return      M4ERR_BAD_CONTEXT       pContext is NULL
* @return      M4ERR_BAD_OPTION_ID the option id is not valid.
* @return      M4ERR_NOT_IMPLEMENTED The option is not implemented yet.
******************************************************************************
*/
M4OSA_ERR M4OSA_fileSetOption_cache(M4OSA_Context pContext,
                                    M4OSA_OptionID OptionID,
                                    M4OSA_DataOption OptionValue)
{
    M4OSA_FileCache_Context* apContext = (M4OSA_FileCache_Context*) pContext;

#ifdef M4OSA_FILE_CACHE_TIME_MEAS
    M4OSA_Time time1 = 0;
    M4OSA_Time time2 = 0;

    M4OSA_clockGetTime(&time1,1000);
#endif /* M4OSA_FILE_CACHE_TIME_MEAS */

    /* Check input parameters */
    M4ERR_CHECK_NULL_RETURN_VALUE(M4ERR_BAD_CONTEXT, apContext);

    if (apContext->IsOpened != M4OSA_TRUE)
    {
        return M4ERR_BAD_CONTEXT;       /**< The context can not be correct */
    }

    /* Set the desired option if it is avalaible */
    switch(OptionID)
    {
        case M4OSA_kFileReadGetFileSize :       /**< Get size of the file, limited to 32 bit size */
        case M4OSA_kFileReadGetFileAttribute :  /**< Get the file attribute*/
        case M4OSA_kFileReadGetURL :            /**< Get the directory + name of the file */
        case M4OSA_kFileReadIsEOF :             /**< See if we are at the end of the file */
        case M4OSA_kFileReadGetFilePosition :   /**< Get file position */
            return M4ERR_READ_ONLY;
            break;

        case M4OSA_kFileWriteDescMode:
            return M4NO_ERROR;                    /* for MM */

        default :                               /**< Bad option ID */
            return M4ERR_BAD_OPTION_ID;
            break;
    }

#ifdef M4OSA_FILE_CACHE_TIME_MEAS
    M4OSA_clockGetTime(&time2,1000);
    if (time2>time1)
        apContext->gMyPerfFileTab[fileSetOptiontime] += time2-time1;
#endif /* M4OSA_FILE_CACHE_TIME_MEAS */

    /* Return without error */
    return M4NO_ERROR;
}

/**
******************************************************************************
* @brief       This method asks the core file reader to return the value associated with the optionID.
*                      The caller is responsible for allocating/de-allocating the memory of the value field.
* @note        The options handled by the component depend on the implementation of the component.
* @param       pContext:       (IN) Execution context.
* @param       OptionId :      (IN) Id of the option to set.
* @param       pOptionValue :  (OUT) Value of the option.
* @return      M4NO_ERROR: there is no error
* @return      M4ERR_BAD_CONTEXT       pContext is NULL
* @return      M4ERR_BAD_OPTION_ID the option id is not valid.
* @return      M4ERR_NOT_IMPLEMENTED The option is not implemented yet.
******************************************************************************
*/
M4OSA_ERR M4OSA_fileGetOption_cache(M4OSA_Context pContext,
                                    M4OSA_OptionID OptionID,
                                    M4OSA_DataOption* pOptionValue)
{
    M4OSA_FileCache_Context* apContext = (M4OSA_FileCache_Context*) pContext;
    M4OSA_ERR err = M4NO_ERROR;
    M4OSA_Bool isEof;

#ifdef M4OSA_FILE_CACHE_TIME_MEAS
    M4OSA_Time time1 = 0;
    M4OSA_Time time2 = 0;

    M4OSA_clockGetTime(&time1,1000);
#endif /* M4OSA_FILE_CACHE_TIME_MEAS */


    /*  Check input parameters */
    M4ERR_CHECK_NULL_RETURN_VALUE(M4ERR_BAD_CONTEXT, apContext);

    if (apContext->IsOpened != M4OSA_TRUE)
    {
        return M4ERR_BAD_CONTEXT;       /**< The context can not be correct */
    }

LOCK

    /* Get the desired option if it is avalaible */
    switch(OptionID)
    {
        /* Get File Size */
        case M4OSA_kFileReadGetFileSize:/**< Get size of the file, limited to 32 bit size */
            M4OSA_TRACE2_1("M4OSA_fileGetOption_cache ReadGetFileSize return filesize = %d ",
                                                    apContext->virtualFileSize);
            (*(M4OSA_UInt32 *)pOptionValue) = apContext->virtualFileSize; /* return virtual */
            break;


        case M4OSA_kFileWriteGetFileSize:/**< Get size of the file, limited to 32 bit size */
            M4OSA_TRACE2_1("M4OSA_fileGetOption_cache WriteGetFileSize return filesize = %d ",
                                                    apContext->virtualFileSize);
            (*(M4OSA_UInt32 *)pOptionValue) = apContext->virtualFileSize; /* return virtual */
            break;

        /* Check End of file Occurs */
        case M4OSA_kFileReadIsEOF :     /**< See if we are at the end of the file */
            isEof = (apContext->absolutePos >= apContext->virtualFileSize) ? M4OSA_TRUE : M4OSA_FALSE; /* virtual */
            (*(M4OSA_Bool *)pOptionValue) = isEof;
            M4OSA_TRACE2_1("M4OSA_fileGetOption_cache ReadIsEOF return isEof=%d ",
                                                                         isEof);
            break;

        /* Get File Position */
        case M4OSA_kFileReadGetFilePosition :   /**< Get file position */
            M4OSA_TRACE2_1("M4OSA_fileGetOption_cache ReadGetFilePosition return rpos=%d ",
                                                        apContext->absolutePos);
            *(M4OSA_FilePosition *)pOptionValue = apContext->absolutePos;
            break;

        /* Get File Position */
        case M4OSA_kFileWriteGetFilePosition :    /**< Get file position */
            M4OSA_TRACE2_1("M4OSA_fileGetOption_cache WriteGetFilePosition return wpos=%d ",
                                                   apContext->absoluteWritePos);
            *(M4OSA_FilePosition *)pOptionValue = apContext->absoluteWritePos;
            break;

        /* Get Attribute */
        case M4OSA_kFileReadGetFileAttribute :  /**< Get the file attribute = access mode */
            M4OSA_TRACE2_1("M4OSA_fileGetOption_cache ReadGetFileAttribute return mode=%d ",
                                           apContext->FileAttribute.modeAccess);
            (*(M4OSA_FileAttribute *)pOptionValue).modeAccess = apContext->FileAttribute.modeAccess;
            break;
   /** Get the reader context for read & write file. (M4OSA_Context*)*/
        case M4OSA_kFileWriteGetReaderContext:
            M4OSA_TRACE2_1("M4OSA_fileGetOption_cache WriteGetReaderContext return c=0x%x ",
                                                                     apContext);
            (*(M4OSA_Context *)pOptionValue) = apContext;
            break;
        default:
            /**< Bad option ID */
            UNLOCK
            return  M4ERR_BAD_OPTION_ID;
            break;
    }

#ifdef M4OSA_FILE_CACHE_TIME_MEAS
    M4OSA_clockGetTime(&time2,1000);
    if (time2>time1)
        apContext->gMyPerfFileTab[fileGetOptiontime] += time2-time1;
#endif /* M4OSA_FILE_CACHE_TIME_MEAS */

    UNLOCK


    /*Return without error */
    return err;
}

/* For VA */
M4OSA_ERR M4OSA_fileExtrafTruncate_cache(M4OSA_Context context, M4OSA_UInt32 length)
{
    M4OSA_ERR err = M4NO_ERROR;
    M4OSA_UInt16 result = M4OSA_FALSE;
    M4OSA_FileCache_Context* apContext = context;


    FILE* filedesc1 = ((M4OSA_FileSystem_FFS_t_cache*) ( apContext->aFileDesc))->FileDesc;

    result = ftruncate(filedesc1->_file, length);

    if(result != 0)
    {
        err = errno;
        M4OSA_TRACE1_1("SetEndOfFile returns err: 0x%x\n", err);
        return M4OSA_ERR_CREATE(M4_ERR, M4OSA_FILE_EXTRA, err);
    }
    return M4NO_ERROR;
}
#ifdef M4OSA_FILE_CACHE_TIME_MEAS

/**************************************************************/
void M4OSA_FileCache_initTimeMeas(M4OSA_Context pContext)
/**************************************************************/
{
    M4OSA_FileCache_Context* apContext = (M4OSA_FileCache_Context*) pContext;
    M4OSA_Time time1 = 0;

    memset(apContext->gMyPerfFileTab, 0, sizeof(apContext->gMyPerfFileTab)); //Reset perf measurement array

    M4OSA_clockGetTime(&time1,1000);
    apContext->gMyPerfFileTab[enum_size] = time1;         //to compute total application time

}

/**************************************************************/
void M4OSA_FileCache_displayTimeMeas(M4OSA_Context pContext)
/**************************************************************/
{
    M4OSA_FileCache_Context* apContext = (M4OSA_FileCache_Context*) pContext;

    M4OSA_Time globalfileperfmeas = 0;
    M4OSA_Time time2 = 0;
    M4OSA_UInt32 i=0;

    M4OSA_clockGetTime(&time2,1000);

    /* Time spent in application */
    time2 = time2-apContext->gMyPerfFileTab[enum_size];

    /* Time spent in File System procedures */
    for (i=0; i<enum_size; i++)
        globalfileperfmeas += apContext->gMyPerfFileTab[i];

    M4OSA_TRACE1_1("Osal File Cache Time measurement for %s ",
                                                         apContext->m_filename);
    M4OSA_TRACE1_2("Application time =%d, fileCache total time =%d",
                                               (M4OSA_Int32)time2,
                                               (M4OSA_Int32)globalfileperfmeas);
    M4OSA_TRACE1_4("Opentime:%d, ReadDatatime:%d, WriteDatatime: %d, Seektime:%d",
                  (M4OSA_Int32)apContext->gMyPerfFileTab[fileOpentime] ,
                  (M4OSA_Int32)apContext->gMyPerfFileTab[fileReadDatatime] ,
                  (M4OSA_Int32)apContext->gMyPerfFileTab[fileWriteDatatime] ,
                  (M4OSA_Int32)apContext->gMyPerfFileTab[fileSeektime] );
    M4OSA_TRACE1_4("GetOptiontime:%d, SetOptiontime:%d, ExternalFlush: %d, Closetime: %d",
                  (M4OSA_Int32)apContext->gMyPerfFileTab[fileGetOptiontime] ,
                  (M4OSA_Int32)apContext->gMyPerfFileTab[fileSetOptiontime],
                  (M4OSA_Int32)apContext->gMyPerfFileTab[fileExternalFlushtime],
                  (M4OSA_Int32)apContext->gMyPerfFileTab[fileClosetime]);
    M4OSA_TRACE1_0("--------------------------------------------------------------------");
}

#endif /* M4OSA_FILE_INTERFACE_MM_TIME_MEAS */