summaryrefslogtreecommitdiffstats
path: root/src/messaging/qfsengine_symbian.cpp
blob: 719010bc6f40dc96c7697b303239de1d75011e7a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qmessageservice.h"
#include "qmessageservice_symbian_p.h"
#include "qfsengine_symbian_p.h"
#include "qmessage_symbian_p.h"
#include "messagingutil_p.h"
#include "qmessageaccount.h"
#include "qmessageaccount_p.h"
#include "qmessageaccountfilter.h"
#include "qmessageaccountfilter_p.h"
#include "qmessagecontentcontainer_symbian_p.h"
#include "qmessagefolder.h"
#include "qmessagefolder_p.h"
#include "qmessagefolderfilter.h"
#include "qmessagefolderfilter_p.h"
#include "qmessageaccountsortorder_p.h"
#include "qmessagestore_symbian_p.h"
#include "qmessagefoldersortorder_p.h"
#include "qmessagesortorder_p.h"

#include <emailinterfacefactory.h>
#include <QTextCodec>
#include <emailapidefs.h>
#include <memailmailbox.h>
#include <memailfolder.h>
#include <memailmessage.h>
#include <memailaddress.h>
#include <memailcontent.h>
#include <mmessageiterator.h>

#include <QThreadStorage>
#include <QCoreApplication>
#include <QDesktopServices>

using namespace EmailInterface;

QTM_BEGIN_NAMESPACE

using namespace SymbianHelpers;

Q_GLOBAL_STATIC(CFSEngine, applicationThreadFsEngine);
Q_GLOBAL_STATIC(QThreadStorage<CFSEngine *>, fsEngineThreadStorage)

/**
 * Generic error mapper. Maps Symbian error code to QMessageManager::Error.
 */
#ifdef FREESTYLEMAILMAPI12USED
static QMessageManager::Error symbianToMessageManagerError( TInt aError )
{
    QMessageManager::Error error = QMessageManager::RequestIncomplete;
    switch( aError ) {
        case KErrNone: {
            error = QMessageManager::NoError;
            break;
        }
        case KErrArgument: {
            error = QMessageManager::InvalidId;
            break;
        }
        case KErrNotFound:
        case KErrCouldNotConnect: {
            error = QMessageManager::ContentInaccessible;
            break;
        }
        case KErrNoMemory: {
            error = QMessageManager::WorkingMemoryOverflow;
            break;
        }
        case KErrNotSupported: {
            error = QMessageManager::NotYetImplemented;
            break;
        }
        case KErrServerBusy: 
        case KErrInUse: {
            error = QMessageManager::Busy;
            break;
        }
        default: {
            break;
        }
    }
    return error;
}
#endif

CFSEngine::CFSEngine()
 : m_messageQueryActive(false), 
   m_cleanedup(false)
#ifdef FREESTYLEMAILMAPI12USED
   ,m_mailboxMoveRequestId(0)
   ,m_messageStorePrivateSingleton(0)
#endif
{
    m_factory = 0;
    m_ifPtr = 0;
    ipMessageStorePrivate = 0;
    iListenForNotifications = false;
    TRAPD(err, {
        m_factory = CEmailInterfaceFactory::NewL();
        m_ifPtr = m_factory->InterfaceL(KEmailClientApiInterface);
    } );

    // Check that getting email api interface was successful.
    // Otherwise throwing exception.
    if( err != KErrNone ) {
        if( m_factory ) {
            delete m_factory;
            m_factory = 0;
        }
        // This is always throwing
        qt_symbian_throwIfError(err);
    }

    m_clientApi = q_check_ptr( static_cast<MEmailClientApi*>(m_ifPtr) );

    if (QCoreApplication::instance() && QCoreApplication::instance()->thread() == QThread::currentThread()) {
        // Make sure that application/main thread specific FsEngine will be cleaned up
        // when application event loop quits
        connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), this, SLOT(cleanupFSBackend()));

        // If application event loop is not running, aboutToQuit() won't be called
        // => Use qAddPostRoutine to make sure that FsEngine will be correctly
        //    cleaned up when QApplication is destroyed
        qAddPostRoutine(CFSEngine::cleanup);
    }

    if (QCoreApplication::instance() && QCoreApplication::instance()->thread() == QThread::currentThread()) {
        TRAP_IGNORE(setPluginObserversL());
    }
}

CFSEngine::~CFSEngine()
{
    cleanupFSBackend();
}

void CFSEngine::cleanup()
{
    if (QCoreApplication::instance() && QCoreApplication::instance()->thread() == QThread::currentThread()) {
        CFSEngine* pEngine = applicationThreadFsEngine();
        pEngine->cleanupFSBackend();
    }
}

void CFSEngine::cleanupFSBackend()
{
    for (TInt i = 0; i < m_attachments.Count(); i++){
        m_attachments[i]->Release();
    }
    m_attachments.Reset();

    foreach (CFSContentFetchOperation* operation, m_contentFetchOperations) {
        delete operation;
    }
    m_contentFetchOperations.clear();

#ifdef FREESTYLEMAILMAPI12USED
    foreach (CFSContentStructureFetchOperation* operation, m_contentStructurefetchOperations) {
        delete operation;
    }
    m_contentStructurefetchOperations.clear();

    m_moveRequests.clear();
#endif

    foreach (MEmailMailbox* value, m_mailboxes) {
        if (value) {
        value->Release();
        }
    }
    m_mailboxes.clear();

    if (m_clientApi) {
        m_clientApi->Release();
        m_clientApi = NULL;
    }

    foreach (EMailSyncRequest* req, m_syncRequests) {
        delete req;
    }
    m_syncRequests.clear();
    
    if (m_factory) {
        delete m_factory;
        m_factory = NULL;
    }
}

CFSEngine* CFSEngine::instance()
{   
    if (QCoreApplication::instance() && QCoreApplication::instance()->thread() == QThread::currentThread()) {
        return applicationThreadFsEngine();
    }

    if (!fsEngineThreadStorage()->hasLocalData()) {
        fsEngineThreadStorage()->setLocalData(new CFSEngine);
    }
    
    return fsEngineThreadStorage()->localData();
}

bool CFSEngine::accountLessThan(const QMessageAccountId accountId1, const QMessageAccountId accountId2)
{
    CFSEngine* freestyleEngine = instance();
    return QMessageAccountSortOrderPrivate::lessThan(freestyleEngine->m_currentAccountOrdering,
        freestyleEngine->account(accountId1),
        freestyleEngine->account(accountId2));
}

void CFSEngine::orderAccounts(QMessageAccountIdList& accountIds, const QMessageAccountSortOrder &sortOrder) const
{
    Q_UNUSED(accountIds);
    m_currentAccountOrdering = sortOrder;
    qSort(accountIds.begin(), accountIds.end(), CFSEngine::accountLessThan);
}

bool CFSEngine::folderLessThan(const QMessageFolderId folderId1, const QMessageFolderId folderId2)
{
    CFSEngine* freestyleEngine = instance();
    return QMessageFolderSortOrderPrivate::lessThan(freestyleEngine->m_currentFolderOrdering,
            freestyleEngine->folder(folderId1),
            freestyleEngine->folder(folderId2));
}

void CFSEngine::orderFolders(QMessageFolderIdList& folderIds,  const QMessageFolderSortOrder &sortOrder) const
{
    m_currentFolderOrdering = sortOrder;
    qSort(folderIds.begin(), folderIds.end(), CFSEngine::folderLessThan);
}

bool CFSEngine::messageLessThan(const QMessage& message1, const QMessage& message2)
{
    CFSEngine* freestyleEngine = instance();
    return QMessageSortOrderPrivate::lessThan(freestyleEngine->m_currentMessageOrdering, message1, message2);
}

void CFSEngine::orderMessages(QMessageIdList& messageIds, const QMessageSortOrder &sortOrder) const
{
    m_currentMessageOrdering = sortOrder;
    QList<QMessage> messages;
    for (int i=0; i < messageIds.count(); i++) {
        messages.append(message(messageIds[i]));
    }
    qSort(messages.begin(), messages.end(), CFSEngine::messageLessThan);
    messageIds.clear();
    for (int i=0; i < messages.count(); i++) {
        messageIds.append(messages[i].id());
    }
}

#ifdef FREESTYLEMAILMAPI12USED
void CFSEngine::setMessageStorePrivateSingleton(QMessageStorePrivate* privateStore)
{
    m_messageStorePrivateSingleton = privateStore;
}
#endif

QMessageAccountIdList CFSEngine::queryAccounts(const QMessageAccountFilter &filter, const QMessageAccountSortOrder &sortOrder, uint limit, uint offset) const
{
    QMessageAccountIdList accountIds;

    TRAPD(err, updateEmailAccountsL());
    Q_UNUSED(err);
    
    QMessageAccountFilterPrivate* privateMessageAccountFilter = QMessageAccountFilterPrivate::implementation(filter);
    if (filter.isEmpty()) {
        if (!privateMessageAccountFilter->_notFilter) {
            // All accounts are returned for empty filter
            foreach (QMessageAccount value, m_accounts) {                
                accountIds.append(value.id());
            }
        }
    } else {
        if (privateMessageAccountFilter->_valid) {
            foreach (QMessageAccount value, m_accounts) {
                if (privateMessageAccountFilter->filter(value)) {
                    accountIds.append(value.id());
                }
            }
        } else {
            foreach (QMessageAccount value, m_accounts) {
                if (privateMessageAccountFilter->filter(value)) {
                    accountIds.append(value.id());
                }
            }
        }
    }
    
    if (!sortOrder.isEmpty()) {
        orderAccounts(accountIds, sortOrder);
    }

    applyOffsetAndLimitToAccountIds(accountIds, offset, limit);

    return accountIds;
}

void CFSEngine::applyOffsetAndLimitToAccountIds(QMessageAccountIdList& idList, int offset, int limit) const
{
    if (offset > 0) {
        if (offset > idList.count()) {
            idList.clear();
        } else {
            for (int i = 0; i < offset; i++) {
                idList.removeFirst();
            }
        }
    }
    if (limit > 0) {
        for (int i = idList.count()-1; i >= limit; i--) {
            idList.removeAt(i);
        }
    }
}

int CFSEngine::countAccounts(const QMessageAccountFilter &filter) const
{
    return queryAccounts(filter, QMessageAccountSortOrder(), 0, 0).count();
}

QMessageAccount CFSEngine::account(const QMessageAccountId &id) const
{
    TRAPD(err, updateEmailAccountsL());
    Q_UNUSED(err)

    if (!m_accounts.contains(id.toString())) {
        return QMessageAccountPrivate::from(QMessageAccountId(), QString(), 0, 0, QMessage::NoType);
    }

    return m_accounts[id.toString()];
}

QMessageAccountId CFSEngine::defaultAccount(QMessage::Type type) const
{
    TRAPD(err, updateEmailAccountsL());
    Q_UNUSED(err); 
    QMessageAccountIdList accountIds = accountsByType(type);
    if (accountIds.count() > 0)
        return accountIds.at(0);
        
    return QMessageAccountId();
}

#ifdef FREESTYLEMAILMAPI12USED
int CFSEngine::removeAccount(const QMessageAccountId &id)
{
    TRAP_IGNORE(updateEmailAccountsL());
    TMailboxId mailboxId = fsMailboxIdFromQMessageAccountId(id);
    TRAPD(err, m_clientApi->RemoveMailboxL(mailboxId, this, KUndefinedRequestId) );
    return err;
}
#endif

QMessageAccountIdList CFSEngine::accountsByType(QMessage::Type type) const
{
    QMessageAccountIdList accountIds = QMessageAccountIdList();
    
    foreach (QMessageAccount value, m_accounts) {
        if ((value.messageTypes() & type) == (int)type) {
            accountIds.append(value.id());
        }
    }
    
    return accountIds;
}


void CFSEngine::updateEmailAccountsL() const
{
    QStringList keys = m_accounts.keys();
    RMailboxPtrArray mailboxes;
    CleanupResetAndRelease<MEmailMailbox>::PushL(mailboxes);
    
    m_clientApi->GetMailboxesL(mailboxes);
    
    for (TInt i = 0; i < mailboxes.Count(); i++) {
        MEmailMailbox *mailbox = mailboxes[i];
        QMessageAccountId messageAccountId = qMessageAccountIdFromFsMailboxId(mailbox->MailboxId());
        if (!m_accounts.contains(messageAccountId.toString())) {
            QMessageAccount account = QMessageAccountPrivate::from(
                                      messageAccountId,
                                      QString::fromUtf16(mailbox->MailboxName().Ptr(), mailbox->MailboxName().Length()),
                                      0,
                                      0,
                                      QMessage::Email);
          
            m_accounts.insert(messageAccountId.toString(), account);
        } else {
            keys.removeOne(messageAccountId.toString());
        }
        mailbox->Release();
    }  
    
    mailboxes.Reset();
    CleanupStack::PopAndDestroy(); // mailboxes
    
    for (int i=0; i < keys.count(); i++) {
        m_accounts.remove(keys[i]);
    }   
}

void CFSEngine::setPluginObserversL()
{
    RMailboxPtrArray mailboxes;
    m_clientApi->GetMailboxesL(mailboxes);
    for (TInt i = 0; i < mailboxes.Count(); i++) {
        MEmailMailbox *mailbox = mailboxes[i];
        TRAP_IGNORE(mailbox->RegisterObserverL(*this));
        m_mailboxes.insert(mailbox->MailboxId().iId, mailbox);
    }
    mailboxes.Close();

#ifdef FREESTYLEMAILMAPI12USED
    m_clientApi->RegisterObserverL(*this);
#endif
}

void CFSEngine::NewMessageEventL(const TMailboxId& aMailbox, const REmailMessageIdArray aNewMessages, const TFolderId& aParentFolderId)
{
    for (TInt i = 0; i < aNewMessages.Count(); i++) {
        notificationL(aMailbox, aNewMessages[i], aParentFolderId, QMessageStorePrivate::Added);
    }
}

void CFSEngine::MessageChangedEventL(const TMailboxId& aMailbox, const REmailMessageIdArray aChangedMessages, const TFolderId& aParentFolderId)
{
    for (TInt i = 0; i < aChangedMessages.Count(); i++) {
        notificationL(aMailbox, aChangedMessages[i], aParentFolderId, QMessageStorePrivate::Updated);
    }
}

void CFSEngine::MessageDeletedEventL(const TMailboxId& aMailbox, const REmailMessageIdArray aDeletedMessages, const TFolderId& aParentFolderId)
{
    for (TInt i = 0; i < aDeletedMessages.Count(); i++) {
        notificationL(aMailbox, aDeletedMessages[i], aParentFolderId, QMessageStorePrivate::Removed);
    }
}

#ifdef FREESTYLEMAILMAPI12USED
void CFSEngine::EmailClientApiEventL(const TEmailClientApiEvent aEvent, const TMailboxId& aId)
{
    if(!m_messageStorePrivateSingleton)
        return;
    
    TRAP_IGNORE(updateEmailAccountsL());
    switch (aEvent) {
    case EMailboxRemoved: {
        QMessageAccountId accountId = qMessageAccountIdFromFsMailboxId(aId);
        m_messageStorePrivateSingleton->accountRemoved(accountId);
        }
        break;
    case EMailboxCreated:
    default:
        break;
    }
}
#endif

void CFSEngine::notificationL(const TMailboxId& aMailbox, const TMessageId& aMessageId, 
                              const TFolderId& aParentFolderId, QMessageStorePrivate::NotificationType aNotificationType)
{
    Q_UNUSED(aParentFolderId);
    QMessageManager::NotificationFilterIdSet matchingFilters;
    // Copy the filter map to protect against modification during traversal
    QMap<int, QMessageFilter> filters(m_filters);
    QMap<int, QMessageFilter>::const_iterator it = filters.begin(), end = filters.end();
    QMessage message;
    QMessageId realMessageId = qMessageIdFromFsMessageId(aMessageId);

    if (aNotificationType == QMessageStorePrivate::Removed) {
        message = MessageCache::instance()->message(realMessageId);
        // Remove the removed message from the cache
        MessageCache::instance()->remove(realMessageId.toString());
    } else {

        // Remove the updated message from the cache
        if (aNotificationType == QMessageStorePrivate::Updated)
            MessageCache::instance()->remove(realMessageId.toString());

        // Some older versions of Email client API will return NULL instead of
        // leaving with KErrNotFound if mailbox is not found.
        MEmailMailbox* mailbox = m_clientApi->MailboxL(aMailbox);
        if( !mailbox )
            return;
        CleanupReleasePushL(*mailbox);
        MEmailMessage* fsMessage = NULL;
        TRAP_IGNORE(fsMessage = mailbox->MessageL(aMessageId));
        if (!fsMessage) {
            CleanupStack::PopAndDestroy(mailbox);
            return;
        }
        CleanupReleasePushL(*fsMessage);
        CreateQMessageL(&message, *fsMessage);
        CleanupStack::PopAndDestroy(fsMessage);
        CleanupStack::PopAndDestroy(mailbox);
    }

    for ( ; it != end; ++it) {
        const QMessageFilter &filter(it.value());
        if (filter.isEmpty()) {
            // Empty filter matches to all messages
            matchingFilters.insert(it.key());
        } else {
            if (message.type() == QMessage::NoType) {
                matchingFilters.clear();
                continue;
            }
        }
        QMessageFilterPrivate* privateMessageFilter = QMessageFilterPrivate::implementation(filter);
        if (privateMessageFilter->filter(message)) {
            matchingFilters.insert(it.key());
        }
    }

    int c = matchingFilters.count();
    QString id = realMessageId.toString();
    if (matchingFilters.count() > 0) {
        QT_TRYCATCH_LEAVING(ipMessageStorePrivate->messageNotification(aNotificationType, realMessageId, matchingFilters));
    }
}

#ifdef FREESTYLEMAILMAPI12USED
void CFSEngine::EmailRequestCompleteL( TInt aResult, TUint aRequestId )
{
    if (m_messageStorePrivateSingleton && (aRequestId == KUndefinedRequestId) ) {
        m_messageStorePrivateSingleton->removeAccountComplete(aResult);
        return;
    }

    // notify completion to observer
    EMailMoveRequest request = m_moveRequests.value( aRequestId );
    if( !request.isNull() ) {
        request.m_observer->_error = symbianToMessageManagerError( aResult );
        request.m_observer->setFinished( aResult == KErrNone );
        m_moveRequests.remove( aRequestId );
    }
}
#endif

MEmailMessage* CFSEngine::createFSMessageL(const QMessage &message, const MEmailMailbox* mailbox)
{
    MEmailAddress* pTemplateAddress = mailbox->AddressL();
    TPtrC16 stringPtr(KNullDesC);

    MEmailMessage* fsMessage = mailbox->CreateDraftMessageL();
    CleanupReleasePushL(*fsMessage);

    // Priority
    switch (message.priority()) {
    case QMessage::HighPriority:
        fsMessage->SetFlag(EmailInterface::EFlag_Important);
        fsMessage->ResetFlag(EmailInterface::EFlag_Low);
        break;
    case QMessage::NormalPriority:
        fsMessage->ResetFlag(EmailInterface::EFlag_Important);
        fsMessage->ResetFlag(EmailInterface::EFlag_Low);
        break;
    case QMessage::LowPriority:
        fsMessage->SetFlag(EmailInterface::EFlag_Low);
        fsMessage->ResetFlag(EmailInterface::EFlag_Important);
        break;
    }

    // Read status
    if (message.status() & QMessage::Read) {
        fsMessage->SetFlag(EmailInterface::EFlag_Read);
    } else {
        fsMessage->ResetFlag(EmailInterface::EFlag_Read);
    }

    // Sender/Reply to address
    MEmailAddress* pSenderAddress = fsMessage->SenderAddressL();
    stringPtr.Set(reinterpret_cast<const TUint16*>(QMessagePrivate::senderName(message).utf16()));
    if (pSenderAddress) {
        pSenderAddress->SetDisplayNameL(stringPtr);
    }
    pTemplateAddress->SetDisplayNameL(stringPtr);
    stringPtr.Set(reinterpret_cast<const TUint16*>(message.from().addressee().utf16()));
    if (pTemplateAddress->DisplayName().Length() == 0) {
        if (pSenderAddress) {
            pSenderAddress->SetDisplayNameL(stringPtr);
        }
        pTemplateAddress->SetDisplayNameL(stringPtr);
    }
    if (pSenderAddress) {
        pSenderAddress->SetAddressL(stringPtr);
    }
    pTemplateAddress->SetAddressL(stringPtr);
    fsMessage->SetReplyToAddressL(*pTemplateAddress);

    // To addresses
    QList<QMessageAddress> toList(message.to());
    if (toList.count() > 0) {
        TPtrC16 receiver(KNullDesC);
        TPtrC16 displayname(KNullDesC);
        for (int i = 0; i < toList.size(); ++i) {
            REmailAddressArray toAddress;
            QString qaddress;
            QString qname;
            convertQMessageAddressToFreestyle(toList.at(i).addressee(), qaddress, qname, receiver, displayname);
            pTemplateAddress->SetAddressL(receiver);
            pTemplateAddress->SetDisplayNameL(displayname);
            pTemplateAddress->SetRole(MEmailAddress::ETo);
            toAddress.Append(pTemplateAddress);
            fsMessage->SetRecipientsL(MEmailAddress::ETo, toAddress);
            toAddress.Close();
        }
    }
    
    // Cc addresses
    QList<QMessageAddress> ccList(message.cc());
    if (ccList.count() > 0) {
        TPtrC16 receiver(KNullDesC);
        TPtrC16 displayname(KNullDesC);
        for (int i = 0; i < ccList.size(); ++i) {
            REmailAddressArray ccAddress;
            QString qaddress;
            QString qname;
            convertQMessageAddressToFreestyle(ccList.at(i).addressee(), qaddress, qname, receiver, displayname);
            pTemplateAddress->SetDisplayNameL(displayname);
            pTemplateAddress->SetRole(MEmailAddress::ECc);
            pTemplateAddress->SetAddressL(receiver);
            ccAddress.Append(pTemplateAddress);
            fsMessage->SetRecipientsL(MEmailAddress::ECc, ccAddress);
            ccAddress.Close();
        }
    }
        
    // Bcc addresses
    QList<QMessageAddress> bccList(message.bcc());
    if (bccList.count() > 0) {
        TPtrC16 receiver(KNullDesC);
        TPtrC16 displayname(KNullDesC);
        for (int i = 0; i < bccList.size(); ++i) {
            REmailAddressArray bccAddress;
            QString qaddress;
            QString qname;
            convertQMessageAddressToFreestyle(bccList.at(i).addressee(), qaddress, qname, receiver, displayname);
            pTemplateAddress->SetDisplayNameL(displayname);
            pTemplateAddress->SetRole(MEmailAddress::EBcc);
            pTemplateAddress->SetAddressL(receiver);
            bccAddress.Append(pTemplateAddress);
            fsMessage->SetRecipientsL(MEmailAddress::EBcc, bccAddress);
            bccAddress.Close();
        }
    }

    if (message.bodyId() == QMessageContentContainerPrivate::bodyContentId()) {
        // Message contains only body (not attachments)
        QString messageBody = message.textContent();
        if (!messageBody.isEmpty()) {
            QByteArray type = message.contentType();
            QByteArray subType = message.contentSubType();
            MEmailMessageContent* content = fsMessage->ContentL();
            MEmailTextContent* textContent = content->AsTextContentOrNull();
            if (textContent) {
                if (type == "text" && subType == "plain") {
                    textContent->SetTextL(MEmailTextContent::EPlainText, TPtrC(reinterpret_cast<const TUint16*>(message.textContent().utf16())));
                } 
               else if (type == "text" && subType == "html") {
                    textContent->SetTextL(MEmailTextContent::EHtmlText, TPtrC(reinterpret_cast<const TUint16*>(message.textContent().utf16())));
                }
            }
            else
                fsMessage->SetPlainTextBodyL(TPtrC(reinterpret_cast<const TUint16*>(message.textContent().utf16())));
        }
    } else {
        // Message contains body and attachments
        QMessageContentContainerIdList contentIds = message.contentIds();
        foreach (QMessageContentContainerId id, contentIds){
            QMessageContentContainer container = message.find(id);
            MEmailMessageContent* content = fsMessage->ContentL(); 
            QMessageContentContainerPrivate* pPrivateContainer = QMessageContentContainerPrivate::implementation(container);
            if (pPrivateContainer->_id == message.bodyId()) {
                // ContentContainer is body
                if (!container.textContent().isEmpty()) {               
                    MEmailTextContent* textContent = content->AsTextContentOrNull();
                    if (textContent) {
                        QByteArray type = container.contentType();
                        QByteArray subType = container.contentSubType();
                        if (type == "text" && subType == "plain") {
                            textContent->SetTextL(MEmailTextContent::EPlainText, TPtrC(reinterpret_cast<const TUint16*>(container.textContent().utf16())));
                        }
                        else if (type == "text" && subType == "html") {
                            textContent->SetTextL(MEmailTextContent::EHtmlText, TPtrC(reinterpret_cast<const TUint16*>(container.textContent().utf16())));
                        } 
                    }
                    else
                        fsMessage->SetPlainTextBodyL(TPtrC(reinterpret_cast<const TUint16*>(container.textContent().utf16())));
                }
            } else {
                // ContentContainer is attachment
                QByteArray filePath = QMessageContentContainerPrivate::attachmentFilename(container);
                if (filePath.length() > 0) {
                    if (filePath.startsWith('.')) {
                        // Remove "."
                        filePath.remove(0,1);
                        // Insert data directory location to the path
                        filePath.insert(0,QDesktopServices::storageLocation(QDesktopServices::DataLocation).toAscii());
                    }
                    // Replace Qt style path separator "/" with Symbian path separator "\"
                    filePath.replace(QByteArray("/"), QByteArray("\\"));
                    QString temp_path = QString(filePath);
                    TPtrC16 attachmentPath(KNullDesC);
                    attachmentPath.Set(reinterpret_cast<const TUint16*>(temp_path.utf16()));
                    fsMessage->AddAttachmentL(attachmentPath);
                }
            }        
        }
    }
    fsMessage->SetSubjectL(TPtrC(reinterpret_cast<const TUint16*>(message.subject().utf16())));
    
    QMessagePrivate* privateMessage = QMessagePrivate::implementation(message);
    privateMessage->_id = qMessageIdFromFsMessageId(fsMessage->MessageId());
    
    fsMessage->SaveChangesL();
    CleanupStack::Pop(fsMessage);
    return fsMessage;
}

void CFSEngine::convertQMessageAddressToFreestyle(const QString& emailAddress, QString& qaddress, QString& qname, 
                                                    TPtrC16& address, TPtrC16& displayname)
{
    QString qsuffix;

    bool startDelimeterFound = false;
    bool endDelimeterFound = false;

    QMessageAddress::parseEmailAddress(emailAddress, &qname,
            &qaddress, &qsuffix, &startDelimeterFound, &endDelimeterFound);

    address.Set(reinterpret_cast<const TUint16*>(qaddress.utf16()));

    if (startDelimeterFound)
        displayname.Set(reinterpret_cast<const TUint16*>(qname.utf16()));
    else
        displayname.Set(KNullDesC);
}

void CFSEngine::convertFreestyleAddressToQString(MEmailAddress* emailAddress, QString& combinedAddress)
{
    TPtrC address = emailAddress->Address();
    TPtrC displayName = emailAddress->DisplayName();

    QString qAddress = QString::fromUtf16(address.Ptr(), address.Length());
    QString qDisplayName = QString::fromUtf16(displayName.Ptr(), displayName.Length());

    QChar startDelimiter = '<';
    QChar endDelimiter = '>';
    QChar separator = ' ';

    combinedAddress = "";

    if (qAddress.compare(qDisplayName)) {
        combinedAddress += qDisplayName;
        combinedAddress += separator;
        combinedAddress += startDelimiter;
        combinedAddress += qAddress;
        combinedAddress += endDelimiter;
    } else {
        combinedAddress += qDisplayName;
    }
}

bool CFSEngine::addMessage(QMessage* message)
{
    bool ret(false);
    if (message) {
        TRAPD(err, addMessageL(message));
        if (err == KErrNone) {
            ret= true;
        }
    }
    return ret;
}
void CFSEngine::addMessageL(QMessage* message)
{
    TMailboxId mailboxId(fsMailboxIdFromQMessageAccountId(message->parentAccountId()));
    // function call leaves with error if mailbox is not found
    MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId);
    CleanupReleasePushL(*mailbox);
    // address pointer not owned

    MEmailAddress* pMailboxAddress = mailbox->AddressL();
    HBufC* pOriginalAddress = pMailboxAddress->Address().AllocLC();
    HBufC* pOriginalDisplayName = pMailboxAddress->DisplayName().AllocLC();
    MEmailAddress::TRole originalRole = pMailboxAddress->Role();
    MEmailMessage* fsMessage = createFSMessageL(*message, mailbox);
    CleanupReleasePushL(*fsMessage);
    pMailboxAddress->SetRole(originalRole);
    pMailboxAddress->SetDisplayNameL(*pOriginalDisplayName);
    pMailboxAddress->SetAddressL(*pOriginalAddress);

    
    CleanupStack::PopAndDestroy(4, mailbox);
}

bool CFSEngine::updateMessage(QMessage* message)
{
    TRAPD(err, updateMessageL(message));
    if (err != KErrNone)
        return false;
    else
        return true;
}

void CFSEngine::updateMessageL(QMessage* message)
{
    TMailboxId mailboxId(fsMailboxIdFromQMessageAccountId(message->parentAccountId()));
    MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId);
    CleanupReleasePushL(*mailbox);

    MEmailAddress* pTemplateAddress = mailbox->AddressL();
    TPtrC16 stringPtr(KNullDesC);
  
    TMessageId messageId(fsMessageIdFromQMessageId(message->id()));
    MEmailMessage* fsMessage = mailbox->MessageL(messageId);
    CleanupReleasePushL(*fsMessage);
    
    // Priority
    switch (message->priority()) {
    case QMessage::HighPriority:
        fsMessage->SetFlag(EmailInterface::EFlag_Important);
        fsMessage->ResetFlag(EmailInterface::EFlag_Low);
        break;
    case QMessage::NormalPriority:
        fsMessage->ResetFlag(EmailInterface::EFlag_Important);
        fsMessage->ResetFlag(EmailInterface::EFlag_Low);
        break;
    case QMessage::LowPriority:
        fsMessage->SetFlag(EmailInterface::EFlag_Low);
        fsMessage->ResetFlag(EmailInterface::EFlag_Important);
        break;
    }

    // Read status
    if (message->status() & QMessage::Read) {
        fsMessage->SetFlag(EmailInterface::EFlag_Read);
    } else {
        fsMessage->ResetFlag(EmailInterface::EFlag_Read);
    }
        
    // Sender/Reply to address
    MEmailAddress* pSenderAddress = fsMessage->SenderAddressL();
    stringPtr.Set(reinterpret_cast<const TUint16*>(QMessagePrivate::senderName(*message).utf16()));
    if (pSenderAddress) {
        pSenderAddress->SetDisplayNameL(stringPtr);
    }
    pTemplateAddress->SetDisplayNameL(stringPtr);
    stringPtr.Set(reinterpret_cast<const TUint16*>(message->from().addressee().utf16()));
    if (pTemplateAddress->DisplayName().Length() == 0) {
        if (pSenderAddress) {
            pSenderAddress->SetDisplayNameL(stringPtr);
        }
        pTemplateAddress->SetDisplayNameL(stringPtr);
    }
    if (pSenderAddress) {
        pSenderAddress->SetAddressL(stringPtr);
    }
    pTemplateAddress->SetAddressL(stringPtr);
    fsMessage->SetReplyToAddressL(*pTemplateAddress);

    // Remove all addresses from existing email message
    // to make sure that there won't be duplicates when
    // message addresses are updated.
    REmailAddressArray oldAddresses;
    fsMessage->GetRecipientsL(MEmailAddress::EUndefined, oldAddresses);
    CleanupResetAndRelease<MEmailAddress>::PushL(oldAddresses);
    for (int i=0; i<oldAddresses.Count(); i++) {
        fsMessage->RemoveRecipientL(*oldAddresses[i]);
    }
    CleanupStack::PopAndDestroy(&oldAddresses);

    // To addresses
    QList<QMessageAddress> toList(message->to());
    if (toList.count() > 0) {
        TPtrC16 receiver(KNullDesC);
        QString qreceiver;
        for (int i = 0; i < toList.size(); ++i) {
            REmailAddressArray toAddress;
            qreceiver = toList.at(i).addressee();
            receiver.Set(reinterpret_cast<const TUint16*>(qreceiver.utf16()));
            MEmailAddress* address = mailbox->AddressL();
            address->SetAddressL(receiver);
            toAddress.Append(address);
            fsMessage->SetRecipientsL(MEmailAddress::ETo, toAddress);
            toAddress.Close();
        }
    }

    // Cc addresses
    QList<QMessageAddress> ccList(message->cc());
    if (ccList.count() > 0) {
        TPtrC16 receiver(KNullDesC);
        QString qreceiver;
        for (int i = 0; i < ccList.size(); ++i) {
            REmailAddressArray ccAddress;
            qreceiver = ccList.at(i).addressee();
            receiver.Set(reinterpret_cast<const TUint16*>(qreceiver.utf16()));
            pTemplateAddress->SetDisplayNameL(receiver);
            pTemplateAddress->SetRole(MEmailAddress::ECc);
            pTemplateAddress->SetAddressL(receiver);
            ccAddress.Append(pTemplateAddress);
            fsMessage->SetRecipientsL(MEmailAddress::ECc, ccAddress);
            ccAddress.Close();
        }
    }

    // Bcc addresses
    QList<QMessageAddress> bccList(message->bcc());
    if (bccList.count() > 0) {
        TPtrC16 receiver(KNullDesC);
        QString qreceiver;
        for (int i = 0; i < bccList.size(); ++i) {
            REmailAddressArray bccAddress;
            qreceiver = bccList.at(i).addressee();
            receiver.Set(reinterpret_cast<const TUint16*>(qreceiver.utf16()));
            pTemplateAddress->SetDisplayNameL(receiver);
            pTemplateAddress->SetRole(MEmailAddress::EBcc);
            pTemplateAddress->SetAddressL(receiver);
            bccAddress.Append(pTemplateAddress);
            fsMessage->SetRecipientsL(MEmailAddress::EBcc, bccAddress);
            bccAddress.Close();
        }
    }
    
    if (message->bodyId() == QMessageContentContainerPrivate::bodyContentId()) {
        // Message contains only body (not attachments)
        QString messageBody = message->textContent();
        if (!messageBody.isEmpty()) {
            MEmailMessageContent* content = fsMessage->ContentL();
            MEmailTextContent* textContent = content->AsTextContentOrNull();
            if (textContent) {
                QByteArray type = message->contentType();
                QByteArray subType = message->contentSubType();
                if (type == "text" && subType == "plain")
                    textContent->SetTextL(MEmailTextContent::EPlainText, TPtrC(reinterpret_cast<const TUint16*>(message->textContent().utf16())));
                else if (type == "text" && subType == "html")
                    textContent->SetTextL(MEmailTextContent::EHtmlText, TPtrC(reinterpret_cast<const TUint16*>(message->textContent().utf16())));
            } else {
                fsMessage->SetPlainTextBodyL(TPtrC(reinterpret_cast<const TUint16*>(message->textContent().utf16())));
            }
        }
    } else {
        // Message contains body and attachments
        QMessageContentContainerIdList contentIds = message->contentIds();
        foreach (QMessageContentContainerId id, contentIds){
            QMessageContentContainer container = message->find(id);
            QMessageContentContainerPrivate* pPrivateContainer = QMessageContentContainerPrivate::implementation(container);
            if (pPrivateContainer->_id == message->bodyId()) {
                // ContentContainer is body
                if (!container.textContent().isEmpty()) {
                    MEmailMessageContent* content = fsMessage->ContentL();
                    MEmailTextContent* textContent = content->AsTextContentOrNull();
                    if (textContent) {
                        QByteArray type = container.contentType();
                        QByteArray subType = container.contentSubType();
                        if (type == "text" && subType == "plain")
                            textContent->SetTextL(MEmailTextContent::EPlainText, TPtrC(reinterpret_cast<const TUint16*>(container.textContent().utf16())));
                        else if (type == "text" && subType == "html")
                            textContent->SetTextL(MEmailTextContent::EHtmlText, TPtrC(reinterpret_cast<const TUint16*>(container.textContent().utf16())));
                    } else {
                        fsMessage->SetPlainTextBodyL(TPtrC(reinterpret_cast<const TUint16*>(container.textContent().utf16())));
                    }
                }
            } else {
                // ContentContainer is attachment
                QByteArray filePath = QMessageContentContainerPrivate::attachmentFilename(container);
                if (filePath.length() > 0) {
                    if (filePath.startsWith('.')) {
                        // Remove "."
                        filePath.remove(0,1);
                        // Insert data directory location to the path
                        filePath.insert(0,QDesktopServices::storageLocation(QDesktopServices::DataLocation).toAscii());
                    }
                    // Replace Qt style path separator "/" with Symbian path separator "\"
                    filePath.replace(QByteArray("/"), QByteArray("\\"));
                    QString temp_path = QString(filePath);
                    TPtrC16 attachmentPath(KNullDesC);
                    attachmentPath.Set(reinterpret_cast<const TUint16*>(temp_path.utf16()));
                    fsMessage->AddAttachmentL(attachmentPath);
                }
            }        
        }
    }
    
    fsMessage->SetSubjectL(TPtrC(reinterpret_cast<const TUint16*>(message->subject().utf16())));
    fsMessage->SaveChangesL();
    CleanupStack::PopAndDestroy(fsMessage);
    CleanupStack::PopAndDestroy(mailbox);

    // Remove updated message from the cache
    MessageCache::instance()->remove(message->id().toString());
}

bool CFSEngine::removeMessage(const QMessageId &id, QMessageManager::RemovalOption option)
{
    Q_UNUSED(option);

    TMessageId fsMessageId = fsMessageIdFromQMessageId(id);
    MEmailMailbox* mailbox = NULL;
    TRAPD(err, mailbox = m_clientApi->MailboxL(fsMessageId.iFolderId.iMailboxId));
    if (err == KErrNone) {
        MEmailFolder* folder = NULL;
        TRAP(err, folder = mailbox->FolderL(fsMessageId.iFolderId));
        if (err == KErrNone) {
            REmailMessageIdArray messageIds;
            messageIds.Append(fsMessageId);
            TRAP(err, folder->DeleteMessagesL(messageIds));
            folder->Release();
            messageIds.Close();
        }
        mailbox->Release();
    }

    // Remove removed message from the cache
    MessageCache::instance()->remove(id.toString());

    if (err != KErrNone) {
        return false;
    }
    return true;
}

bool CFSEngine::showMessage(const QMessageId &id)
{
    TMessageId fsMessageId = fsMessageIdFromQMessageId(id);
    MEmailMailbox* mailbox = NULL;
    TRAPD(err, mailbox = m_clientApi->MailboxL(fsMessageId.iFolderId.iMailboxId));
    if (err == KErrNone) {
        MEmailMessage* message = NULL;
        TRAP(err, message = mailbox->MessageL(fsMessageId));
        if (err == KErrNone) {
            TRAP(err, message->ShowMessageViewerL());
            message->Release();
        }
        mailbox->Release();
    }

    if (err != KErrNone) {
        return false;
    }
    return true;
}

bool CFSEngine::composeMessage(const QMessage &message)
{
    bool retVal = false;
    MEmailMailbox* mailbox = NULL;
    TMailboxId mailboxId(fsMailboxIdFromQMessageAccountId(message.parentAccountId()));
    TRAPD(err, mailbox = m_clientApi->MailboxL(mailboxId));
    if (err == KErrNone) {
        TRAPD(err2, mailbox->EditNewMessageL());
        if (err2 == KErrNone)
            retVal = true;
        mailbox->Release();
    }
    return retVal;
}

bool CFSEngine::retrieve(QMessageServicePrivate& privateService, const QMessageId &messageId, const QMessageContentContainerId& id)
{
    bool retVal = false;

    QMessage msg = message(messageId);
    QMessageContentContainer cont = msg.find(id);
    QMessageContentContainerPrivate *contPrivate = QMessageContentContainerPrivate::implementation(cont);
    TMessageContentId contentId = contPrivate->_fsContentId;

    MEmailAttachment* attachment = attachmentById(contentId);
    if (attachment) {
        if (attachment->TotalSize() != attachment->AvailableSize()) {
            CFSContentFetchOperation* op = new CFSContentFetchOperation(*this, privateService, attachment);
            if (op->fetch()) {
                m_contentFetchOperations.insert(&privateService, op);
                retVal = true;
            } else {
                delete op;
                retVal = false;
            }
        } else {
            attachment->Release();
            retVal = false;
        }
    }

    return retVal;
}

bool CFSEngine::retrieveBody(QMessageServicePrivate& privateService, const QMessageId& id)
{
    bool retVal = false;

    TMessageId fsMessageId = fsMessageIdFromQMessageId(id);
    if (fsMessageId.iId <= 0)
        return retVal;

    MEmailMailbox* mailbox = NULL;
    TRAPD(err, mailbox = m_clientApi->MailboxL(fsMessageId.iFolderId.iMailboxId));
    if (err != KErrNone)
        return retVal;

    MEmailMessage* emailMessage = NULL;
    TRAP(err, emailMessage = mailbox->MessageL(fsMessageId));
    if (err != KErrNone) {
        mailbox->Release();
        return retVal;
    }

    QMessage msg = message(id);
    if (msg.bodyId().isValid()) {
        MEmailMessageContent* emailContent = NULL;
        TRAP(err, emailContent = emailMessage->ContentL());
        if (err == KErrNone && emailContent) {
            QMessageContentContainer cont = msg.find(msg.bodyId());
            QMessageContentContainerPrivate *contPrivate = QMessageContentContainerPrivate::implementation(cont);
            TMessageContentId contentId = contPrivate->_fsContentId;
            MEmailTextContent* bodyContent = textContentById(contentId, emailContent);
            if (bodyContent) {
                if (bodyContent->TotalSize() != bodyContent->AvailableSize()) {
                    CFSContentFetchOperation* op = new CFSContentFetchOperation(*this, privateService, bodyContent, emailMessage);
                    emailMessage = NULL; // CFSContentFetchOperation took emailMessage ownership
                    bodyContent = NULL; // CFSContentFetchOperation took bodyContent ownership
                    if (op->fetch()) {
                        m_contentFetchOperations.insert(&privateService, op);
                        retVal = true;
                    } else {
                        delete op;
                    }
                }
                if (bodyContent)
                    bodyContent->Release();
            }
        }
    } else {
#ifdef FREESTYLEMAILMAPI12USED
        CFSContentStructureFetchOperation* op = new CFSContentStructureFetchOperation(*this, privateService, emailMessage);
        emailMessage = NULL; // CFSContentStructureFetchOperation took emailMessage ownership
        if (op->fetch()) {
            m_contentStructurefetchOperations.insert(&privateService, op);
            retVal = true;
        } else {
            delete op;
        }
#endif
    }

    if (emailMessage)
        emailMessage->Release();
    mailbox->Release();

    return retVal;
}

bool CFSEngine::retrieveHeader(QMessageServicePrivate& privateService, const QMessageId& id)
{
    Q_UNUSED(id);
    Q_UNUSED(privateService);
    return false;
}

void CFSEngine::synchronizeL(QMessageServicePrivate &observer, const QMessageAccountId &id)
{
    TMailboxId mailboxId = fsMailboxIdFromQMessageAccountId(id);
    
    foreach (EMailSyncRequest* request, m_syncRequests) {
        if (request->m_mailboxId == mailboxId) {
            User::Leave(KErrAlreadyExists);
        }
    }
    
    EMailSyncRequest* req = new (ELeave) EMailSyncRequest(observer, m_syncRequests, mailboxId);
    req->m_active = true;
    m_syncRequests.append(req);
    
    MEmailMailbox* mailbox = m_mailboxes.value(mailboxId.iId);
    if (!mailbox) {
        // Mailbox was not found in the cache
        mailbox = m_clientApi->MailboxL(mailboxId);
        m_mailboxes.insert(mailboxId.iId, mailbox);
        
        if (!mailbox) {
            User::Leave(KErrNotFound);
        }
    }
    
    // Mailbox cannot be released since it would cause email client API
    // side to crash when it tries to callback to the observer given to plugin.
    // Mailbox will be released when the mailbox cache is cleaned.
    mailbox->SynchroniseL(*req);
}

bool CFSEngine::synchronize(QMessageServicePrivate &observer, const QMessageAccountId &id)
{
    TRAPD(err, synchronizeL(observer, id));
    return (err == KErrNone);
}

#ifdef FREESTYLEMAILMAPI12USED
bool CFSEngine::moveMessages(QMessageServicePrivate& observer, const QMessageIdList &messageIds, 
    const QMessageFolderId &toFolderId)
{
    // message count already checked in QMessageService::moveMessages
    TMessageId fsFirstMessageId = fsMessageIdFromQMessageId(messageIds[0]);
    TMailboxId mailboxId = fsFirstMessageId.iFolderId.iMailboxId;
   
    // Check that To folder belongs to same mailbox as message.
    TFolderId fsToFolderId = fsFolderIdFromQMessageFolderId(toFolderId);
    if (!(mailboxId == fsToFolderId.iMailboxId)) {
        observer._error = QMessageManager::InvalidId;
        return false;
    }
    
    REmailMessageIdArray fsMessageIdArray;
    int count = messageIds.count();
    for (int i = 0; i < count; i++) {
        TMessageId fsMessageId = fsMessageIdFromQMessageId(messageIds[i]);
        // Check that messages are within the same mailbox.
        if (!(mailboxId == fsMessageId.iFolderId.iMailboxId)) {
            fsMessageIdArray.Close();
            observer._error = QMessageManager::InvalidId;
            return false; 
        }
        // Let's populate native mail array.
        int error = fsMessageIdArray.Append(fsMessageId);
        if (error != KErrNone) {
            fsMessageIdArray.Close();
            observer._error = QMessageManager::WorkingMemoryOverflow;
            return false;
        }
    }
    
    TRAPD( err, moveMessagesL(observer, fsMessageIdArray, fsToFolderId) );
    fsMessageIdArray.Close();
    if (err != KErrNone)
        {
        observer._error = symbianToMessageManagerError(err);
        return false;
        }
    return true;
}

void CFSEngine::moveMessagesL(QMessageServicePrivate &observer, 
    const REmailMessageIdArray &messages, const TFolderId &toFolder)
{
    // use cached mailbox instances if available
    TMailboxId mailboxId = toFolder.iMailboxId;
    MEmailMailbox* mailbox = m_mailboxes.value(mailboxId.iId);
    if (!mailbox) {
        mailbox = m_clientApi->MailboxL(mailboxId.iId);    
        if (mailbox) {
            m_mailboxes.insert(mailboxId.iId, mailbox);
        } else {
            User::Leave(KErrNotFound);
        }
    }

    m_mailboxMoveRequestId++;
    mailbox->MoveMessagesL( messages, toFolder, this, m_mailboxMoveRequestId);
    m_moveRequests.insert(m_mailboxMoveRequestId, EMailMoveRequest( &observer, mailboxId ));
}
#endif

bool CFSEngine::removeMessages(const QMessageFilter& /*filter*/, QMessageManager::RemovalOption /*option*/)
{
    return false;
}

void CFSEngine::handleNestedFiltersFromMessageFilter(QMessageFilter &filter) const
{
    QMessageFilterPrivate* pMFFilter = QMessageFilterPrivate::implementation(filter);
    if (pMFFilter->_filterList.count() > 0) {
        int filterListCount = pMFFilter->_filterList.count();
        for (int i=0; i < filterListCount; i++) {
            for (int j=0; j < pMFFilter->_filterList[i].count(); j++) {
                QMessageFilterPrivate* pMFFilter2 = QMessageFilterPrivate::implementation(pMFFilter->_filterList[i][j]);
                if (pMFFilter2->_field == QMessageFilterPrivate::ParentAccountIdFilter) {
                    QMessageAccountIdList accountIds = queryAccounts(*pMFFilter2->_accountFilter, QMessageAccountSortOrder(), 0, 0);
                    QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter2->_comparatorValue));
                    if (accountIds.count() > 0) {
                        pMFFilter->_filterList[i].removeAt(j);
                        if (cmp == QMessageDataComparator::Includes) {
                            for (int x = 0; x < accountIds.count(); x++) {
                                if (x == 0) {
                                    if (x+1 < accountIds.count()) {
                                        pMFFilter->_filterList.append(pMFFilter->_filterList[i]);
                                    }
                                    pMFFilter->_filterList[i].append(QMessageFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal));
                                    qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan);
                                } else {
                                    if (x+1 < accountIds.count()) {
                                        pMFFilter->_filterList.append(pMFFilter->_filterList[pMFFilter->_filterList.count()-1]);
                                        pMFFilter->_filterList[pMFFilter->_filterList.count()-2].append(QMessageFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal));
                                        qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-2].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-2].end(), QMessageFilterPrivate::lessThan);
                                    } else {
                                        pMFFilter->_filterList[pMFFilter->_filterList.count()-1].append(QMessageFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal));
                                        qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-1].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-1].end(), QMessageFilterPrivate::lessThan);
                                    }
                                }
                            }
                        } else { // Excludes
                            for (int x = 0; x < accountIds.count(); x++) {
                                pMFFilter->_filterList[i].append(QMessageFilter::byParentAccountId(accountIds[x],QMessageDataComparator::NotEqual));
                            }
                            qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan);
                        }
                    } else {
                        delete pMFFilter2->_accountFilter;
                        pMFFilter2->_accountFilter = 0;
                        pMFFilter2->_field = QMessageFilterPrivate::Id;
                        qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan);
                    }
                } else if (pMFFilter2->_field == QMessageFilterPrivate::ParentFolderIdFilter) { 
                    QMessageFolderIdList folderIds = queryFolders(*pMFFilter2->_folderFilter, QMessageFolderSortOrder(), 0, 0);
                    QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter2->_comparatorValue));
                    if (folderIds.count() > 0) {
                        pMFFilter->_filterList[i].removeAt(j);
                        if (cmp == QMessageDataComparator::Includes) {
                            for (int x = 0; x < folderIds.count(); x++) {
                                if (x == 0) {
                                    if (x+1 < folderIds.count()) {
                                        pMFFilter->_filterList.append(pMFFilter->_filterList[i]);
                                    }
                                    pMFFilter->_filterList[i].append(QMessageFilter::byParentFolderId(folderIds[x],QMessageDataComparator::Equal));
                                    qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan);
                                } else {
                                    if (x+1 < folderIds.count()) {
                                        pMFFilter->_filterList.append(pMFFilter->_filterList[pMFFilter->_filterList.count()-1]);
                                        pMFFilter->_filterList[pMFFilter->_filterList.count()-2].append(QMessageFilter::byParentFolderId(folderIds[x],QMessageDataComparator::Equal));
                                        qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-2].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-2].end(), QMessageFilterPrivate::lessThan);
                                    } else {
                                        pMFFilter->_filterList[pMFFilter->_filterList.count()-1].append(QMessageFilter::byParentFolderId(folderIds[x],QMessageDataComparator::Equal));
                                        qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-1].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-1].end(), QMessageFilterPrivate::lessThan);
                                    }
                                }
                            }
                        } else { // Excludes
                            for (int x = 0; x < folderIds.count(); x++) {
                                pMFFilter->_filterList[i].append(QMessageFilter::byParentFolderId(folderIds[x],QMessageDataComparator::NotEqual));
                            }
                            qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan);
                        }
                    } else {
                        delete pMFFilter2->_folderFilter;
                        pMFFilter2->_folderFilter = 0;
                        pMFFilter2->_field = QMessageFilterPrivate::Id;
                        qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFilterPrivate::lessThan);
                    }
                } else {
                    break;
                }
            }
        }
    } else {
        if (pMFFilter->_field == QMessageFilterPrivate::ParentAccountIdFilter) {
            QMessageAccountIdList accountIds = queryAccounts(*pMFFilter->_accountFilter, QMessageAccountSortOrder(), 0, 0);
            QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter->_comparatorValue));
            if (accountIds.count() > 0) {
                for (int i=0; i < accountIds.count(); i++) {
                    if (i == 0) {
                        delete pMFFilter->_accountFilter;
                        pMFFilter->_accountFilter = 0;
                        pMFFilter->_field = QMessageFilterPrivate::ParentAccountId;
                        pMFFilter->_value = accountIds[0].toString();
                        pMFFilter->_comparatorType = QMessageFilterPrivate::Equality;
                        if (cmp == QMessageDataComparator::Includes) {
                            pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::Equal);
                        } else { // Excludes
                            pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::NotEqual);
                        }
                    } else {
                        if (cmp == QMessageDataComparator::Includes) {
                            filter |= QMessageFilter::byParentAccountId(accountIds[i],QMessageDataComparator::Equal);
                        } else { // Excludes
                            filter &= QMessageFilter::byParentAccountId(accountIds[i],QMessageDataComparator::NotEqual);
                        }
                    }
                }
            } else {
                delete pMFFilter->_accountFilter;
                pMFFilter->_accountFilter = 0;
                pMFFilter->_field = QMessageFilterPrivate::Id;
            }
        } else if (pMFFilter->_field == QMessageFilterPrivate::ParentFolderIdFilter) {
            QMessageFolderIdList folderIds = queryFolders(*pMFFilter->_folderFilter, QMessageFolderSortOrder(), 0, 0);
            QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter->_comparatorValue));
            if (folderIds.count() > 0) {
                for (int i=0; i < folderIds.count(); i++) {
                    if (i == 0) {
                        delete pMFFilter->_folderFilter;
                        pMFFilter->_folderFilter = 0;
                        pMFFilter->_field = QMessageFilterPrivate::ParentFolderId;
                        pMFFilter->_value = folderIds[0].toString();
                        pMFFilter->_comparatorType = QMessageFilterPrivate::Equality;
                        if (cmp == QMessageDataComparator::Includes) {
                            pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::Equal);
                        } else { // Excludes
                            pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::NotEqual);
                        }
                    } else {
                        if (cmp == QMessageDataComparator::Includes) {
                            filter |= QMessageFilter::byParentFolderId(folderIds[i],QMessageDataComparator::Equal);
                        } else { // Excludes
                            filter &= QMessageFilter::byParentFolderId(folderIds[i],QMessageDataComparator::NotEqual);
                        }
                    }
                }
            } else {
                delete pMFFilter->_folderFilter;
                pMFFilter->_folderFilter = 0;
                pMFFilter->_field = QMessageFilterPrivate::Id;
            }
        }
    }
}

bool CFSEngine::queryMessages(QMessageServicePrivate& privateService, const QMessageFilter &filter, const QMessageSortOrder &sortOrder, uint limit, uint offset) const
{
    TRAPD(err, queryMessagesL(privateService, filter, sortOrder, limit, offset));
    if (err != KErrNone) {
        return false;
    }
    return true;
}


void CFSEngine::queryMessagesL(QMessageServicePrivate& privateService, const QMessageFilter &filter, const QMessageSortOrder &sortOrder, uint limit, uint offset) const
{
    TRAP_IGNORE(updateEmailAccountsL());

    FSMessageQueryInfo queryInfo;
    queryInfo.operationId = ++m_operationIds;
    if (queryInfo.operationId == 100000) {
        queryInfo.operationId = 1;
    }
    queryInfo.isQuery = true;
    queryInfo.body = QString();
    queryInfo.matchFlags = 0;
    queryInfo.filter = filter;
    queryInfo.sortOrder = sortOrder;
    queryInfo.offset = offset;
    queryInfo.limit = limit;
    queryInfo.findOperation = new CFSMessagesFindOperation((CFSEngine&)*this, queryInfo.operationId);
    queryInfo.privateService = &privateService;
    queryInfo.currentFilterListIndex = 0;
    queryInfo.canceled = false;
    m_messageQueries.append(queryInfo);

    handleNestedFiltersFromMessageFilter(m_messageQueries[m_messageQueries.count()-1].filter);
    
    doNextQuery();
}

bool CFSEngine::queryMessages(QMessageServicePrivate& privateService, const QMessageFilter &filter, const QString &body, QMessageDataComparator::MatchFlags matchFlags, const QMessageSortOrder &sortOrder, uint limit, uint offset) const
{
    TRAPD(err, queryMessagesL(privateService, filter, body, matchFlags, sortOrder, limit, offset));
    if (err != KErrNone) {
        return false;
    }
    return true;
}

void CFSEngine::queryMessagesL(QMessageServicePrivate& privateService, const QMessageFilter &filter, const QString &body, QMessageDataComparator::MatchFlags matchFlags, const QMessageSortOrder &sortOrder, uint limit, uint offset) const
{
    TRAP_IGNORE(updateEmailAccountsL());

    FSMessageQueryInfo queryInfo;
    queryInfo.operationId = ++m_operationIds;
    if (queryInfo.operationId == 100000) {
        queryInfo.operationId = 1;
    }
    queryInfo.isQuery = true;
    queryInfo.body = body;
    queryInfo.matchFlags = matchFlags;
    queryInfo.filter = filter;
    queryInfo.sortOrder = sortOrder;
    queryInfo.offset = offset;
    queryInfo.limit = limit;
    queryInfo.findOperation = new CFSMessagesFindOperation((CFSEngine&)*this, queryInfo.operationId);
    queryInfo.privateService = &privateService;
    queryInfo.currentFilterListIndex = 0;
    queryInfo.canceled = false;
    m_messageQueries.append(queryInfo);
    
    handleNestedFiltersFromMessageFilter(m_messageQueries[m_messageQueries.count()-1].filter);
    
    doNextQuery();
}

bool CFSEngine::countMessages(QMessageServicePrivate& privateService, const QMessageFilter &filter)
{
    TRAPD(err, countMessagesL(privateService, filter));
    if (err != KErrNone) {
        return false;
    }
    return true;
}

void CFSEngine::countMessagesL(QMessageServicePrivate& privateService, const QMessageFilter &filter)
{
    TRAP_IGNORE(updateEmailAccountsL());

    FSMessageQueryInfo queryInfo;
    queryInfo.operationId = ++m_operationIds;
    if (queryInfo.operationId == 100000) {
        queryInfo.operationId = 1;
    }
    queryInfo.isQuery = false;
    queryInfo.body = QString();
    queryInfo.matchFlags = 0;
    queryInfo.filter = filter;
    queryInfo.sortOrder = QMessageSortOrder();
    queryInfo.offset = 0;
    queryInfo.limit = 0;
    queryInfo.findOperation = new CFSMessagesFindOperation((CFSEngine&)*this, queryInfo.operationId);
    queryInfo.privateService = &privateService;
    queryInfo.currentFilterListIndex = 0;
    queryInfo.count = 0;
    queryInfo.canceled = false;
    m_messageQueries.append(queryInfo);
    
    handleNestedFiltersFromMessageFilter(m_messageQueries[m_messageQueries.count()-1].filter);
    
    doNextQuery();
}

void CFSEngine::doNextQuery() const
{
    int retVal = KErrNone;
    while (m_messageQueries.count() && !m_messageQueryActive) {
        if (m_messageQueries[0].canceled) {
            delete m_messageQueries[0].findOperation;
            m_messageQueries.removeAt(0);
        } else {
            m_messageQueryActive = true;
            QMessageFilterPrivate* pf = QMessageFilterPrivate::implementation(m_messageQueries[0].filter); 
            if (pf->_filterList.count() == 0) {
                retVal = m_messageQueries[0].findOperation->filterAndOrderMessages(m_messageQueries[0].filter,
                                                                                   m_messageQueries[0].sortOrder,
                                                                                   m_messageQueries[0].body,
                                                                                   m_messageQueries[0].matchFlags);
            } else {
                retVal = m_messageQueries[0].findOperation->filterAndOrderMessages(pf->_filterList[0],
                                                                                   m_messageQueries[0].sortOrder,
                                                                                   m_messageQueries[0].body,
                                                                                   m_messageQueries[0].matchFlags);
            }
            if (retVal != KErrNone) {
                // filtering & ordering failed
                if (m_messageQueries[0].isQuery) {
                    // => return empty id list
                    m_messageQueries[0].privateService->messagesFound(QMessageIdList(), false, false);
                } else {
                    // => return 0 as count
                    m_messageQueries[0].privateService->messagesCounted(0);
                }
                
                m_messageQueryActive = false;
                delete m_messageQueries[0].findOperation;
                m_messageQueries.removeAt(0);
            }
        }
    }
}

void CFSEngine::filterAndOrderMessagesReady(bool success, int operationId, QMessageIdList ids, int numberOfHandledFilters,
                                            bool resultSetOrdered)
{
    int index=0;
    for (; index < m_messageQueries.count(); index++) {
        if (m_messageQueries[index].operationId == operationId) {
            break;
        }
    }
    
    if (m_messageQueries[index].canceled) {
        m_messageQueryActive = false;
        delete m_messageQueries[index].findOperation;
        m_messageQueries.removeAt(index);
        
        doNextQuery();
        return;
    }    
    
    if (success) {
        // If there are unhandled filters, loop through all filters and do filtering for ids using unhandled filters.
        QMessageFilterPrivate* pf = QMessageFilterPrivate::implementation(m_messageQueries[index].filter);
        if (pf->_filterList.count() > 0) {
            if (pf->_filterList[m_messageQueries[index].currentFilterListIndex].count() > numberOfHandledFilters) {
                for (int i=0; i < ids.count(); i++) {
                    QMessage msg = message(ids[i]);
                    for (int j=numberOfHandledFilters; j < pf->_filterList[m_messageQueries[index].currentFilterListIndex].count(); j++) {
                        QMessageFilterPrivate* pf2 = QMessageFilterPrivate::implementation(pf->_filterList[m_messageQueries[index].currentFilterListIndex][j]);
                        if (!pf2->filter(msg)) {
                            ids.removeAt(i);
                            i--;
                            break;
                        }
                    }
                }
            }
        }
        if (pf->_filterList.count() > 0) {
            // Filter contains filterlist (or filterlists), not just one single filter 
            if (m_messageQueries[index].currentFilterListIndex == 0) {
                m_messageQueries[index].ids << ids;
                m_messageQueries[index].count = ids.count(); 
            } else {
                // Append new ids to resultset
                for (int i=0; i < ids.count(); i++) {
                    if (!m_messageQueries[index].ids.contains(ids[i])) {
                        m_messageQueries[index].ids.append(ids[i]);
                        m_messageQueries[index].count++;
                    }
                }
            }
            
            m_messageQueries[index].currentFilterListIndex++;
            if (m_messageQueries[index].currentFilterListIndex < pf->_filterList.count()) {
                // There are still unhandled filter lists left
                int retVal = m_messageQueries[index].findOperation->filterAndOrderMessages(pf->_filterList[m_messageQueries[index].currentFilterListIndex],
                                                                                           m_messageQueries[index].sortOrder,
                                                                                           m_messageQueries[index].body,
                                                                                           m_messageQueries[index].matchFlags);
                if (retVal != KErrNone) {
                    filterAndOrderMessagesReady(false, operationId, QMessageIdList(), numberOfHandledFilters, false);
                }
                return;
            } else {
                // All filters successfully handled
                if (m_messageQueries[index].isQuery) {
                    if (!m_messageQueries[index].sortOrder.isEmpty()) {
                        // Make sure that messages are correctly ordered
                        orderMessages(m_messageQueries[index].ids, m_messageQueries[index].sortOrder);
                    }
                    applyOffsetAndLimitToMsgIds(m_messageQueries[index].ids,
                                                m_messageQueries[index].offset,
                                                m_messageQueries[index].limit);
                    m_messageQueries[index].privateService->messagesFound(m_messageQueries[index].ids, true, true);
                } else {
                    m_messageQueries[index].privateService->messagesCounted(m_messageQueries[index].count);
                }
            }
        } else {
            // There was only one single filter to handle
            if (numberOfHandledFilters == 0) {
                // The one and only filter was not handled
                // => Do filtering for all returned messages
                for (int i=ids.count()-1; i >= 0; i--) {
                    QMessage msg = message(ids[i]);
                    if (!pf->filter(msg)) {
                        ids.removeAt(i);
                    }
                }
            }
            // => All filters successfully handled
            if (m_messageQueries[index].isQuery) {
                // Make sure that messages are correctly ordered
                if (!m_messageQueries[index].sortOrder.isEmpty() && !resultSetOrdered) {
                    MessagingHelper::orderMessages(ids, m_messageQueries[index].sortOrder);
                }
                // Handle offest & limit
                applyOffsetAndLimitToMsgIds(ids, m_messageQueries[index].offset, m_messageQueries[index].limit);
                m_messageQueries[index].privateService->messagesFound(ids, true, true);
            } else {
                m_messageQueries[index].privateService->messagesCounted(ids.count());
            }
        }
    } else {
        // filtering & ordering failed
        if (m_messageQueries[index].isQuery) {
            // => return empty id list
            m_messageQueries[index].privateService->messagesFound(QMessageIdList(), false, false);
        } else {
            // => return 0 as count
            m_messageQueries[index].privateService->messagesCounted(0);
        }
    }

    m_messageQueryActive = false;
    delete m_messageQueries[index].findOperation;
    m_messageQueries.removeAt(index);
    
    doNextQuery();
}


void CFSEngine::cancel(QMessageServicePrivate& privateService)
{
    for (int i=0; i < m_messageQueries.count(); i++) {
        if (m_messageQueries[i].privateService == &privateService) {
            m_messageQueries[i].canceled = true;
        }
    }

    CFSContentFetchOperation* cfOp = m_contentFetchOperations.take(&privateService);
    if (cfOp) {
        cfOp->cancelFetch();
        delete cfOp;
    }

    foreach (EMailSyncRequest* req, m_syncRequests) {
        if (&req->m_observer == &privateService) {
            req->m_active = false;
            MEmailMailbox* mailbox = m_mailboxes.value(req->m_mailboxId.iId);
            if (mailbox) {
                mailbox->CancelSynchronise();
            }
        }
    }
    
#ifdef FREESTYLEMAILMAPI12USED
    CFSContentStructureFetchOperation* csfOp = m_contentStructurefetchOperations.take(&privateService);
    if (csfOp) {
        csfOp->cancelFetch();
        delete csfOp;
    }

    // cancel move requests
    QMap<uint, EMailMoveRequest>::iterator i( m_moveRequests.begin() );
    while( i != m_moveRequests.end() ) {
        EMailMoveRequest req( i.value() );
        if( req.m_observer == &privateService ) {
            MEmailMailbox* mailbox = m_mailboxes.value(req.m_mailbox.iId);
            if( mailbox ) {
                TRAP_IGNORE( mailbox->CancelMoveL( i.key() ) );
            }
            i = m_moveRequests.erase( i );
        } else {
            i++;
        }
    }
#endif
}

void CFSEngine::applyOffsetAndLimitToMsgIds(QMessageIdList& idList, int offset, int limit) const
{
    if (offset > 0) {
        if (offset > idList.count()) {
            idList.clear();
        } else {
            for (int i = 0; i < offset; i++) {
                idList.removeFirst();
            }
        }
    }
    if (limit > 0) {
        for (int i = idList.count()-1; i >= limit; i--) {
            idList.removeAt(i);
        }
    }
}

QMessageManager::NotificationFilterId CFSEngine::registerNotificationFilter(QMessageStorePrivate& aPrivateStore,
                                                                           const QMessageFilter &filter, QMessageManager::NotificationFilterId aId)
{
    if (QCoreApplication::instance() && QCoreApplication::instance()->thread() != QThread::currentThread()) {
        if (this != applicationThreadFsEngine()) {
            return applicationThreadFsEngine()->registerNotificationFilter(aPrivateStore, filter, aId);
        }
    }

    ipMessageStorePrivate = &aPrivateStore;
    iListenForNotifications = true;    

    int filterId = aId;
    if (filterId == 0)
        filterId = ++m_filterId;
    m_filters.insert(filterId, filter);
    return filterId;
}

void CFSEngine::unregisterNotificationFilter(QMessageManager::NotificationFilterId notificationFilterId)
{
    if (QCoreApplication::instance() && QCoreApplication::instance()->thread() != QThread::currentThread()) {
        if (this != applicationThreadFsEngine()) {
            return applicationThreadFsEngine()->unregisterNotificationFilter(notificationFilterId);
        }
    }

    m_filters.remove(notificationFilterId);
    if (m_filters.count() == 0) {
        iListenForNotifications = false;
    }
}
void CFSEngine::handleNestedFiltersFromFolderFilter(QMessageFolderFilter &filter) const
{
    QMessageFolderFilterPrivate* pMFFilter = QMessageFolderFilterPrivate::implementation(filter);
    if (pMFFilter->_filterList.count() > 0) {
        int filterListCount = pMFFilter->_filterList.count();
        for (int i=0; i < filterListCount; i++) {
            for (int j=0; j < pMFFilter->_filterList[i].count(); j++) {
                QMessageFolderFilterPrivate* pMFFilter2 = QMessageFolderFilterPrivate::implementation(pMFFilter->_filterList[i][j]);
                if (pMFFilter2->_field == QMessageFolderFilterPrivate::ParentAccountIdFilter) {
                    QMessageAccountIdList accountIds = queryAccounts(*pMFFilter2->_accountFilter, QMessageAccountSortOrder(), 0, 0);
                    QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter2->_comparatorValue));
                    if (accountIds.count() > 0) {
                        pMFFilter->_filterList[i].removeAt(j);
                        if (cmp == QMessageDataComparator::Includes) {
                            for (int x = 0; x < accountIds.count(); x++) {
                                if (x == 0) {
                                    if (x+1 < accountIds.count()) {
                                        pMFFilter->_filterList.append(pMFFilter->_filterList[i]);
                                    }
                                    pMFFilter->_filterList[i].append(QMessageFolderFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal));
                                    qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFolderFilterPrivate::lessThan);
                                } else {
                                    if (x+1 < accountIds.count()) {
                                        pMFFilter->_filterList.append(pMFFilter->_filterList[pMFFilter->_filterList.count()-1]);
                                        pMFFilter->_filterList[pMFFilter->_filterList.count()-2].append(QMessageFolderFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal));
                                        qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-2].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-2].end(), QMessageFolderFilterPrivate::lessThan);
                                    } else {
                                        pMFFilter->_filterList[pMFFilter->_filterList.count()-1].append(QMessageFolderFilter::byParentAccountId(accountIds[x],QMessageDataComparator::Equal));
                                        qSort(pMFFilter->_filterList[pMFFilter->_filterList.count()-1].begin(), pMFFilter->_filterList[pMFFilter->_filterList.count()-1].end(), QMessageFolderFilterPrivate::lessThan);
                                    }
                                }
                            }
                        } else { // Excludes
                            for (int x = 0; x < accountIds.count(); x++) {
                                pMFFilter->_filterList[i].append(QMessageFolderFilter::byParentAccountId(accountIds[x],QMessageDataComparator::NotEqual));
                            }
                            qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFolderFilterPrivate::lessThan);
                        }
                    } else {
                        delete pMFFilter2->_accountFilter;
                        pMFFilter2->_accountFilter = 0;
                        pMFFilter2->_field = QMessageFolderFilterPrivate::Id;
                        qSort(pMFFilter->_filterList[i].begin(), pMFFilter->_filterList[i].end(), QMessageFolderFilterPrivate::lessThan);
                    }
                } else {
                    break;
                }
            }
        }
    } else {
        if (pMFFilter->_field == QMessageFolderFilterPrivate::ParentAccountIdFilter) {
            QMessageAccountIdList accountIds = queryAccounts(*pMFFilter->_accountFilter, QMessageAccountSortOrder(), 0, 0);
            QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pMFFilter->_comparatorValue));
            if (accountIds.count() > 0) {
                for (int i=0; i < accountIds.count(); i++) {
                    if (i == 0) {
                        delete pMFFilter->_accountFilter;
                        pMFFilter->_accountFilter = 0;
                        pMFFilter->_field = QMessageFolderFilterPrivate::ParentAccountId;
                        pMFFilter->_value = accountIds[0].toString();
                        pMFFilter->_comparatorType = QMessageFolderFilterPrivate::Equality;
                        if (cmp == QMessageDataComparator::Includes) {
                            pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::Equal);
                        } else { // Excludes
                            pMFFilter->_comparatorValue = static_cast<int>(QMessageDataComparator::NotEqual);
                        }
                    } else {
                        if (cmp == QMessageDataComparator::Includes) {
                            filter |= QMessageFolderFilter::byParentAccountId(accountIds[i],QMessageDataComparator::Equal);
                        } else { // Excludes
                            filter &= QMessageFolderFilter::byParentAccountId(accountIds[i],QMessageDataComparator::NotEqual);
                        }
                    }
                }
            } else {
                delete pMFFilter->_accountFilter;
                pMFFilter->_accountFilter = 0;
                pMFFilter->_field = QMessageFolderFilterPrivate::Id;
            }
        }
    }
}

QMessageFolderIdList CFSEngine::queryFolders(const QMessageFolderFilter &filter, const QMessageFolderSortOrder &sortOrder, uint limit, uint offset) const
{
    QMessageFolderIdList ids;
    
    QMessageFolderFilter copyOfFilter = filter;

    handleNestedFiltersFromFolderFilter(copyOfFilter);
    
    QMessageFolderFilterPrivate* pMFFilter = QMessageFolderFilterPrivate::implementation(copyOfFilter);

    if (pMFFilter->_filterList.count() > 0) {
        for (int i=0; i < pMFFilter->_filterList.count(); i++) {
            bool filterHandled;
            QMessageFolderIdList ids2 = filterMessageFolders(pMFFilter->_filterList[i][0], filterHandled);
            for (int x=ids2.count()-1; x >= 0; x--) {
                QMessageFolder mf = folder(ids2[x]);
                int j = filterHandled ? 1 : 0;
                for (; j < pMFFilter->_filterList[i].count(); j++) {
                    if (!QMessageFolderFilterPrivate::implementation(pMFFilter->_filterList[i][j])->filter(mf)) {
                        ids2.removeAt(x);
                        break;
                    }
                }
            }
            for (int j=0; j < ids2.count(); j++) {
                if (!ids.contains(ids2[j])) {
                   ids.append(ids2[j]);
                }
            }
        }
    } else {
        bool filterHandled;
        ids = filterMessageFolders(copyOfFilter, filterHandled);
        if (!filterHandled) {
            for (int i=ids.count()-1; i >= 0; i--) {
                if (!QMessageFolderFilterPrivate::implementation(copyOfFilter)->filter(ids[i])) {
                    ids.removeAt(i);
                }
            }
        }
    }
    
    if (!sortOrder.isEmpty()) {
        orderFolders(ids, sortOrder);
    }
    
    applyOffsetAndLimitToMsgFolderIds(ids, offset, limit);
    
    return ids;
}

void CFSEngine::applyOffsetAndLimitToMsgFolderIds(QMessageFolderIdList& idList, int offset, int limit) const
{
    if (offset > 0) {
        if (offset > idList.count()) {
            idList.clear();
        } else {
            for (int i = 0; i < offset; i++) {
                idList.removeFirst();
            }
        }
    }
    if (limit > 0) {
        for (int i = idList.count()-1; i >= limit; i--) {
            idList.removeAt(i);
        }
    }
}

int CFSEngine::countFolders(const QMessageFolderFilter &filter) const
{
    return queryFolders(filter, QMessageFolderSortOrder(), 0, 0).count();
}

QMessageFolder CFSEngine::folder(const QMessageFolderId &id) const
{
    //return QMessageFolder();
    
    QMessageFolder folder;
    TRAPD(err, folder = folderL(id));
    Q_UNUSED(err)
       
    return folder;
}

QMessageFolder CFSEngine::folderL(const QMessageFolderId &id) const
{
    QMessageFolder folder;

    TFolderId folderId = fsFolderIdFromQMessageFolderId(id);
    MEmailMailbox* mailbox = NULL;
    TRAPD(err, mailbox = m_clientApi->MailboxL(folderId.iMailboxId));
    if (err == KErrNone) {
        MEmailFolder* fsFolder = NULL;
        TRAP(err, fsFolder = mailbox->FolderL(folderId));
        if (err == KErrNone) {
            QMessageFolderId parentId;
            QMessageAccountId accountId = qMessageAccountIdFromFsMailboxId(mailbox->MailboxId());
            QString name = QString::fromUtf16(fsFolder->Name().Ptr(), fsFolder->Name().Length());
            if (name.length() == 0) {
                switch (fsFolder->FolderType()) {
                case EInbox:
                    name = "Inbox";
                    break;
                case EOutbox:
                    name = "Outbox";
                    break;
                case EDrafts:
                    name = "Drafts";
                    break;
                case EDeleted:
                    name = "Deleted";
                    break;
                case ESent:
                    name = "Sent";
                    break;
                case EOther:
                    name = "Unknown";
                    break;
                default:
                    name = "Unknown";
                    break;
                }
            }
            folder = QMessageFolderPrivate::from(id, accountId, parentId, name, name);
            fsFolder->Release();
        }
        mailbox->Release();
    }

    return folder;
}

QMessageFolderIdList CFSEngine::filterMessageFolders(const QMessageFolderFilter& filter, bool& filterHandled) const
{
    QMessageFolderIdList ids;
    TRAPD(err, ids = filterMessageFoldersL(filter, filterHandled));
    Q_UNUSED(err)
    return ids;
}

QMessageFolderIdList CFSEngine::filterMessageFoldersL(const QMessageFolderFilter& filter, bool& filterHandled) const
{
    filterHandled = false;
    QMessageFolderIdList ids;
    
    if (filter.isEmpty()) {
        QMessageFolderFilterPrivate* pf = QMessageFolderFilterPrivate::implementation(filter);
        if (!pf->_notFilter) {
            ids = allFolders();
        }
        filterHandled = true;
    } else {
        QMessageFolderFilterPrivate* pf = QMessageFolderFilterPrivate::implementation(filter);
        if (!pf->_valid) {
            return QMessageFolderIdList();
        }
    
        switch (pf->_field) {
        case QMessageFolderFilterPrivate::Id:
            {
            if (pf->_comparatorType == QMessageFolderFilterPrivate::Equality) {
                QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue));
                if (pf->_value.toString().length() > QString(SymbianHelpers::mtmPrefix).length()) {
                    bool folderOk = false;
                    MEmailMailbox* mailbox = NULL;
                    MEmailFolder* folder = NULL;;
                    if (fsFolderL(QMessageFolderId(pf->_value.toString()), mailbox, folder)) {
                        folderOk = true;
                        // cleanup
                        folder->Release();
                        mailbox->Release();
                    }
                    if (cmp == QMessageDataComparator::Equal) {
                        if (folderOk) {
                            ids.append(QMessageFolderId(pf->_value.toString()));
                        }
                    } else { // NotEqual
                        ids = allFolders();
                        if (folderOk) {
                            ids.removeOne(QMessageFolderId(pf->_value.toString()));
                        }
                    }
                } else {
                    if (cmp == QMessageDataComparator::NotEqual) {
                        ids = allFolders();
                    }
                }
                filterHandled = true;
            } else if (pf->_comparatorType == QMessageFolderFilterPrivate::Inclusion) {
                QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue));
                if (pf->_ids.count() > 0) { // QMessageIdList
                    QMessageFolderIdList ids2;
                    for (int i=0; i < pf->_ids.count(); i++) {
                        MEmailMailbox* mailbox = NULL;
                        MEmailFolder* folder = NULL;
                        if (fsFolderL(QMessageFolderId(pf->_ids[i]), mailbox, folder)) {
                            ids2.append(pf->_ids[i]);
                            // cleanup
                            folder->Release();
                            mailbox->Release();
                        }
                    }
                    if (cmp == QMessageDataComparator::Includes) {
                        ids << ids2;
                    } else { // Excludes
                        ids = allFolders();
                        for (int i=0; i < ids2.count(); i++) {
                            ids.removeOne(ids2[i]);
                        }
                    }
                    filterHandled = true;
                } else {
                    // Empty QMessageIdList as a list
                    if (cmp == QMessageDataComparator::Excludes) {
                        ids = allFolders();
                    }
                    filterHandled = true;
                
                    // QMessageFilter 
                    /*if (cmp == QMessageDataComparator::Includes) {
                        // TODO:
                    } else { // Excludes
                        // TODO:
                    }*/
                }
            }
            break;
            }
        case QMessageFolderFilterPrivate::Name:
            {
            if (pf->_comparatorType == QMessageFolderFilterPrivate::Equality) {
                QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue));
                if (cmp == QMessageDataComparator::Equal) {
                    // TODO:
                } else { // NotEqual
                    // TODO:
                }
            } else if (pf->_comparatorType == QMessageFolderFilterPrivate::Inclusion) {
                QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue));
                if (cmp == QMessageDataComparator::Includes) {
                    // TODO:
                } else { // Excludes
                    if (pf->_value.toString().isEmpty() || pf->_value.toString().length() == 0) {
                        filterHandled = true;
                    }
                }
            }
            break;
            }
        case QMessageFolderFilterPrivate::Path:
            {
            if (pf->_comparatorType == QMessageFolderFilterPrivate::Equality) {
                QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue));
                if (cmp == QMessageDataComparator::Equal) {
                    // TODO:
                } else { // NotEqual
                    // TODO:
                }
            } else if (pf->_comparatorType == QMessageFolderFilterPrivate::Inclusion) {
                QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue));
                if (cmp == QMessageDataComparator::Includes) {
                    // TODO:
                } else { // Excludes
                    if (pf->_value.toString().isEmpty() || pf->_value.toString().length() == 0) {
                        filterHandled = true;
                    }
                }
            }
            break;
            }
        case QMessageFolderFilterPrivate::ParentAccountId:
            {
            if (pf->_comparatorType == QMessageFolderFilterPrivate::Equality) {
                QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue));
                if (cmp == QMessageDataComparator::Equal) {
                    if (pf->_value.toString().length() > 0) {
                        ids = folderIdsByAccountIdL(QMessageAccountId(pf->_value.toString()));
                    }
                } else { // NotEqual
                    ids = allFolders();
                    if (pf->_value.toString().length() > 0) {
                        QMessageFolderIdList ids2 = folderIdsByAccountIdL(QMessageAccountId(pf->_value.toString()));
                        for (int i = 0; i < ids2.count(); i++) {
                            ids.removeOne(ids2[i]);
                        }
                    }
                }
                filterHandled = true;
            } else if (pf->_comparatorType == QMessageFolderFilterPrivate::Inclusion) {
                QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue));
                if (cmp == QMessageDataComparator::Includes) {
                    // TODO:
                } else { // Excludes
                    // TODO:
                }
            }
            break;
            }
        case QMessageFolderFilterPrivate::ParentFolderId:
            {
            if (pf->_comparatorType == QMessageFolderFilterPrivate::Equality) {
                QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue));
                if (cmp == QMessageDataComparator::Equal) {
                    MEmailMailbox* mailbox = NULL;
                    MEmailFolder* parentFolder = NULL;
                    if (fsFolderL(QMessageFolderId(pf->_value.toString()), mailbox, parentFolder)) {
                        CleanupReleasePushL(*mailbox);
                        CleanupReleasePushL(*parentFolder);

                        RFolderArray subfolders;
                        CleanupClosePushL(subfolders);
                        parentFolder->GetSubfoldersL(subfolders);

                        for(TInt i=0; i < subfolders.Count(); i++) {
                            MEmailFolder *subFolder = subfolders[i];
                            ids.append(qMessageFolderIdFromFsFolderId(subFolder->FolderId()));
                            subFolder->Release();
                        }
                        
                        CleanupStack::PopAndDestroy(&subfolders);
                        CleanupStack::PopAndDestroy(parentFolder);
                        CleanupStack::PopAndDestroy(mailbox);
                    }
                } else { // NotEqual
                    // TODO:
                }
            } else if (pf->_comparatorType == QMessageFolderFilterPrivate::Inclusion) {
                QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue));
                if (cmp == QMessageDataComparator::Includes) {
                    // TODO:
                } else { // Excludes
                    // TODO:
                }
            }
            break;
            }
        case QMessageFolderFilterPrivate::AncestorFolderIds:
            {
                if (pf->_comparatorType == QMessageFolderFilterPrivate::Inclusion) {
                    QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue));
                    if (!pf->_value.isNull()) { // QMessageFolderId
                        if (cmp == QMessageDataComparator::Includes) {
                            // TODO:
                        } else { // Excludes
                            // TODO:
                        }
                    } else { // QMessageFolderFilter
                        if (cmp == QMessageDataComparator::Includes) {
                            // TODO:
                        } else { // Excludes
                            // TODO:
                        }
                    }
                }
                break;
            }
        case QMessageFolderFilterPrivate::ParentAccountIdFilter:
        case QMessageFolderFilterPrivate::None:
            break;        
        }
    }
    
    if (!filterHandled) {
        ids = allFolders();
    }

    return ids;
}


QMessageFolderIdList CFSEngine::allFolders() const
{
    QMessageFolderIdList ids;
    TRAPD(err, updateEmailAccountsL());
    Q_UNUSED(err)
    foreach (QMessageAccount value, m_accounts) {
        QMessageFolderIdList ids2 = folderIdsByAccountId(value.id());
        ids << ids2;
    }
    return ids;
}

QMessageFolderIdList CFSEngine::folderIdsByAccountId(const QMessageAccountId& accountId) const
{
    QMessageFolderIdList idList;
    TRAPD(err, idList << folderIdsByAccountIdL(accountId))
    Q_UNUSED(err);
    return idList;
}

QMessageFolderIdList CFSEngine::folderIdsByAccountIdL(const QMessageAccountId& accountId) const
{
    QMessageFolderIdList folderIds;
    
    if (idType(accountId) != EngineTypeFreestyle)
        return QMessageFolderIdList();
    
    QMessageAccount messageAccount = account(accountId);
    
    TMailboxId mailboxId = fsMailboxIdFromQMessageAccountId(accountId);
    MEmailMailbox* mailbox = NULL;
    mailbox = m_clientApi->MailboxL(mailboxId);

    if (mailbox == NULL)
        return QMessageFolderIdList();

    CleanupReleasePushL(*mailbox);

    RFolderArray folders;
    
    mailbox->GetFoldersL(folders);
    CleanupClosePushL(folders);

    for(TInt i=0; i < folders.Count(); i++) {
        MEmailFolder *mailFolder = folders[i];
        
        folderIds.append(qMessageFolderIdFromFsFolderId(mailFolder->FolderId()));

        //TODO: Support for subfolders?
        mailFolder->Release();
    }
    
    CleanupStack::PopAndDestroy(&folders);
    CleanupStack::PopAndDestroy(mailbox);
    
    return folderIds;
}

bool CFSEngine::fsFolderL(const QMessageFolderId& id, MEmailMailbox*& mailbox, MEmailFolder*& folder) const
{
    TFolderId folderId = fsFolderIdFromQMessageFolderId(id);
    TRAPD(err, mailbox = m_clientApi->MailboxL(folderId.iMailboxId));
    if (err == KErrNone) {
        TRAP(err, folder = mailbox->FolderL(folderId));
        if (err == KErrNone) {               
            return true;
        }
        mailbox->Release();
    }
    mailbox = NULL;
    folder = NULL;
    return false;
}


QMessage CFSEngine::message(const QMessageId& id) const
{
    QMessage msg = QMessage();

    MessageCache::instance()->lock();
    QMessage* msgPtr = MessageCache::instance()->messageObject(id.toString());
    if (msgPtr == NULL) {
        MessageCache::instance()->unlock();
        msgPtr = new QMessage();
        if (message(msgPtr, id)) {
            MessageCache::instance()->insertObject(msgPtr);
            msg = *msgPtr;
        } else {
            delete msgPtr;
        }
    } else {
        msg = *msgPtr;
        MessageCache::instance()->unlock();
    }

    return msg;
}

bool CFSEngine::message(QMessage* message, const QMessageId& id) const
{
    bool retVal = false;

    TMessageId messageId = fsMessageIdFromQMessageId(id);
    MEmailMailbox* mailbox = NULL;
    bool mailboxFoundFromCache = true;
    TInt err = KErrNone;
    mailbox = m_mailboxes.value(messageId.iFolderId.iMailboxId.iId);
    if (mailbox == NULL) {
        TRAP(err, mailbox = m_clientApi->MailboxL(messageId.iFolderId.iMailboxId.iId));
        mailboxFoundFromCache = false;
    }
    if (err == KErrNone) {
        MEmailMessage* fsMessage = NULL;
        TRAP(err, fsMessage = mailbox->MessageL(messageId));
        if (err == KErrNone && fsMessage) {
            TRAP(err, CreateQMessageL(message, *fsMessage));
            if (err == KErrNone) {
                retVal = true;
                QMessagePrivate* privateMessage = QMessagePrivate::implementation(*message);
                privateMessage->_id = id;
                privateMessage->_modified = false;
            }
            fsMessage->Release();
        }
        if (!mailboxFoundFromCache) {
            mailbox->Release();
        }
    }

    return retVal;
}

bool CFSEngine::sendEmail(QMessage &message)
{
    TMailboxId mailboxId(fsMailboxIdFromQMessageAccountId(message.parentAccountId()));
    MEmailMailbox* mailbox = NULL;
    TRAPD(mailerr, mailbox = m_clientApi->MailboxL(mailboxId));
    Q_UNUSED(mailerr);
    
    MEmailMessage* fsMessage = NULL;
    TRAPD(err,
        fsMessage = createFSMessageL(message, mailbox);
        fsMessage->SaveChangesL();
        fsMessage->SendL(); 
    );

    if (fsMessage)
        fsMessage->Release();
    if (mailbox)
        mailbox->Release();

    if (err != KErrNone)
        return false;
    else
        return true;
}

void CFSEngine::CreateQMessageL(QMessage* aQMessage, const MEmailMessage& aFSMessage) const
{
    if ( !aQMessage ) {
        User::Leave(KErrArgument);
    }
    QMessagePrivate* privateMessage = QMessagePrivate::implementation(*aQMessage);

    aQMessage->setType(QMessage::Email);

    aQMessage->setDate(symbianTTimetoQDateTime(aFSMessage.Date()));
    aQMessage->setReceivedDate(symbianTTimetoQDateTime(aFSMessage.Date()));

    const TFolderId& folderId = aFSMessage.ParentFolderId();
    aQMessage->setParentAccountId(qMessageAccountIdFromFsMailboxId(folderId.iMailboxId));
    privateMessage->_parentFolderId = qMessageFolderIdFromFsFolderId(folderId);
    privateMessage->_id = qMessageIdFromFsMessageId(aFSMessage.MessageId());

    MEmailMailbox* mailbox = NULL;
    bool mailboxFoundFromCache = true;
    mailbox = m_mailboxes.value(folderId.iMailboxId.iId);
    if (mailbox == NULL) {
        mailbox = m_clientApi->MailboxL(folderId.iMailboxId);
        mailboxFoundFromCache = false;
    }
    if (m_folderTypes.contains(folderId.iId)) {
        QMessagePrivate::setStandardFolder(*aQMessage, m_folderTypes.value(folderId.iId));
    } else {
        MEmailFolder* folder = mailbox->FolderL(folderId);
        QMessagePrivate::setStandardFolder(*aQMessage, QMessage::InboxFolder);
        if (folder->FolderType() == EDrafts) {
            QMessagePrivate::setStandardFolder(*aQMessage, QMessage::DraftsFolder);
        } else if (folder->FolderType() == EDeleted) {
            QMessagePrivate::setStandardFolder(*aQMessage, QMessage::TrashFolder);
        } else if (folder->FolderType() == ESent) {
            QMessagePrivate::setStandardFolder(*aQMessage, QMessage::SentFolder);
        }
        m_folderTypes.insert(folderId.iId, aQMessage->standardFolder());
        folder->Release();
    }
    if (!mailboxFoundFromCache) {
        mailbox->Release();
    }

    if (aFSMessage.Flags() & EFlag_Read) {
        privateMessage->_status = privateMessage->_status | QMessage::Read; 
    }

    if (aFSMessage.Flags() & EFlag_Important) {
        aQMessage->setPriority(QMessage::HighPriority);
    } else if (aFSMessage.Flags() & EFlag_Low) {
        aQMessage->setPriority(QMessage::LowPriority);
    } else {
        aQMessage->setPriority(QMessage::NormalPriority);
    }

    if (aFSMessage.Flags() & EFlag_Attachments) {
        privateMessage->_status = privateMessage->_status | QMessage::HasAttachments;
    }

    // Body & Attachments
    QMessageContentContainerPrivate* pContainer = QMessagePrivate::containerImplementation(*aQMessage);
    pContainer->_contentRetrieved = false;
    
    //from
    MEmailAddress* pSenderAddress = aFSMessage.SenderAddressL();
    if (pSenderAddress) {
        TPtrC from = pSenderAddress->Address();
        TPtrC displayname = pSenderAddress->DisplayName();
        if (from.Length() > 0) {
            QString qAddress;
            convertFreestyleAddressToQString(pSenderAddress, qAddress);
            aQMessage->setFrom(QMessageAddress(QMessageAddress::Email, qAddress));
            QMessagePrivate::setSenderName(*aQMessage, QString::fromUtf16(displayname.Ptr(), displayname.Length()));
        }
    }
    
    //to
    REmailAddressArray toRecipients;
    CleanupResetAndRelease<MEmailAddress>::PushL(toRecipients);

    aFSMessage.GetRecipientsL(MEmailAddress::ETo, toRecipients);
    QList<QMessageAddress> toList;
    for(TInt i = 0; i < toRecipients.Count(); i++) {
        QString qAddress;
        convertFreestyleAddressToQString(toRecipients[i], qAddress);
        toList.append(QMessageAddress(QMessageAddress::Email, qAddress));
    }
    aQMessage->setTo(toList);
    CleanupStack::PopAndDestroy(&toRecipients);
    toRecipients.Close();
    
    //cc
    REmailAddressArray ccRecipients;
    CleanupResetAndRelease<MEmailAddress>::PushL(ccRecipients);
    aFSMessage.GetRecipientsL(MEmailAddress::ECc, ccRecipients);
    QList<QMessageAddress> ccList;
    for(TInt i = 0; i < ccRecipients.Count(); i++) {
        QString qAddress;
        convertFreestyleAddressToQString(ccRecipients[i], qAddress);
        ccList.append(QMessageAddress(QMessageAddress::Email, qAddress));
    }
    aQMessage->setCc(ccList);
    CleanupStack::PopAndDestroy(&ccRecipients);
    ccRecipients.Close();
    
    //bcc
    REmailAddressArray bccRecipients;
    CleanupResetAndRelease<MEmailAddress>::PushL(bccRecipients);
    aFSMessage.GetRecipientsL(MEmailAddress::EBcc, bccRecipients);
    QList<QMessageAddress> bccList;
    for(TInt i = 0; i < bccRecipients.Count(); i++) {
        QString qAddress;
        convertFreestyleAddressToQString(bccRecipients[i], qAddress);
        bccList.append(QMessageAddress(QMessageAddress::Email, qAddress));
    }
    aQMessage->setBcc(bccList);
    CleanupStack::PopAndDestroy(&bccRecipients);
    bccRecipients.Close();
    
    // Read message subject   
    TPtrC subject = aFSMessage.Subject();
    if (subject.Length() > 0) {
        aQMessage->setSubject(QString::fromUtf16(subject.Ptr(), subject.Length()));
    }
}

void CFSEngine::retrieveMessageContentHeaders(QMessage& message) const
{
    MessageCache::instance()->lock();
    QMessage* msgPtr = MessageCache::instance()->messageObject(message.id().toString());
    if (msgPtr == NULL) {
        MessageCache::instance()->unlock();
        msgPtr = new QMessage();
        if (this->message(msgPtr, message.id())) {
            MessageCache::instance()->insertObject(msgPtr);
        } else {
            delete msgPtr;
            return; // Just giving up. Should we throw std::bad_alloc here?
        }
        MessageCache::instance()->lock();
    }

    QMessageContentContainerPrivate* pContainer = QMessagePrivate::containerImplementation(*msgPtr);
    pContainer->_contentRetrieved = true;

    bool contentHeadersRetrieved = false;
    TMessageId messageId = fsMessageIdFromQMessageId(message.id());
    MEmailMailbox* mailbox = NULL;
    TRAPD(err, mailbox = m_clientApi->MailboxL(messageId.iFolderId.iMailboxId.iId));
    if (err == KErrNone) {
        MEmailMessage* pEmailMessage = NULL;
        TRAP(err, pEmailMessage = mailbox->MessageL(messageId));
        if (err == KErrNone) {
            addMessagePartsToQMessage(*msgPtr, *pEmailMessage);
            contentHeadersRetrieved = true;
            pEmailMessage->Release();
        }
        mailbox->Release();
    }

    if (contentHeadersRetrieved) {
        message = *msgPtr;
    }

    MessageCache::instance()->unlock();
}

void CFSEngine::addMessagePartsToQMessage(QMessage& message, MEmailMessage& mEmailMessage) const
{
    int size = 0;
    QByteArray mimeType;
    QByteArray mimeSubType;
    QByteArray charset;

    TMessageId msgId = mEmailMessage.MessageId();

    MEmailMessageContent* pContent = NULL;
    TRAPD(err, pContent = mEmailMessage.ContentL());
    if ((err == KErrNone) && pContent) {
        // Message MIME type
        QByteArray mimeHeader = QString::fromUtf16(pContent->ContentType().Ptr(),
                                                   pContent->ContentType().Length()).toAscii();
        MessagingHelper::extractMIMEHeaderParts(mimeHeader, mimeType, mimeSubType, charset);
        QMessageContentContainerPrivate* container = QMessagePrivate::containerImplementation(message);
        container->_type = mimeType;
        container->_subType = mimeSubType;
        addContentToQMessage(message, *pContent, msgId);
        size = pContent->TotalSize();
        pContent->Release();
    }
    else {
        // Attachments
        REmailAttachmentArray attachments;
        TInt count = mEmailMessage.GetAttachmentsL(attachments);
        for (int i=0; i < attachments.Count(); i++) {
            QByteArray fileName;
            TPtrC fName(KNullDesC);
            TRAPD(err, fName.Set(attachments[i]->FileNameL()));
            if (err == KErrNone) {
                fileName = QString::fromUtf16(fName.Ptr(), fName.Length()).toUtf8();
            }
            QByteArray mimeHeader = QString::fromUtf16(attachments[i]->ContentType().Ptr(),
                                                       attachments[i]->ContentType().Length()).toAscii();
            MessagingHelper::extractMIMEHeaderParts(mimeHeader, mimeType, mimeSubType, charset);
            int attachmentSize = attachments[i]->TotalSize();
            size += attachmentSize;
            QMessageContentContainer attachment = QMessageContentContainerPrivate::from(msgId.iId,
                                                                                        1,
                                                                                        fileName, mimeType,
                                                                                        mimeSubType, attachmentSize,
                                                                                        attachments[i]->Id());
            QMessageContentContainerPrivate *attachmentContainer = QMessageContentContainerPrivate::implementation(attachment);
            attachmentContainer->_freestyleAttachment = true;
            if (attachments[i]->TotalSize() == attachments[i]->AvailableSize()) {
                attachmentContainer->_available = true;
            } else {
                attachmentContainer->_available = false;
            }
            addAttachmentToQMessage(message, attachment);
            attachments[i]->Release();
        }
        attachments.Reset();
    }

    QMessagePrivate* pPrivateMessage = QMessagePrivate::implementation(message);
    pPrivateMessage->_size = size;
}

void CFSEngine::addContentToQMessage(QMessage& message, const MEmailMessageContent &content, TMessageId messageId) const
{
    MEmailMultipart* pMultipart = content.AsMultipartOrNull();
    if (pMultipart) {
        TInt partCount = 0;
        TRAPD(err, partCount = pMultipart->PartCountL());
        if (err == KErrNone) {
            for (TInt i = 0; i < partCount; i++) {
                MEmailMessageContent* pContent = NULL;
                TRAP(err, pContent = pMultipart->PartByIndexL(i));
                if (err == KErrNone) {
                    addContentToQMessage(message, *pContent, messageId);
                    pContent->Release();
                }
            }
        }
        return;
    }

    QByteArray mimeType;
    QByteArray mimeSubType;
    QByteArray charset;

    MEmailTextContent* pTextContent = content.AsTextContentOrNull();
    if (pTextContent) {
        QMessagePrivate* pPrivateMessage = QMessagePrivate::implementation(message);
        QMessageContentContainerPrivate* pContainer = QMessagePrivate::containerImplementation(message);
        QMessageContentContainerId existingBodyId(message.bodyId());

        QByteArray mimeHeader = QString::fromUtf16(pTextContent->ContentType().Ptr(),
                                                   pTextContent->ContentType().Length()).toAscii();
        MessagingHelper::extractMIMEHeaderParts(mimeHeader, mimeType, mimeSubType, charset);
        if (charset.isEmpty()) {
            charset = "UTF-8";
        }
        if (existingBodyId.isValid()) {
            if (existingBodyId == QMessageContentContainerPrivate::bodyContentId()) {
                // The body content is in the message itself
                if (!pContainer->_attachmentId || (pTextContent->TextType() == MEmailTextContent::EPlainText)) {
                    pContainer->_fsContentId = pTextContent->Id();
                    pContainer->_attachmentId = 1;
                    pContainer->_containingMessageId = messageId.iId;
                    pContainer->_name = QByteArray();
                    pContainer->_type = mimeType;
                    pContainer->_subType = mimeSubType;
                    pContainer->_charset = charset;
                    pContainer->_size = pTextContent->TotalSize();
                    pContainer->_freestyleAttachment = true;
                    if (pTextContent->TotalSize() == pTextContent->AvailableSize()) {
                        pContainer->_available = true;
                    } else {
                        pContainer->_available = false;
                    }
                }
            } else {
                // The body content is in the first attachment
                QMessageContentContainerPrivate *pAttachmentContainer(QMessageContentContainerPrivate::implementation(*pContainer->attachment(existingBodyId)));
                if (!pAttachmentContainer->_attachmentId || (pTextContent->TextType() == MEmailTextContent::EPlainText)) {
                    pAttachmentContainer->_fsContentId = pTextContent->Id();
                    pAttachmentContainer->_attachmentId = 1;
                    pAttachmentContainer->_containingMessageId = messageId.iId;
                    pAttachmentContainer->_name = QByteArray();
                    pAttachmentContainer->_type = mimeType;
                    pAttachmentContainer->_subType = mimeSubType;
                    pAttachmentContainer->_charset = charset;
                    pAttachmentContainer->_size = pTextContent->TotalSize();
                    pAttachmentContainer->_freestyleAttachment = true;
                    if (pTextContent->TotalSize() == pTextContent->AvailableSize()) {
                        pAttachmentContainer->_available = true;
                    } else {
                        pAttachmentContainer->_available = false;
                    }
                }
            }
        } else {
            if (pContainer->_attachments.isEmpty()) {
                // Put the content directly into the message
                pContainer->_fsContentId = pTextContent->Id();
                pContainer->_attachmentId = 1;
                pContainer->_containingMessageId = messageId.iId;
                pContainer->_name = QByteArray();
                pContainer->_type = mimeType;
                pContainer->_subType = mimeSubType;
                pContainer->_charset = charset;
                pContainer->_size = pTextContent->TotalSize();
                pContainer->_freestyleAttachment = true;
                if (pTextContent->TotalSize() == pTextContent->AvailableSize()) {
                    pContainer->_available = true;
                } else {
                    pContainer->_available = false;
                }
                pPrivateMessage->_bodyId = QMessageContentContainerPrivate::bodyContentId();
            } else {
                // Add the body as the first attachment
                QMessageContentContainer newBody;
                QMessageContentContainerPrivate *pAttachmentContainer = QMessageContentContainerPrivate::implementation(newBody);
                pAttachmentContainer->_fsContentId = pTextContent->Id();
                pAttachmentContainer->_attachmentId = 1;
                pAttachmentContainer->_containingMessageId = messageId.iId;
                pAttachmentContainer->_name = QByteArray();
                pAttachmentContainer->_type = mimeType;
                pAttachmentContainer->_subType = mimeSubType;
                pAttachmentContainer->_charset = charset;
                pAttachmentContainer->_size = pTextContent->TotalSize();
                pAttachmentContainer->_freestyleAttachment = true;
                if (pTextContent->TotalSize() == pTextContent->AvailableSize()) {
                    pAttachmentContainer->_available = true;
                } else {
                    pAttachmentContainer->_available = false;
                }
                pPrivateMessage->_bodyId = pContainer->prependContent(newBody);
            }
        }
    }

    MEmailAttachment* pAttachment = content.AsAttachmentOrNull();
    if (pAttachment) {
        QByteArray fileName;
        TPtrC fName(KNullDesC);
        TRAPD(err, fName.Set(pAttachment->FileNameL()));
        if (err == KErrNone) {
            fileName = QString::fromUtf16(fName.Ptr(), fName.Length()).toUtf8();
        }
        QByteArray mimeHeader = QString::fromUtf16(pAttachment->ContentType().Ptr(),
                                                   pAttachment->ContentType().Length()).toAscii();
        MessagingHelper::extractMIMEHeaderParts(mimeHeader, mimeType, mimeSubType, charset);
        int size = pAttachment->TotalSize();
        QMessageContentContainer attachment = QMessageContentContainerPrivate::from(messageId.iId,
                                                                                    1,
                                                                                    fileName, mimeType,
                                                                                    mimeSubType,
                                                                                    size,
                                                                                    pAttachment->Id());
        QMessageContentContainerPrivate *attachmentContainer = QMessageContentContainerPrivate::implementation(attachment);
        attachmentContainer->_freestyleAttachment = true;
        if (pAttachment->TotalSize() == pAttachment->AvailableSize()) {
            attachmentContainer->_available = true;
        } else {
            attachmentContainer->_available = false;
        }
        addAttachmentToQMessage(message, attachment);
    }

    QMessageContentContainerPrivate* pContainer = QMessagePrivate::containerImplementation(message);
}

void CFSEngine::addAttachmentToQMessage(QMessage& message, QMessageContentContainer& attachment) const
{
    QMessagePrivate* privateMessage = QMessagePrivate::implementation(message);
    QMessageContentContainerPrivate* container = QMessagePrivate::containerImplementation(message);
    
    if (container->_attachments.isEmpty()) {
        QMessageContentContainerId existingBodyId(message.bodyId());
        if (existingBodyId == QMessageContentContainerPrivate::bodyContentId()) {
            // The body content is in the message itself - move it to become the first attachment
            QMessageContentContainer newBody(message);
            QMessageContentContainerPrivate::implementation(newBody)->setDerivedMessage(0);
    
            container->setContentType("multipart", "mixed", "");
            privateMessage->_bodyId = container->prependContent(newBody);
        } else {
            // This message is now multipart
            container->setContentType("multipart", "mixed", "");
        }
    
        container->_available = true;
    }
    
    container->appendContent(attachment);
    
    bool haveAttachments = !container->_attachments.isEmpty();
    message.setStatus(QMessage::HasAttachments,haveAttachments);
    
    privateMessage->_modified = true;
}

QString CFSEngine::attachmentTextContent(long int messageId, TMessageContentId attachmentContentId,
                                         const QByteArray &charset) const
{
    QString result;

    QByteArray data = attachmentContent(messageId, attachmentContentId);
    if (!data.isEmpty()) {
        // Convert attachment data to string form
        QTextCodec *codec;
        if (!charset.isEmpty()) {
            codec = QTextCodec::codecForName(charset);
        } else {
            codec = QTextCodec::codecForLocale();
        }

        if (codec) {
            result = codec->toUnicode(data);
        }
    } else {
        result = bodyContent(messageId, attachmentContentId);
    }

    return result;
}

QByteArray CFSEngine::attachmentContent(long int messageId, TMessageContentId attachmentContentId) const
{
    QByteArray content;

    MEmailAttachment* attachment = attachmentById(attachmentContentId);
    if (attachment) {
        TRAP_IGNORE(
            RFile file = attachment->FileL();
            CleanupClosePushL(file);
            TInt fileSize = 0;
            file.Size(fileSize);
            if (fileSize != 0) {
                HBufC8* pContentBuf = HBufC8::NewLC(fileSize);
                TPtr8 contentBuf = pContentBuf->Des();
                if (file.Read(0, contentBuf, fileSize) == KErrNone) {
                    content = QByteArray((char*)pContentBuf->Ptr(), pContentBuf->Length());
                }
                CleanupStack::PopAndDestroy(pContentBuf);
            }
            CleanupStack::PopAndDestroy(&file);
        );
        attachment->Release();
    }

    return content;
}

MEmailAttachment* CFSEngine::attachmentById(TMessageContentId attachmentId) const
{
    MEmailAttachment* attachment = NULL;

    MEmailMailbox* mailbox = NULL;
    TRAPD(err, mailbox = m_clientApi->MailboxL(attachmentId.iMessageId.iFolderId.iMailboxId));
    if (err == KErrNone) {
        MEmailMessage* pEmailMessage = NULL;
        TRAP(err, pEmailMessage = mailbox->MessageL(attachmentId.iMessageId));
        if (err == KErrNone) {
            REmailAttachmentArray attachments;
            TRAP(err, pEmailMessage->GetAttachmentsL(attachments));
            if (err == KErrNone) {
                for (int i=0; i < attachments.Count(); i++) {
                    if (attachments[i]->Id() == attachmentId) {
                        attachment = attachments[i];
                    } else {
                        attachments[i]->Release();
                    }
                }
                attachments.Close();
            }
            pEmailMessage->Release();
        }
        mailbox->Release();
    }

    return attachment;
}

MEmailTextContent* CFSEngine::textContentById(TMessageContentId contentId, MEmailMessageContent* content) const
{
    MEmailTextContent* retContent = NULL;

    if (content) {
        MEmailMultipart* pMultipart = content->AsMultipartOrNull();
        if (pMultipart) {
            TInt partCount = 0;
            TRAP_IGNORE(partCount = pMultipart->PartCountL());
            for (TInt i = 0; i < partCount; i++) {
                MEmailMessageContent* pContent = NULL;
                TRAPD(err, pContent = pMultipart->PartByIndexL(i));
                if (err == KErrNone) {
                    retContent = textContentById(contentId, pContent);
                    if (retContent) {
                        pMultipart->Release();
                        break;
                    } else {
                        pContent->Release();
                    }
                }
            }
        } else {
            MEmailTextContent* pTextContent = content->AsTextContentOrNull();
            if (pTextContent) {
                if (pTextContent->Id() == contentId) {
                    retContent = pTextContent;
                }
            }
        }
    }

    return retContent;
}

QString CFSEngine::bodyContent(long int messageId, TMessageContentId bodyContentId) const
{
    QString content;

    MEmailMailbox* mailbox = NULL;
    TRAPD(err, mailbox = m_clientApi->MailboxL(bodyContentId.iMessageId.iFolderId.iMailboxId));
    if (err == KErrNone) {
        MEmailMessage* pEmailMessage = NULL;
        TRAP(err, pEmailMessage = mailbox->MessageL(bodyContentId.iMessageId));
        if (err == KErrNone) {
            MEmailMessageContent* emailContent = NULL;
            TRAP(err, emailContent = pEmailMessage->ContentL());
            if (err == KErrNone) {
                MEmailTextContent* bodyContent = textContentById(bodyContentId, emailContent);
                if (bodyContent) {
                    TPtrC contentPtr(KNullDesC);
                    TRAPD(err, contentPtr.Set(bodyContent->ContentL()));
                    if (err == KErrNone) {
                        content = QString::fromUtf16(contentPtr.Ptr(), contentPtr.Length());
                    }
                    bodyContent->Release();
                }
            }
            pEmailMessage->Release();
        }
        mailbox->Release();
    }

    return content;
}

QString CFSEngine::bodyContentFromMessageContent(const MEmailMessageContent& messageContent) const
{
    QString bodyContent;

    MEmailMultipart* pMultipart = messageContent.AsMultipartOrNull();
    if (pMultipart) {
        TInt partCount = 0;
        TRAP_IGNORE(partCount = pMultipart->PartCountL());
        for (TInt i = 0; i < partCount; i++) {
            MEmailMessageContent* pContent = NULL;
            TRAP_IGNORE(pContent = pMultipart->PartByIndexL(i));
            if (pContent) {
                bodyContent = bodyContentFromMessageContent(*pContent);
                pContent->Release();
            }
        }
        return bodyContent;
    }

    MEmailTextContent* pTextContent = messageContent.AsTextContentOrNull();
    if (pTextContent) {
        TPtrC content(KNullDesC);
        TRAPD(err, content.Set(pTextContent->ContentL()));
        if (err == KErrNone) {
            bodyContent = QString::fromUtf16(content.Ptr(), content.Length());
        }
    }

    return bodyContent;
}

QDateTime CFSEngine::symbianTTimetoQDateTime(const TTime& time) const
{
    TDateTime dateTime = time.DateTime();
    QDate qdate = QDate(dateTime.Year(), static_cast<int>(dateTime.Month())+1, dateTime.Day()+1);
    QTime qtime = QTime(dateTime.Hour(), dateTime.Minute(), dateTime.Second(), dateTime.MicroSecond()/1000 );
    return QDateTime(qdate, qtime, Qt::UTC);
}

TTime CFSEngine::qDateTimeToSymbianTTime(const QDateTime& date) const
{
    TDateTime dateTime;
    dateTime.SetYear(date.date().year());
    dateTime.SetMonth(static_cast<TMonth>(date.date().month()-1));
    dateTime.SetDay(date.date().day()-1);
    dateTime.SetHour(date.time().hour());
    dateTime.SetMinute(date.time().minute());
    dateTime.SetSecond(date.time().second());
    dateTime.SetMicroSecond(date.time().msec()*1000);
    return TTime(dateTime);
}

TFolderType CFSEngine::standardFolderId(QMessage::StandardFolder standardFolder)
{
    switch(standardFolder) {
        case QMessage::InboxFolder: return EInbox;
        case QMessage::OutboxFolder: return EOutbox;
        case QMessage::DraftsFolder: return EDrafts;
        case QMessage::SentFolder: return ESent;
        case QMessage::TrashFolder: return EDeleted;
        default: return EOther;
    }
}

TMessageId CFSEngine::fsMessageIdFromQMessageId(QMessageId messageId)
{
    TUint mailboxId = 0;
    TUint folderId = 0;
    TUint msgId = 0;

    QString messageIdString = stripIdPrefix(messageId.toString());
    int index = messageIdString.indexOf('_');
    if (index != -1) {
        mailboxId = messageIdString.left(index).toUInt();
        messageIdString = messageIdString.mid(index + 1);
        int index = messageIdString.indexOf('_');
        if (index != -1) {
            folderId = messageIdString.left(index).toUInt();
            msgId = messageIdString.mid(index + 1).toUInt();
        }
    }

    return TMessageId(msgId, folderId, mailboxId);
}

QMessageId CFSEngine::qMessageIdFromFsMessageId(TMessageId messageId)
{
    QString messageIdString;
    messageIdString = QString::number(messageId.iFolderId.iMailboxId.iId);
    messageIdString += "_" + QString::number(messageId.iFolderId.iId);
    messageIdString += "_" + QString::number(messageId.iId);
    return QMessageId(addIdPrefix(messageIdString, SymbianHelpers::EngineTypeFreestyle));
}

TFolderId CFSEngine::fsFolderIdFromQMessageFolderId(QMessageFolderId folderId)
{
    TUint mailboxId = 0;
    TUint fldrId = 0;

    QString folderIdString = stripIdPrefix(folderId.toString());
    int index = folderIdString.indexOf('_');
    if (index != -1) {
        mailboxId = folderIdString.left(index).toUInt();
        fldrId = folderIdString.mid(index + 1).toUInt();
    }

    return TFolderId(fldrId, mailboxId);
}

QMessageFolderId CFSEngine::qMessageFolderIdFromFsFolderId(TFolderId folderId)
{
    QString folderIdString;
    folderIdString = QString::number(folderId.iMailboxId.iId);
    folderIdString += "_" + QString::number(folderId.iId);
    return QMessageFolderId(addIdPrefix(folderIdString, SymbianHelpers::EngineTypeFreestyle));
}

TMailboxId CFSEngine::fsMailboxIdFromQMessageAccountId(QMessageAccountId accountId)
{
    return TMailboxId(stripIdPrefix(accountId.toString()).toUInt());
}

QMessageAccountId CFSEngine::qMessageAccountIdFromFsMailboxId(TMailboxId mailboxId)
{
    return QMessageAccountId(addIdPrefix(QString::number(mailboxId.iId), SymbianHelpers::EngineTypeFreestyle));
}

#ifdef FREESTYLEMAILMAPI12USED
void CFSEngine::contentStructureFetched(void* service, bool success)
{
    QMessageServicePrivate* pService = reinterpret_cast<QMessageServicePrivate*>(service);
    CFSContentStructureFetchOperation* op = m_contentStructurefetchOperations.take(pService);
    if (op) {
        if (success) {
            QMessageId id = qMessageIdFromFsMessageId(op->m_message->MessageId());
            // Make sure that new message contents will be updated to cache
            MessageCache::instance()->remove(id);
            pService->setFinished(true);
        } else {
            pService->setFinished(false);
        }
        delete op;
    }
}
#endif

void CFSEngine::contentFetched(void* service, bool success)
{
    QMessageServicePrivate* pService = reinterpret_cast<QMessageServicePrivate*>(service);
    CFSContentFetchOperation* op = m_contentFetchOperations.take(pService);
    if (op) {
        if (success) {
            QMessageId messageId = qMessageIdFromFsMessageId(op->m_content->Id().iMessageId);
            // Make sure that new message contents will be updated to cache
            MessageCache::instance()->remove(messageId.toString());
            pService->setFinished(true);
        } else {
            pService->setFinished(false);
        }
        delete op;
    }
}

void EMailSyncRequest::MailboxSynchronisedL(TInt aResult)
{
    m_requestList.removeOne(this);

    if (m_active) {
        bool result = (aResult == KErrNone);
        m_observer.setFinished(result);
    }
    
    delete this;
}

CFSContentFetchOperation::CFSContentFetchOperation(CFSEngine& parentEngine, QMessageServicePrivate& service,
                                                   MEmailMessageContent* content, MEmailMessage* message)
    : m_parentEngine(parentEngine),
      m_service(service),
      m_content(content),
      m_message(message)
{
}

CFSContentFetchOperation::~CFSContentFetchOperation()
{
    m_content->Release(); // Note: Cancels fetch if fetch is ongoing
    if (m_message) {
        m_message->Release();
    }
}

void CFSContentFetchOperation::cancelFetch()
{
    m_content->CancelFetch();
}

bool CFSContentFetchOperation::fetch()
{
    TRAPD(err, m_content->FetchL(*this));
    if (err != KErrNone) {
        return false;
    }
    return true;
}

void CFSContentFetchOperation::DataFetchedL(const TInt aResult)
{
    bool result = false;
    if (aResult == KErrNone) {
        result = true;
    }
    QMetaObject::invokeMethod(&m_parentEngine, "contentFetched", Qt::QueuedConnection,
                              Q_ARG(void*, reinterpret_cast<void*>(&m_service)),
                              Q_ARG(bool, result));
}

#ifdef FREESTYLEMAILMAPI12USED
CFSContentStructureFetchOperation::CFSContentStructureFetchOperation(CFSEngine& parentEngine, QMessageServicePrivate& service,
                                                   MEmailMessage* message)
    : m_parentEngine(parentEngine),
      m_service(service),
      m_message(message)
{
}

CFSContentStructureFetchOperation::~CFSContentStructureFetchOperation()
{
    cancelFetch();
}

void CFSContentStructureFetchOperation::cancelFetch()
{
    if (m_message) {
        m_message->Release();
        m_message = NULL;
    }
}

bool CFSContentStructureFetchOperation::fetch()
{
    if (!m_message)
        return false;

    TRAPD(err, m_message->FetchContentStructureL(*this));
    if (err != KErrNone)
        return false;

    return true;
}

void CFSContentStructureFetchOperation::DataFetchedL(const TInt aResult)
{
    bool result = false;
    if (aResult == KErrNone) {
        result = true;
    }
    QMetaObject::invokeMethod(&m_parentEngine, "contentStructureFetched", Qt::QueuedConnection,
                              Q_ARG(void*, reinterpret_cast<void*>(&m_service)),
                              Q_ARG(bool, result));
}
#endif

CFSMessagesFindOperation::CFSMessagesFindOperation(CFSEngine& aOwner, int aOperationId)
    : m_owner(aOwner), 
      m_operationId(aOperationId),
      m_asynchronousSearchStarted(false),
      m_resultCorrectlyOrdered(false),
      m_clientApi(0),
      m_interfacePtr(0)
{

    m_factory = 0;
    TRAPD(err, {
        m_factory = CEmailInterfaceFactory::NewL();
        m_interfacePtr = m_factory->InterfaceL(KEmailClientApiInterface);
    } );

    // Check that getting email api interface was successful.
    // Otherwise throwing exception.
    if( err != KErrNone ) {
        if( m_factory ) {
            delete m_factory;
            m_factory = 0;
        }
        // This is always throwing
        qt_symbian_throwIfError(err);
    }

    m_clientApi = q_check_ptr( static_cast<MEmailClientApi*>(m_interfacePtr) );

}

CFSMessagesFindOperation::~CFSMessagesFindOperation()
{
    foreach(FSSearchOperation operation, m_searchOperations) {
        if (operation.m_mailbox) {
            operation.m_mailbox->Release();
        }
    }
    if (m_clientApi) {
        m_clientApi->Release();
    }
    delete m_factory;

}

int CFSMessagesFindOperation::filterAndOrderMessages(const QMessageFilter &filter, const QMessageSortOrder& sortOrder,
                                                     QString body, QMessageDataComparator::MatchFlags matchFlags)
{
    m_filterList.clear();
    m_filterList.append(filter);
    return filterAndOrderMessages(m_filterList, sortOrder, body, matchFlags);
}

int CFSMessagesFindOperation::filterAndOrderMessages(const QMessageFilterPrivate::SortedMessageFilterList& filters,
                                                     const QMessageSortOrder& sortOrder,
                                                     QString body,
                                                     QMessageDataComparator::MatchFlags matchFlags)
{
    TRAPD(err, filterAndOrderMessagesL(filters, sortOrder, body, matchFlags));
    return err;
}

void CFSMessagesFindOperation::filterAndOrderMessagesL(const QMessageFilterPrivate::SortedMessageFilterList& filters,
                                                       const QMessageSortOrder& sortOrder,
                                                       QString body,
                                                       QMessageDataComparator::MatchFlags matchFlags)
{
    m_numberOfHandledFilters = 0;
    m_resultCorrectlyOrdered = false;
    m_asynchronousSearchStarted = false;
    m_body = body;
    m_matchFlags = matchFlags;
    m_idList = QMessageIdList();

    TEmailSortCriteria sortCriteria = TEmailSortCriteria();
    // This is a workaroud for MEmailFolder::MessagesL(...) crashing when default TEmailSortCriteria (EDontCare) is set
    // => TEmailSortCriteria::EByDate is always used by default
    sortCriteria.iField = TEmailSortCriteria::EByDate;
    m_excludeIdList = QMessageIdList();

    if (filters.count() == 0) {
        m_idList = QMessageIdList();
        QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection);
        return;
    }

    // Handle ordering
    QMessageSortOrderPrivate* privateMessageOrdering = QMessageSortOrderPrivate::implementation(sortOrder);
    if (privateMessageOrdering->_fieldOrderList.count() == 1) {
        // Set sortOrder
        if (!sortOrder.isEmpty() ) {
            QPair<QMessageSortOrderPrivate::Field, Qt::SortOrder> fieldOrder = privateMessageOrdering->_fieldOrderList.at(0);
            switch (fieldOrder.first) {
            case QMessageSortOrderPrivate::Type:
                break;
            case QMessageSortOrderPrivate::Sender:
                sortCriteria.iField = TEmailSortCriteria::EBySender;
                m_resultCorrectlyOrdered = true;
                break;
            case QMessageSortOrderPrivate::Recipients:
                sortCriteria.iField = TEmailSortCriteria::EByRecipient;
                m_resultCorrectlyOrdered = true;
                break;
            case QMessageSortOrderPrivate::Subject:
                sortCriteria.iField = TEmailSortCriteria::EBySubject;
                m_resultCorrectlyOrdered = true;
                break;
            case QMessageSortOrderPrivate::TimeStamp:
                sortCriteria.iField = TEmailSortCriteria::EByDate;
                m_resultCorrectlyOrdered = true;
                break;
            case QMessageSortOrderPrivate::ReceptionTimeStamp:
                sortCriteria.iField = TEmailSortCriteria::EByDate;
                m_resultCorrectlyOrdered = true;
                break;
            case QMessageSortOrderPrivate::Read:
                sortCriteria.iField = TEmailSortCriteria::EByUnread;
                m_resultCorrectlyOrdered = true;
                break;
            case QMessageSortOrderPrivate::HasAttachments:
                sortCriteria.iField = TEmailSortCriteria::EByAttachment;
                m_resultCorrectlyOrdered = true;
                break;
            case QMessageSortOrderPrivate::Incoming:
                //TODO:
                break;
            case QMessageSortOrderPrivate::Removed:
                //TODO:
                break;
            case QMessageSortOrderPrivate::Priority:
                sortCriteria.iField = TEmailSortCriteria::EByPriority;
                m_resultCorrectlyOrdered = true;
                break;
            case QMessageSortOrderPrivate::Size:
                sortCriteria.iField = TEmailSortCriteria::EBySize;
                m_resultCorrectlyOrdered = true;
                break;
            }
            sortCriteria.iAscending = fieldOrder.second == Qt::AscendingOrder?true:false;
        }
    }

    // Handle empty filter
    QMessageFilterPrivate* pf = QMessageFilterPrivate::implementation(filters[m_numberOfHandledFilters]);
    if ((filters.count() == 1) &&
        (pf->_field == QMessageFilterPrivate::None) &&
        (pf->_filterList.count() == 0)) {
        if (pf->_notFilter) {
            // There is only one filter: empty ~QMessageFilter()
            // => return empty QMessageIdList 
            m_numberOfHandledFilters++;
            m_idList = QMessageIdList();
            QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection);
        } else {
            // There is only one filter: empty QMessageFilter()
            // => return all messages
            m_numberOfHandledFilters++;
            getAllMessagesL(sortCriteria);
        }
        return;
    }

    // Handle filtering
    switch (pf->_field) {
    case QMessageFilterPrivate::ParentFolderId: {
        if (pf->_comparatorType == QMessageFilterPrivate::Equality) { // QMessageFolderId
            QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue));
            if (cmp == QMessageDataComparator::Equal) {
                m_numberOfHandledFilters++;
                TFolderId folderId = CFSEngine::fsFolderIdFromQMessageFolderId(QMessageFolderId(pf->_value.toString()));
                MEmailMailbox* mailbox = m_clientApi->MailboxL(folderId.iMailboxId);
                if (mailbox) {
                    CleanupReleasePushL(*mailbox);
                    MEmailFolder* folder = mailbox->FolderL(folderId);
                    CleanupReleasePushL(*folder);
                    getFolderSpecificMessagesL(*folder, sortCriteria);
                    CleanupStack::PopAndDestroy(folder);
                    CleanupStack::PopAndDestroy(mailbox);
                }
            } else { // NotEqual
                // TODO:
            }
        } else if (pf->_comparatorType == QMessageFilterPrivate::Inclusion) { // QMessageFolderFilter
            QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue));
            if (cmp == QMessageDataComparator::Includes) {
                // TODO:
            } else { // Excludes
                // TODO:
            }
        }
        break;
    }
    case QMessageFilterPrivate::Id: {
        m_numberOfHandledFilters++;
        if (pf->_comparatorType == QMessageFilterPrivate::Equality) { // QMessageId
            QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue));
            if (!pf->_value.isNull() && pf->_value.toString().length() > QString(SymbianHelpers::freestylePrefix).length()) {
                if (cmp == QMessageDataComparator::Equal) {
                    QMessage message = m_owner.message(QMessageId(pf->_value.toString()));
                    m_idList.clear();
                    m_idList.append(message.id());
                    m_resultCorrectlyOrdered = true;
                } else { // NotEqual
                    m_excludeIdList.clear();
                    m_excludeIdList.append(QMessageId(pf->_value.toString()));
                    getAllMessagesL(sortCriteria);
                }
            } else { // Invalid QMessageId
                if (cmp == QMessageDataComparator::Equal) {
                    m_idList.clear();
                    m_resultCorrectlyOrdered = true;
                } else { // NotEqual
                    getAllMessagesL(sortCriteria);
                }
            }
        } else if (pf->_comparatorType == QMessageFilterPrivate::Inclusion) {
            QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue));
            if (pf->_ids.count() > 0) { // QMessageIdList
                if (cmp == QMessageDataComparator::Includes) {
                    for (int i=0; i < pf->_ids.count(); i++) {
                        QMessage message = m_owner.message(QMessageId(pf->_ids[i].toString()));
                        if (message.type() != QMessage::NoType) {
                            m_idList.append(message.id());
                        }
                    }
                } else { // Excludes
                    m_excludeIdList.clear();
                    for (int i=0; i < pf->_ids.count(); i++) {
                        m_excludeIdList.append(QMessageId(pf->_ids[i].toString()));
                    }
                    getAllMessagesL(sortCriteria);
                }
            } else { // Empty QMessageAccountIdList
                if (cmp == QMessageDataComparator::Includes) {
                    m_idList.clear();
                    m_resultCorrectlyOrdered = true;
                } else { // Excludes
                    getAllMessagesL(sortCriteria);
                }
            }
        }
        break;
        }
    case QMessageFilterPrivate::ParentAccountId: {
        if (pf->_comparatorType == QMessageFilterPrivate::Equality) { // QMessageAccountId
            m_numberOfHandledFilters++;
            QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue));
            if (cmp == QMessageDataComparator::Equal) {
                QMessageAccount messageAccount = m_owner.account(pf->_value.toString());
                getAccountSpecificMessagesL(messageAccount, sortCriteria);
            } else { // NotEqual
                QStringList exludedAccounts;
                exludedAccounts << pf->_value.toString();

                QMessageFilterPrivate* privateFilter = NULL;
                for (int i=m_numberOfHandledFilters; i < filters.count(); i++) {
                    privateFilter = QMessageFilterPrivate::implementation(filters[i]);
                    if (privateFilter->_field == QMessageFilterPrivate::ParentAccountId &&
                        privateFilter->_comparatorType == QMessageFilterPrivate::Equality) {
                        cmp = static_cast<QMessageDataComparator::EqualityComparator>(privateFilter->_comparatorValue);
                        if (cmp == QMessageDataComparator::NotEqual) {
                            exludedAccounts << privateFilter->_value.toString();
                            m_numberOfHandledFilters++;
                        } else {
                            break;
                        }
                    } else {
                        break;
                    }
                }

                foreach (QMessageAccount value, m_owner.m_accounts) {
                    if (!exludedAccounts.contains(value.id().toString())) {
                        getAccountSpecificMessagesL(value, sortCriteria);
                    }
                }
            }
        }
        break;
    }

    case QMessageFilterPrivate::AncestorFolderIds: {
        m_numberOfHandledFilters++;
        if (pf->_comparatorType == QMessageFilterPrivate::Inclusion) {
            QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue));
            if (!pf->_value.isNull()) { // QMessageFolderId
                if (cmp == QMessageDataComparator::Includes) {
                    // TODO:
                } else { // Excludes
                    // TODO:
                }
            } else { // QMessageFolderFilter
                if (cmp == QMessageDataComparator::Includes) {
                    // TODO:
                } else { // Excludes
                    // TODO:
                }
            }
        }
        break;
        }
    case QMessageFilterPrivate::Type: {
        m_numberOfHandledFilters++;
        QMessageFilterPrivate* privateFilter = NULL;
        // Check if next filter is StandardFolder filter
        if (filters.count() > m_numberOfHandledFilters) {
            privateFilter = QMessageFilterPrivate::implementation(filters[m_numberOfHandledFilters]);
            if (privateFilter->_field != QMessageFilterPrivate::StandardFolder) {
                privateFilter = NULL;
            } else {
                m_numberOfHandledFilters++;
            }
        }
        if (pf->_comparatorType == QMessageFilterPrivate::Equality) { // QMessage::Type
            QMessage::Type type = static_cast<QMessage::Type>(pf->_value.toInt());
            QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue));
            if (cmp == QMessageDataComparator::Equal) {
                QMessageAccountIdList accountIds = m_owner.accountsByType(type);
                for (int i = 0; i < accountIds.count(); i++) {
                    QMessageAccount messageAccount = m_owner.account(accountIds[i]);
                    getAccountSpecificMessagesL(messageAccount, sortCriteria);
                }
            } else { // NotEqual
                foreach (QMessageAccount value, m_owner.m_accounts) {
                    if (!(value.messageTypes() & type)) {
                        getAccountSpecificMessagesL(value, sortCriteria);
                    }
                }
            }
        } else if (pf->_comparatorType == QMessageFilterPrivate::Inclusion) { // QMessage::TypeFlags
            QMessage::TypeFlags typeFlags = static_cast<QMessage::TypeFlags>(pf->_value.toInt());
            QMessageDataComparator::InclusionComparator cmp(static_cast<QMessageDataComparator::InclusionComparator>(pf->_comparatorValue));
            if (cmp == QMessageDataComparator::Includes) {
                foreach (QMessageAccount value, m_owner.m_accounts) {
                    if (value.messageTypes() | typeFlags) {
                        getAccountSpecificMessagesL(value, sortCriteria);
                    }
                }
            } else { // Excludes
                foreach (QMessageAccount value, m_owner.m_accounts) {
                    if (!(value.messageTypes() & typeFlags)) {
                        getAccountSpecificMessagesL(value, sortCriteria);
                    }
                }
            }
        }
        break;
        }
    case QMessageFilterPrivate::StandardFolder: {
        m_numberOfHandledFilters++;
        QMessageDataComparator::EqualityComparator cmp(static_cast<QMessageDataComparator::EqualityComparator>(pf->_comparatorValue));
        QMessage::StandardFolder standardFolder = static_cast<QMessage::StandardFolder>(pf->_value.toInt());
        TFolderType stdFolder = m_owner.standardFolderId(standardFolder);

        if (cmp == QMessageDataComparator::Equal) {
            foreach (QMessageAccount messageAccount, m_owner.m_accounts) {
                TMailboxId mailboxId(CFSEngine::fsMailboxIdFromQMessageAccountId(messageAccount.id()));
                MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId);
                if (mailbox) {
                    CleanupReleasePushL(*mailbox);
                    MEmailFolder* folder = mailbox->FolderByTypeL(stdFolder);
                    if (folder) {
                        CleanupReleasePushL(*folder);
                        getFolderSpecificMessagesL(*folder, sortCriteria);
                        CleanupStack::PopAndDestroy(folder);
                    }
                    CleanupStack::PopAndDestroy(mailbox);
                }
            }
        } else { // NotEqual
            foreach (QMessageAccount messageAccount, m_owner.m_accounts) {
                TMailboxId mailboxId(CFSEngine::fsMailboxIdFromQMessageAccountId(messageAccount.id()));
                MEmailMailbox* mailbox = m_clientApi->MailboxL(mailboxId);
                if (mailbox) {
                    CleanupReleasePushL(*mailbox);
                    QMessage::StandardFolder i = QMessage::InboxFolder;
                    while (i <= QMessage::TrashFolder) {
                        if (i != standardFolder) {
                            MEmailFolder* folder = mailbox->FolderByTypeL(m_owner.standardFolderId(i));
                            if (folder) {
                                CleanupReleasePushL(*folder);
                                getFolderSpecificMessagesL(*folder, sortCriteria);
                                CleanupStack::PopAndDestroy(folder);
                            }
                        }
                        i = static_cast<QMessage::StandardFolder>(static_cast<int>(i) + 1);
                    }
                    CleanupStack::PopAndDestroy(mailbox);
                }
            }
        }
        break;
        }
    case QMessageFilterPrivate::Sender:
    case QMessageFilterPrivate::Recipients:
    case QMessageFilterPrivate::Subject:
    case QMessageFilterPrivate::Status:
    case QMessageFilterPrivate::Priority:
    case QMessageFilterPrivate::Size:
    case QMessageFilterPrivate::ParentAccountIdFilter:
    case QMessageFilterPrivate::ParentFolderIdFilter:
    case QMessageFilterPrivate::TimeStamp:
    case QMessageFilterPrivate::ReceptionTimeStamp:
    case QMessageFilterPrivate::None:
    default:
        break;
    }
    
    if (m_numberOfHandledFilters == 0) {
        // None of the filters were handled
        // => Get all messages and let the engine do brute force filtering
        getAllMessagesL(sortCriteria);
    }

    if (!m_asynchronousSearchStarted) {
        // Messages were searched & filtered synchronously
        // => invoke SearchCompleted method asynchronously
        // (Note: Asynchronous searches invoke automatically SearchCompleted
        //        method as soon as search is finished)
        QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection);
    }
}

void CFSMessagesFindOperation::getAllMessagesL(TEmailSortCriteria& sortCriteria)
{
    // Get all messages from every known account
    QList<QMessageAccount> accounts = m_owner.m_accounts.values();
    for (int i=accounts.count()-1; i >= 0; i--) {
        getAccountSpecificMessagesL(accounts[i], sortCriteria);
    }

    if (m_searchOperations.count() == 0) {
        QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection);
    }
}

void CFSMessagesFindOperation::getAccountSpecificMessagesL(QMessageAccount& messageAccount, TEmailSortCriteria& sortCriteria)
{
    TMailboxId mailboxId(CFSEngine::fsMailboxIdFromQMessageAccountId(messageAccount.id()));
    FSSearchOperation operation;
    operation.m_mailbox = m_clientApi->MailboxL(mailboxId);
    operation.m_emailSortCriteria = sortCriteria;
    if (m_searchOperations.isEmpty()) {
        m_searchOperations.append(operation);
        QMetaObject::invokeMethod(this, "searchAccountFolders", Qt::QueuedConnection);
        m_asynchronousSearchStarted = true;
    } else {
        m_searchOperations.append(operation);
    }
}

void CFSMessagesFindOperation::getAccountSpecificMessagesFromAccountFoldersL(FSSearchOperation& searchOperation)
{
    MEmailMailbox* pEmailMailbox = searchOperation.m_mailbox;
    if (pEmailMailbox == NULL) {
        return;
    }

    RSortCriteriaArray sortCriteriaArray;
    CleanupClosePushL(sortCriteriaArray);
    sortCriteriaArray.Append(searchOperation.m_emailSortCriteria);

    RFolderArray folders;
    CleanupClosePushL(folders);
    pEmailMailbox->GetFoldersL(folders);
    for (TInt i=0; i < folders.Count(); i++) {
        MEmailFolder* pEmailFolder = folders[i];
        CleanupReleasePushL(*pEmailFolder);
        MMessageIterator* msgIterator = NULL;
        // TODO: Bug in CMessageIterator implementation
        //       CMessageIterator constructor does not call iPluginData.ClaimInstance()
        //       BUT CMessageIterator destructor calls iPluginData.ReleaseInstance()
        //       => BUG results crash sooner or later
        //
        // => Take reference count and make sure that reference count
        //    will be restored to its original value after iteration
        unsigned int refCount1 = pluginReferenceCount(pEmailFolder);
        TRAP_IGNORE(msgIterator = pEmailFolder->MessagesL(sortCriteriaArray));
        if (msgIterator) {
            MEmailMessage* msg = NULL;
            while ( NULL != (msg = msgIterator->NextL())) {
                QMessageId messageId = CFSEngine::qMessageIdFromFsMessageId(msg->MessageId());
                if (!MessageCache::instance()->contains(messageId)) {
                    QMessage message;
                    TRAPD(err, m_owner.CreateQMessageL(&message, *msg));
                    if (err == KErrNone) {
                        QMessagePrivate* privateMessage = QMessagePrivate::implementation(message);
                        privateMessage->_id = messageId;
                        privateMessage->_modified = false;
                    }
                    MessageCache::instance()->insert(message);
                }
                if (!m_excludeIdList.contains(messageId)) {
                    // Make sure that same ids won't be added twice
                    if (!m_idList.contains(messageId)) {
                        m_idList.append(messageId);
                    }
                }
            }
            msgIterator->Release();
        }
        // TODO: Bug in CMessageIterator implementation
        //       CMessageIterator constructor does not call iPluginData.ClaimInstance()
        //       BUT CMessageIterator destructor calls iPluginData.ReleaseInstance()
        //       => BUG results crash sooner or later
        //
        // Check if reference count was changed during iteration
        unsigned int refCount2 = pluginReferenceCount(pEmailFolder);
        if (refCount1 != refCount2) {
            // Reference count was changed
            // => Set original value to reference count
            setPluginReferenceCount(pEmailFolder, refCount1);
        }
        CleanupStack::PopAndDestroy(pEmailFolder);
    }
    CleanupStack::PopAndDestroy(&folders);
    CleanupStack::PopAndDestroy(&sortCriteriaArray);
}

void CFSMessagesFindOperation::getFolderSpecificMessagesL(MEmailFolder& folder, TEmailSortCriteria sortCriteria)
{
    RSortCriteriaArray sortCriteriaArray;
    CleanupClosePushL(sortCriteriaArray);
    sortCriteriaArray.Append(sortCriteria);

    // TODO: Bug in CMessageIterator implementation
    //       CMessageIterator constructor does not call iPluginData.ClaimInstance()
    //       BUT CMessageIterator destructor calls iPluginData.ReleaseInstance()
    //       => BUG results crash sooner or later
    //
    // => Take reference count and make sure that reference count
    //    will be restored to its original value after iteration
    unsigned int refCount1 = pluginReferenceCount(&folder);
    MMessageIterator* msgIterator = folder.MessagesL(sortCriteriaArray);
    if (msgIterator) {
        MEmailMessage* msg = NULL;
        while ( NULL != (msg = msgIterator->NextL())) {
            QMessageId messageId = CFSEngine::qMessageIdFromFsMessageId(msg->MessageId());;
            if (!MessageCache::instance()->contains(messageId)) {
                QMessage message;
                TRAPD(err, m_owner.CreateQMessageL(&message, *msg));
                if (err == KErrNone) {
                    QMessagePrivate* privateMessage = QMessagePrivate::implementation(message);
                    privateMessage->_id = messageId;
                    privateMessage->_modified = false;
                }
                MessageCache::instance()->insert(message);
            }
            if (!m_excludeIdList.contains(messageId)) {
                m_idList.append(messageId);
            }
        }
        msgIterator->Release();
        // TODO: Bug in CMessageIterator implementation
        //       CMessageIterator constructor does not call iPluginData.ClaimInstance()
        //       BUT CMessageIterator destructor calls iPluginData.ReleaseInstance()
        //       => BUG results crash sooner or later
        //
        // Check if reference count was changed during iteration
        unsigned int refCount2 = pluginReferenceCount(&folder);
        if (refCount1 != refCount2) {
            // Reference count was changed
            // => Set original value to reference count
            setPluginReferenceCount(&folder, refCount1);
        }
    }

    CleanupStack::PopAndDestroy(&sortCriteriaArray);
}

void CFSMessagesFindOperation::searchAccountFolders()
{
    TRAP_IGNORE(getAccountSpecificMessagesFromAccountFoldersL(m_searchOperations.first()));
    // Remove previous search
    if (m_searchOperations.first().m_mailbox) {
        m_searchOperations.first().m_mailbox->Release();
    }
    m_searchOperations.removeFirst();
    if (m_searchOperations.count() > 0) {
        // => Search continues
        QMetaObject::invokeMethod(this, "searchAccountFolders", Qt::QueuedConnection);
    } else {
        // searchOperation list is empty
        // => Search completed
        QMetaObject::invokeMethod(this, "SearchCompleted", Qt::QueuedConnection);
    }
}

void CFSMessagesFindOperation::SearchCompleted()
{
    if (!m_body.isEmpty()) {
        QMessageIdList idList;
        foreach (QMessageId messageId, m_idList) {
            if (filterBody(messageId))
                idList.append(messageId);   
        }
        m_idList = idList;
    }
    m_owner.filterAndOrderMessagesReady(true, m_operationId, m_idList, m_numberOfHandledFilters, m_resultCorrectlyOrdered);
}

bool CFSMessagesFindOperation::filterBody(QMessageId& messageId)
{
    Qt::CaseSensitivity caseSensitivity = (m_matchFlags & QMessageDataComparator::MatchCaseSensitive) ?
        Qt::CaseSensitive:Qt::CaseInsensitive;
    
    QMessage message = m_owner.message(messageId);
    QMessageContentContainer container = message.find(message.bodyId());
    return container.textContent().contains(m_body, caseSensitivity);
}

// TODO: Remove this function as soon as CMessageIterator bug is fixed
unsigned int CFSMessagesFindOperation::pluginReferenceCount(MEmailFolder* folder)
{
    CEmailFolder* pEmailFolder = static_cast<CEmailFolder*>(folder);
    return pEmailFolder->iPluginData.iRefCount;
}

// TODO: Remove this function as soon as CMessageIterator bug is fixed
void CFSMessagesFindOperation::setPluginReferenceCount(MEmailFolder* folder, unsigned int referenceCount)
{
    CEmailFolder* pEmailFolder = static_cast<CEmailFolder*>(folder);
    pEmailFolder->iPluginData.iRefCount = referenceCount;
}

#include "moc_qfsengine_symbian_p.cpp"

QTM_END_NAMESPACE