summaryrefslogtreecommitdiff
path: root/FreeFileSync.cpp
blob: 09e8efb8b98bb834101eadaa7984ca783cb7e4a6 (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
#include <wx/arrstr.h>
#include <wx/dir.h>
#include <wx/msgdlg.h>
#include "FreeFileSync.h"
#include "library\md5.h"
#include <stdexcept> //for std::runtime_error
#include "library/globalFunctions.h"
#include "library/gmp/include\gmp.h"
#include <wx/filename.h>
#include <fstream>
#include "ui\resources.h"

using namespace globalFunctions;

const wxString FreeFileSync::FFS_ConfigFileID = "FFS_CONFIG";
const wxString FreeFileSync::FFS_LastConfigFile = "LastRun.FFS";

inline
wxString formatTime(unsigned int number)
{
    assert (number < 100);

    if (number <= 9)
    {
        wxChar result[3];

        *result = '0';
        result[1] = '0' + number;
        result[2] = 0;

        return result;
    }
    else
    {
        wxString result;
        if (result.Printf(wxT("%d"), number) < 0)
            throw std::runtime_error("Error when converting int to wxString");
        return result;
    }
}


bool filetimeCmpEqual(const FILETIME a,const FILETIME b)
{
    if (a.dwHighDateTime == b.dwHighDateTime && a.dwLowDateTime == b.dwLowDateTime)
        return (true);
    else
        return (false);
}

void FreeFileSync::getFileInformation(FileInfo& output, const wxString& filename)
{
//
//    wxFileName file(filename);
//
//    wxDateTime lastWriteTime;
//    wxULongLong filesize;
//
//
//
//    if (file.FileExists())
//    {
//        if (!file.GetTimes(NULL, &lastWriteTime, NULL) || ((filesize = file.GetSize()) == wxInvalidSize))
//            throw FileError(wxString(_("Could not retrieve file info for: ")) + "\"" + filename + "\"");
//    output.lastWriteTime = lastWriteTime.FormatISODate();
//
//    output.lastWriteTimeUTC.dwHighDateTime = 0;
//    output.lastWriteTimeUTC.dwLowDateTime  = 0;
//    }
//
//    output.fileSize = filesize.ToString();
//


    WIN32_FIND_DATA winFileInfo;
    FILETIME localFileTime;
    SYSTEMTIME time;
    HANDLE fileHandle;

    if ((fileHandle = FindFirstFile(filename.c_str(), &winFileInfo)) == INVALID_HANDLE_VALUE)
        throw FileError(wxString(_("Could not retrieve file info for: ")) + "\"" + filename + "\"");

    FindClose(fileHandle);

    if (FileTimeToLocalFileTime(
                &winFileInfo.ftLastWriteTime,	// pointer to UTC file time to convert
                &localFileTime 	// pointer to converted file time
            ) == 0)
        throw std::runtime_error(_("Error converting FILETIME to local FILETIME"));


    if (FileTimeToSystemTime(
                &localFileTime, // pointer to file time to convert
                &time 	 // pointer to structure to receive system time
            ) == 0)
        throw std::runtime_error(_("Error converting FILETIME to SYSTEMTIME"));

    output.lastWriteTime = numberToWxString(time.wYear) + "-" +
                           formatTime(time.wMonth) + "-" +
                           formatTime(time.wDay) + "  " +
                           formatTime(time.wHour) + ":" +
                           formatTime(time.wMinute) + ":" +
                           formatTime(time.wSecond);

    //UTC times
    output.lastWriteTimeUTC = wxULongLong(winFileInfo.ftLastWriteTime.dwHighDateTime, winFileInfo.ftLastWriteTime.dwLowDateTime);

    output.fileSize = wxULongLong(winFileInfo.nFileSizeHigh, winFileInfo.nFileSizeLow);
}


string FreeFileSync::calculateMD5Hash(const wxString& filename)
{
    const unsigned int bufferSize = 8192;

    char md5_output[33];
    unsigned char signature[16];
    unsigned char buffer[bufferSize];
    md5_t state;

    md5_init(&state);
    FILE* inputFile = fopen( filename.c_str(), "rb");
    if (!inputFile)
        throw FileError(wxString(_("Could not open file: ")) + "\"" + filename + "\"");
    do
    {
        unsigned int length = fread(buffer, 1, bufferSize, inputFile);
        if (!ferror(inputFile)) md5_process(&state, buffer, length);
    }
    while (!feof(inputFile));

    fclose(inputFile);

    md5_finish(&state, signature);

    for (int i=0;i<16;i++) sprintf(md5_output + i*2, "%02x", signature[i]);

    return md5_output;
}


void FreeFileSync::generateFileAndFolderDescriptions(DirectoryDescrType& output, const wxString& directory, StatusUpdater* updateClass)
{
    assert (updateClass);

    output.clear();

    //get all files and folders from directory (and subdirectories) + information
    GetAllFilesFull traverser(output, getFormattedDirectoryName(directory), updateClass);
    wxDir dir(directory);
    dir.Traverse(traverser);
}


//handle execution of a method while updating the UI
class UpdateWhileCalculatingMD5 : public UpdateWhileExecuting
{
public:
    UpdateWhileCalculatingMD5() {}
    ~UpdateWhileCalculatingMD5() {}

    wxString file;
    bool success;
    wxString errorMessage;
    string result;

private:
    void longRunner() //virtual method implementation
    {
        try
        {
            result = FreeFileSync::calculateMD5Hash(file);
            success = true;
        }
        catch (FileError& error)
        {
            success = false;
            errorMessage = error.show();
        }
    }
};


string FreeFileSync::calculateMD5HashMultithreaded(const wxString& filename, StatusUpdater* updateClass)
{
    static UpdateWhileCalculatingMD5 calcAndUpdate;    //single instantiation: after each execution thread enters wait phase

    calcAndUpdate.waitUntilReady();

    //longRunner is called from thread, but no mutex needed here, since thread is in waiting state!
    calcAndUpdate.file = filename;

    calcAndUpdate.execAndUpdate(updateClass);

    //no mutex needed here since longRunner is finished
    if (!calcAndUpdate.success)
        throw FileError(calcAndUpdate.errorMessage);

    return calcAndUpdate.result;
}


void calcTotalDataForMD5(int& objectsTotal, double& dataTotal, const FileCompareResult& grid, const set<int>& rowsForMD5)
{
    dataTotal = 0;

    for (set<int>::iterator i = rowsForMD5.begin(); i != rowsForMD5.end(); ++i)
    {
        const FileCompareLine& gridline = grid[*i];

        dataTotal+= gridline.fileDescrLeft.fileSize.ToDouble();
        dataTotal+= gridline.fileDescrRight.fileSize.ToDouble();
    }

    objectsTotal = rowsForMD5.size() * 2;
}


void FreeFileSync::startCompareProcess(FileCompareResult& output, const wxString& dirLeft, const wxString& dirRight, CompareVariant cmpVar, StatusUpdater* statusUpdater)
{
    assert (statusUpdater);

//################################################################################################################################################

    //inform about the total amount of data that will be processed from now on
    statusUpdater->initNewProcess(-1, 0, FreeFileSync::scanningFilesProcess);    //it's not known how many files will be scanned => -1 objects

    FileCompareResult output_tmp;   //write to output not before END of process!

    try
    {
        //retrieve sets of files (with description data)
        DirectoryDescrType directoryLeft;
        DirectoryDescrType directoryRight;
        generateFileAndFolderDescriptions(directoryLeft, dirLeft, statusUpdater);
        generateFileAndFolderDescriptions(directoryRight, dirRight, statusUpdater);

        FileCompareLine newline;

        set<int> delayedMD5calculation; //md5 calculation happens AFTER compare in order to separate into two processe (needed by progress indicators)

        //find files/folders that exist in left file model but not in right model
        for (DirectoryDescrType::iterator i = directoryLeft.begin(); i != directoryLeft.end(); i++)
            if (directoryRight.find(*i) == directoryRight.end())
            {
                newline.fileDescrLeft            = *i;
                newline.fileDescrRight           = FileDescrLine();
                newline.fileDescrRight.directory = dirRight;
                newline.cmpResult                = fileOnLeftSideOnly;
                output_tmp.push_back(newline);
            }

        for (DirectoryDescrType::iterator j = directoryRight.begin(); j != directoryRight.end(); j++)
        {
            DirectoryDescrType::iterator i;

            //find files/folders that exist in right file model but not in left model
            if ((i = directoryLeft.find(*j)) == directoryLeft.end())
            {
                newline.fileDescrLeft           = FileDescrLine();
                newline.fileDescrLeft.directory = dirLeft;
                newline.fileDescrRight          = *j;
                newline.cmpResult               = fileOnRightSideOnly;
                output_tmp.push_back(newline);
            }
            //find files that exist in left and right file model
            else
            {   //objType != isNothing
                if (i->objType == isDirectory && j->objType == isDirectory)
                {
                    newline.fileDescrLeft  = *i;
                    newline.fileDescrRight = *j;
                    newline.cmpResult      = filesEqual;
                    output_tmp.push_back(newline);
                }
                //if we have a nameclash between a file and a directory: split into separate rows
                else if (i->objType != j->objType)
                {
                    newline.fileDescrLeft            = *i;
                    newline.fileDescrRight           = FileDescrLine();
                    newline.fileDescrRight.directory = dirRight;
                    newline.cmpResult                = fileOnLeftSideOnly;
                    output_tmp.push_back(newline);

                    newline.fileDescrLeft           = FileDescrLine();
                    newline.fileDescrLeft.directory = dirLeft;
                    newline.fileDescrRight          = *j;
                    newline.cmpResult               = fileOnRightSideOnly;
                    output_tmp.push_back(newline);
                }
                else if (cmpVar == compareByTimeAndSize)
                {  //check files that exist in left and right model but have different properties
                    if (i->lastWriteTimeUTC != j->lastWriteTimeUTC ||
                            i->fileSize != j->fileSize)
                    {
                        newline.fileDescrLeft  = *i;
                        newline.fileDescrRight = *j;

                        if (i->lastWriteTimeUTC == j->lastWriteTimeUTC)
                            newline.cmpResult      = filesDifferent;
                        else if (i->lastWriteTimeUTC < j->lastWriteTimeUTC)
                            newline.cmpResult      = rightFileNewer;
                        else
                            newline.cmpResult      = leftFileNewer;
                        output_tmp.push_back(newline);
                    }
                    else
                    {
                        newline.fileDescrLeft  = *i;
                        newline.fileDescrRight = *j;
                        newline.cmpResult      = filesEqual;
                        output_tmp.push_back(newline);
                    }
                }
                else if (cmpVar == compareByMD5)
                {   //check files that exist in left and right model but have different content

                    //check filesize first!
                    if (i->fileSize == j->fileSize)
                    {
                        newline.fileDescrLeft  = *i;
                        newline.fileDescrRight = *j;
                        //newline.cmpResult    = ...;   //not yet determined
                        output_tmp.push_back(newline);

                        //md5 needed only if filesizes are the same
                        delayedMD5calculation.insert(output_tmp.size() - 1); //save index of row, to calculate cmpResult later
                    }
                    else
                    {
                        newline.fileDescrLeft  = *i;
                        newline.fileDescrRight = *j;
                        newline.cmpResult      = filesDifferent;
                        output_tmp.push_back(newline);
                    }
                }
                else assert (false);
            }
        }

//################################################################################################################################################
        //calculate MD5 checksums and set value "cmpResult"
        if (cmpVar == compareByMD5)
        {
            int objectsTotal = 0;
            double dataTotal = 0;
            calcTotalDataForMD5(objectsTotal, dataTotal, output_tmp, delayedMD5calculation);

            statusUpdater->initNewProcess(objectsTotal, dataTotal, FreeFileSync::calcMD5Process);

            set<int> rowsToDelete;  //if errors occur during file access and user skips, these rows need to be deleted from result

            for (set<int>::iterator i = delayedMD5calculation.begin(); i != delayedMD5calculation.end(); ++i)
            {
                FileCompareLine& gridline = output_tmp[*i];

                //check files that exist in left and right model but have different checksums
                string leftFileHash;
                string rightFileHash;

                while (true)
                {
                    //trigger display refresh
                    statusUpdater->triggerUI_Refresh();

                    try
                    {
                        if (leftFileHash.empty())
                        {
                            statusUpdater->updateStatusText(wxString(_("Reading content of ") + gridline.fileDescrLeft.filename));
                            leftFileHash = calculateMD5HashMultithreaded(gridline.fileDescrLeft.filename, statusUpdater);
                            statusUpdater->updateProcessedData(1, gridline.fileDescrLeft.fileSize.ToDouble());
                        }

                        if (rightFileHash.empty())
                        {
                            statusUpdater->updateStatusText(wxString(_("Reading content of ") + gridline.fileDescrRight.filename));
                            rightFileHash = calculateMD5HashMultithreaded(gridline.fileDescrRight.filename, statusUpdater);
                            statusUpdater->updateProcessedData(1, gridline.fileDescrRight.fileSize.ToDouble());
                        }

                        if (leftFileHash == rightFileHash)
                            gridline.cmpResult = filesEqual;
                        else
                            gridline.cmpResult = filesDifferent;

                        break;
                    }
                    catch (FileError& error)
                    {
                        //if (updateClass) -> is mandatory
                        int rv = statusUpdater->reportError(error.show());
                        if ( rv == StatusUpdater::continueNext)
                        {
                            rowsToDelete.insert(*i);
                            break;
                        }
                        else if (rv == StatusUpdater::retry)
                            ;   //continue with loop
                        else
                            assert (false);
                    }
                }
            }

            //delete invalid rows that have no valid cmpResult
            if (rowsToDelete.size() > 0)
                removeRowsFromVector(output_tmp, rowsToDelete);
        }

        statusUpdater->triggerUI_Refresh();
    }
    catch (std::runtime_error& theException)
    {
        wxMessageBox(_(theException.what()), _("An exception occured!"), wxOK | wxICON_ERROR);
        return;
    }

    //only if everything was processed correctly output is written to!
    output_tmp.swap(output);
}


void FreeFileSync::swapGrids(FileCompareResult& grid)
{
    FileDescrLine tmp;

    for (FileCompareResult::iterator i = grid.begin(); i != grid.end(); ++i)
    {
        //swap compare result
        if (i->cmpResult == fileOnLeftSideOnly)
            i->cmpResult = fileOnRightSideOnly;
        else if (i->cmpResult == fileOnRightSideOnly)
            i->cmpResult = fileOnLeftSideOnly;
        else if (i->cmpResult == rightFileNewer)
            i->cmpResult = leftFileNewer;
        else if (i->cmpResult == leftFileNewer)
            i->cmpResult = rightFileNewer;

        //swap file descriptors
        tmp = i->fileDescrLeft;
        i->fileDescrLeft = i->fileDescrRight;
        i->fileDescrRight = tmp;
    }
}


GetAllFilesFull::GetAllFilesFull(DirectoryDescrType& output, wxString dirThatIsSearched, StatusUpdater* updateClass)
        : m_output(output), directory(dirThatIsSearched), statusUpdater(updateClass)
{
    assert(updateClass);
    prefixLength = directory.Len();
}


wxDirTraverseResult GetAllFilesFull::OnFile(const wxString& filename)
{
    fileDescr.filename         = filename;
    fileDescr.directory        = directory;
    fileDescr.relFilename      = filename.Mid(prefixLength, wxSTRING_MAXLEN);
    while (true)
    {
        try
        {
            FreeFileSync::getFileInformation(currentFileInfo, filename);
            break;
        }
        catch (FileError& error)
        {
            //if (updateClass) -> is mandatory
            int rv = statusUpdater->reportError(error.show());
            if ( rv == StatusUpdater::continueNext)
                return wxDIR_CONTINUE;
            else if (rv == StatusUpdater::retry)
                ;   //continue with loop
            else
                assert (false);
        }
    }

    fileDescr.lastWriteTime    = currentFileInfo.lastWriteTime;
    fileDescr.lastWriteTimeUTC = currentFileInfo.lastWriteTimeUTC;
    fileDescr.fileSize         = currentFileInfo.fileSize;
    fileDescr.objType          = isFile;
    m_output.insert(fileDescr);

    //update UI/commandline status information
    statusUpdater->updateStatusText(wxString(_("Scanning ")) + filename); // NO performance issue at all
    //add 1 element to the progress indicator
    statusUpdater->updateProcessedData(1, 0);     // NO performance issue at all
    //trigger display refresh
    statusUpdater->triggerUI_Refresh();

    return wxDIR_CONTINUE;
}


wxDirTraverseResult GetAllFilesFull::OnDir(const wxString& dirname)
{
    if (dirname.EndsWith("\\RECYCLER"))
        return wxDIR_IGNORE;
    if (dirname.EndsWith("\\System Volume Information"))
        return wxDIR_IGNORE;

    fileDescr.filename    = dirname;
    fileDescr.directory   = directory;
    fileDescr.relFilename = dirname.Mid(prefixLength, wxSTRING_MAXLEN);
    while (true)
    {
        try
        {
            FreeFileSync::getFileInformation(currentFileInfo, dirname);
            break;
        }
        catch (FileError& error)
        {
            //if (updateClass) -> is mandatory
            int rv = statusUpdater->reportError(error.show());
            if ( rv == StatusUpdater::continueNext)
                return wxDIR_IGNORE;
            else if (rv == StatusUpdater::retry)
                ;   //continue with loop
            else
                assert (false);
        }
    }
    fileDescr.lastWriteTime    = currentFileInfo.lastWriteTime;
    fileDescr.lastWriteTimeUTC = currentFileInfo.lastWriteTimeUTC;
    fileDescr.fileSize         = wxULongLong(0);     //currentFileInfo.fileSize should be "0" as well, but just to be sure... currently used by getBytesToTransfer
    fileDescr.objType          = isDirectory;
    m_output.insert(fileDescr);

    //update UI/commandline status information
    statusUpdater->updateStatusText(wxString(_("Scanning ")) + dirname); // NO performance issue at all
    //add 1 element to the progress indicator
    statusUpdater->updateProcessedData(1, 0);     // NO performance issue at all
    //trigger display refresh
    statusUpdater->triggerUI_Refresh();

    return wxDIR_CONTINUE;
}


wxDirTraverseResult GetAllFilesFull::OnOpenError(const wxString& openerrorname)
{
    wxMessageBox(openerrorname, _("Error opening file"));
    return wxDIR_IGNORE;
}


//#####################################################################################################
//file functions

class GetAllFilesSimple : public wxDirTraverser
{
public:
    GetAllFilesSimple(wxArrayString& files, wxArrayString& subDirectories) :
            allFiles(files),
            subdirs(subDirectories)
    {}

    wxDirTraverseResult OnDir(const wxString& dirname)
    {
        subdirs.Add(dirname);
        return wxDIR_CONTINUE;
    }

    wxDirTraverseResult OnFile(const wxString& filename)
    {
        allFiles.Add(filename);
        return wxDIR_CONTINUE;
    }

    wxDirTraverseResult OnOpenError(const wxString& openerrorname)
    {
        wxMessageBox(openerrorname, _("Error opening file"));
        return wxDIR_IGNORE;
    }

private:
    wxArrayString& allFiles;
    wxArrayString& subdirs;
};


void FreeFileSync::moveToRecycleBin(const wxString& filename)
{
    bool aborted = false;
    SHFILEOPSTRUCT fileOp;

    wxString filenameDoubleNull = filename + char(0);

    fileOp.hwnd   = NULL;
    fileOp.wFunc  = FO_DELETE;
    fileOp.pFrom  = filenameDoubleNull.c_str();
    fileOp.pTo    = NULL;
    fileOp.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_SILENT;
    fileOp.fAnyOperationsAborted = aborted;
    fileOp.hNameMappings         = NULL;
    fileOp.lpszProgressTitle     = NULL;

    if (fileOperation(&fileOp   //Pointer to an SHFILEOPSTRUCT structure that contains information the function needs to carry out.
                     ) != 0 || aborted) throw FileError(wxString(_("Error moving file ")) + "\"" + filename + "\"" + _(" to recycle bin!"));
}


inline
void FreeFileSync::removeFile(const wxString& filename)
{
    if (!wxFileExists(filename)) return; //this is NOT an error situation: the manual deletion relies on it!

    if (recycleBinAvailable)
    {
        moveToRecycleBin(filename);
        return;
    }

#ifdef FFS_WIN
    if (!SetFileAttributes(
                filename.c_str(), // address of filename
                FILE_ATTRIBUTE_NORMAL	 	// address of attributes to set
            )) throw FileError(wxString(_("Error deleting file ")) + "\"" + filename + "\"");
#endif  // FFS_WIN

    if (!wxRemoveFile(filename))
        throw FileError(wxString(_("Error deleting file ")) + "\"" + filename + "\"");
}


void FreeFileSync::removeDirectory(const wxString& directory)
{
    if (!wxDirExists(directory)) return; //this is NOT an error situation: the manual deletion relies on it!

    if (recycleBinAvailable)
    {
        moveToRecycleBin(directory);
        return;
    }

    wxArrayString fileList;
    wxArrayString dirList;

    {   //own scope for directory access to not disturb deletion!
        wxDir dir(directory);

        //get all files and directories from current directory (and subdirectories)
        GetAllFilesSimple traverser(fileList, dirList);
        dir.Traverse(traverser);
    }

    for (unsigned int j = 0; j < fileList.GetCount(); ++j)
        removeFile(fileList[j]);

    dirList.Insert(directory, 0);   //this directory will be deleted last

    for (int j = int(dirList.GetCount()) - 1; j >= 0 ; --j)

        if (!wxRmdir(dirList[j]))
            throw FileError(wxString(_("Error deleting directory ")) + "\"" + dirList[j] + "\"");
}


inline
void FreeFileSync::copyfile(const wxString& source, const wxString& target)
{
    if (!wxCopyFile(source, target, false)) //return false if file exists
        throw FileError(wxString(_("Error copying file ")) + "\"" + source + "\"" + _(" to ") + "\"" + target + "\"");
}


inline
void FreeFileSync::copyOverwriting(const wxString& source, const wxString& target)
{
    if (!SetFileAttributes(
                target.c_str(), // address of filename
                FILE_ATTRIBUTE_NORMAL	 	// address of attributes to set
            )) throw FileError(wxString(_("Error overwriting file ")) + "\"" + target + "\"");

    if (!wxCopyFile(source, target, true)) //if file exists it will be overwritten
        throw FileError(wxString(_("Error copying file ")) + "\"" + source + "\"" + _(" to ") + "\"" + target + "\"");
}


void FreeFileSync::createDirectory(const wxString& directory, int level)
{
    if (wxDirExists(directory))
        return;

    if (level == 50)    //catch endless loop
        return;

    //try to create directory
    if (wxMkdir(directory))
        return;

    //if not successfull try to create containing folders first
    wxString createFirstDir = wxDir(directory).GetName().BeforeLast(GlobalResources::fileNameSeparator);

    //call function recursively
    if (createFirstDir.IsEmpty()) return;
    createDirectory(createFirstDir, level + 1);

    //now creation should be possible
    if (!wxMkdir(directory))
    {
        if (level == 0)
            throw FileError(wxString(_("Error creating directory ")) + "\"" + directory + "\"");
    }
}


void FreeFileSync::copyCreatingDirs(const wxString& source, const wxString& target)
{
    wxString targetPath = wxFileName(target).GetPath();
    createDirectory(targetPath);

    if (!wxCopyFile(source, target, false)) //error if file exists
        throw FileError(wxString(_("Error copying file ")) + "\"" + source + "\"" + _(" to ") + "\"" + target + "\"");
}

//###########################################################################################


//handle execution of a method while updating the UI
class UpdateWhileCopying : public UpdateWhileExecuting
{
public:
    UpdateWhileCopying()
    {   //prevent wxWidgets logging
        noWxLogs = new wxLogNull;
    }
    ~UpdateWhileCopying()
    {
        delete noWxLogs;
    }
    wxString source;
    wxString target;
    bool success;

private:
    void longRunner() //virtual method implementation
    {
        success = wxCopyFile(source, target, false); //abort if file exists
    }

    wxLogNull* noWxLogs;
};


void FreeFileSync::copyfileMultithreaded(const wxString& source, const wxString& target, StatusUpdater* updateClass)
{
    static UpdateWhileCopying copyAndUpdate;    //single instantiation: after each execution thread enters wait phase

    copyAndUpdate.waitUntilReady();

    //longRunner is called from thread, but no mutex needed here, since thread is in waiting state!
    copyAndUpdate.source = source;
    copyAndUpdate.target = target;

    copyAndUpdate.execAndUpdate(updateClass);

    //no mutex needed here since longRunner is finished
    if (!copyAndUpdate.success)
        throw FileError(wxString(_("Error copying file ")) + "\"" + source + "\"" + _(" to ") + "\"" + target + "\"");
}


FreeFileSync::FreeFileSync()
        : recycleBinAvailable(false)
{
    // Get a handle to the DLL module containing Recycle Bin functionality
    hinstShell = LoadLibrary("shell32.dll");
    if (hinstShell == NULL)
        recycleBinAvailable = false;
    else
    {
        fileOperation  = (DLLFUNC)GetProcAddress(hinstShell, "SHFileOperation");
        if (fileOperation == NULL )
        {
            FreeLibrary(hinstShell);
            recycleBinAvailable = false;
        }
        else
            recycleBinAvailable = true;
    }

    //prevent wxWidgets logging
    noWxLogs = new wxLogNull;
}


FreeFileSync::~FreeFileSync()
{
    if (recycleBinAvailable)
        FreeLibrary(hinstShell);

    delete noWxLogs;
}


bool FreeFileSync::recycleBinExists()
{
    FreeFileSync dummyObject;
    return dummyObject.recycleBinAvailable;
}


bool FreeFileSync::setRecycleBinUsage(bool activate)
{   //If recycleBin is not available it mustn't be activated: This should NEVER happen!
    if (!recycleBinAvailable && activate)
        throw std::runtime_error("Initialization of Recycle Bin failed! It cannot be used!");
    else
        recycleBinAvailable = activate;
    return true;
}


inline
SyncDirection getSyncDirection(const CompareFilesResult cmpResult, const SyncConfiguration& config)
{
    switch (cmpResult)
    {
    case fileOnLeftSideOnly:
        return config.exLeftSideOnly;
        break;

    case fileOnRightSideOnly:
        return config.exRightSideOnly;
        break;

    case rightFileNewer:
        return config.rightNewer;
        break;

    case leftFileNewer:
        return config.leftNewer;
        break;

    case filesDifferent:
        return config.different;
        break;

    default:
        assert (false);
    }
    return syncDirNone;
}


void FreeFileSync::wxULongLongToMpz(mpz_t& output, const wxULongLong& input)
{
    mpz_set_ui(output, input.GetHi());
    mpz_mul_ui(output, output, 65536);
    mpz_mul_ui(output, output, 65536);
    mpz_add_ui(output, output, input.GetLo());
}


bool getBytesToTransfer(double& result, const FileCompareLine& fileCmpLine, const SyncConfiguration& config)
{   //false if nothing has to be done

    result = 0;  //always initialize variables

    //do not add filtered entries
    if (!fileCmpLine.selectedForSynchronization)
        return false;

    switch (fileCmpLine.cmpResult)
    {
    case fileOnLeftSideOnly:
    case fileOnRightSideOnly:
    case leftFileNewer:
    case rightFileNewer:
    case filesDifferent:
        switch (getSyncDirection(fileCmpLine.cmpResult, config))
        {
        case syncDirLeft:   //copy from right to left
            result = fileCmpLine.fileDescrRight.fileSize.ToDouble();
            return true;
        case syncDirRight:  //copy from left to right
            result = fileCmpLine.fileDescrLeft.fileSize.ToDouble();
            return true;
        case syncDirNone:
            return false;
        }
        break;

    case filesEqual:
        return false;
    };

    return true;
}


void FreeFileSync::calcTotalBytesToSync(int& objectsTotal, double& dataTotal, const FileCompareResult& fileCmpResult, const SyncConfiguration& config)
{
    objectsTotal = 0;
    dataTotal    = 0;

    double tmp = 0;

    for (FileCompareResult::const_iterator i = fileCmpResult.begin(); i != fileCmpResult.end(); ++i)
    {   //only sum up sizes of files AND directories
        if (getBytesToTransfer(tmp, *i, config))
        {
            dataTotal+= tmp;
            objectsTotal++;
        }
    }
}


bool FreeFileSync::synchronizeFile(const FileCompareLine& filename, const SyncConfiguration& config, StatusUpdater* statusUpdater)
{   //false if nothing was to be done
    assert (statusUpdater);

    if (!filename.selectedForSynchronization) return false;

    wxString target;

    //synchronize file:
    switch (filename.cmpResult)
    {
    case fileOnLeftSideOnly:
        switch (config.exLeftSideOnly)
        {
        case syncDirLeft:   //delete files on left
            statusUpdater->updateStatusText(wxString(_("Deleting file ") + filename.fileDescrLeft.filename));
            removeFile(filename.fileDescrLeft.filename);
            break;
        case syncDirRight:  //copy files to right
            target = filename.fileDescrRight.directory + filename.fileDescrLeft.relFilename.c_str();
            statusUpdater->updateStatusText(wxString(_("Copying file ")) + filename.fileDescrLeft.filename +
                                            _(" to ") + target);

            copyfileMultithreaded(filename.fileDescrLeft.filename, target, statusUpdater);
            break;
        case syncDirNone:
            return false;
        default:
            assert (false);
        }
        break;

    case fileOnRightSideOnly:
        switch (config.exRightSideOnly)
        {
        case syncDirLeft:   //copy files to left
            target = filename.fileDescrLeft.directory + filename.fileDescrRight.relFilename;
            statusUpdater->updateStatusText(wxString(_("Copying file ")) + filename.fileDescrRight.filename +
                                            _(" to ") + target);

            copyfileMultithreaded(filename.fileDescrRight.filename, target, statusUpdater);
            break;
        case syncDirRight:  //delete files on right
            statusUpdater->updateStatusText(wxString(_("Deleting file ") + filename.fileDescrRight.filename));
            removeFile(filename.fileDescrRight.filename);
            break;
        case syncDirNone:
            return false;
        default:
            assert (false);
        }
        break;

    case leftFileNewer:
    case rightFileNewer:
    case filesDifferent:
        switch (getSyncDirection(filename.cmpResult, config))
        {
        case syncDirLeft:   //copy from right to left
            statusUpdater->updateStatusText(wxString(_("Copying file ")) + filename.fileDescrRight.filename +
                                            _(" overwriting ") + filename.fileDescrLeft.filename);

            removeFile(filename.fileDescrLeft.filename);  //only used if switch activated by user, else file is simply deleted
            copyfileMultithreaded(filename.fileDescrRight.filename, filename.fileDescrLeft.filename, statusUpdater);
            break;
        case syncDirRight:  //copy from left to right
            statusUpdater->updateStatusText(wxString(_("Copying file ")) + filename.fileDescrLeft.filename +
                                            _(" overwriting ") + filename.fileDescrRight.filename);

            removeFile(filename.fileDescrRight.filename);  //only used if switch activated by user, else file is simply deleted
            copyfileMultithreaded(filename.fileDescrLeft.filename, filename.fileDescrRight.filename, statusUpdater);
            break;
        case syncDirNone:
            return false;
        default:
            assert (false);
        }
        break;

    case filesEqual:
        return false;

    default:
        assert (false);
    }
    return true;
}


bool FreeFileSync::synchronizeFolder(const FileCompareLine& filename, const SyncConfiguration& config, StatusUpdater* statusUpdater)
{   //false if nothing was to be done
    assert (statusUpdater);

    if (!filename.selectedForSynchronization) return false;

    wxString target;

    //synchronize folders:
    switch (filename.cmpResult)
    {
    case fileOnLeftSideOnly:
        switch (config.exLeftSideOnly)
        {
        case syncDirLeft:   //delete folders on left
            statusUpdater->updateStatusText(wxString(_("Deleting folder ") + filename.fileDescrLeft.filename));
            removeDirectory(filename.fileDescrLeft.filename);
            break;
        case syncDirRight:  //create folders on right
            target = filename.fileDescrRight.directory + filename.fileDescrLeft.relFilename;
            statusUpdater->updateStatusText(wxString(_("Creating folder ") + target));

            //some check to catch the error that directory on source has been deleted externally after the "compare"...
            if (!wxDirExists(filename.fileDescrLeft.filename))
                throw FileError(wxString(_("Error: Source directory does not exist anymore: ")) + "\"" + filename.fileDescrLeft.filename + "\"");
            createDirectory(target);
            break;
        case syncDirNone:
            return false;
        default:
            assert (false);
        }
        break;

    case fileOnRightSideOnly:
        switch (config.exRightSideOnly)
        {
        case syncDirLeft:   //create folders on left
            target = filename.fileDescrLeft.directory + filename.fileDescrRight.relFilename;
            statusUpdater->updateStatusText(wxString(_("Creating folder ") + target));

            //some check to catch the error that directory on source has been deleted externally after the "compare"...
            if (!wxDirExists(filename.fileDescrRight.filename))
                throw FileError(wxString(_("Error: Source directory does not exist anymore: ")) + filename.fileDescrRight.filename);
            createDirectory(target);
            break;
        case syncDirRight:  //delete folders on right
            statusUpdater->updateStatusText(wxString(_("Deleting folder ") + filename.fileDescrRight.filename));
            removeDirectory(filename.fileDescrRight.filename);
            break;
        case syncDirNone:
            return false;
        default:
            assert (false);
        }
        break;

    case filesEqual:
        return false;
    case rightFileNewer:
    case leftFileNewer:
    case filesDifferent:
    default:
        assert (false);
    }
    return true;
}


wxString FreeFileSync::formatFilesizeToShortString(const mpz_class& filesize)
{
    mpf_class nrOfBytes = filesize;

    wxString unit = " Byte";
    if (nrOfBytes > 999)
    {
        nrOfBytes/= 1024;
        unit = " kB";
        if (nrOfBytes > 999)
        {
            nrOfBytes/= 1024;
            unit = " MB";
            if (nrOfBytes > 999)
            {
                nrOfBytes/= 1024;
                unit = " GB";
                if (nrOfBytes > 999)
                {
                    nrOfBytes/= 1024;
                    unit = " TB";
                    if (nrOfBytes > 999)
                    {
                        nrOfBytes/= 1024;
                        unit = " PB";
                    }
                }
            }
        }
    }

    mp_exp_t exponent = 0;

    wxString temp;
    if (unit == " Byte")        //no decimal places in case of bytes
    {
        temp = nrOfBytes.get_str(exponent, 10, 3);
        if (!temp.Len()) //if nrOfBytes is zero GMP returns an empty string
            temp = "0";
    }
    else
    {
        temp = wxString(nrOfBytes.get_str(exponent, 10, 3) + "000").substr(0, 3); //returns mantisse of length 3 in all cases

        if (exponent < 0 || exponent > 3)
            temp = _("Error");
        else
            switch (exponent)
            {
            case 0:
                temp = wxString("0") + GlobalResources::floatingPointSeparator + temp.substr(0, 2); //shorten mantisse as a 0 will be inserted
                break;
            case 1:
            case 2:
                temp.insert(exponent, GlobalResources::floatingPointSeparator);
                break;
            case 3:
                break;
            }
    }
    temp+= unit;
    return temp;
}


void FreeFileSync::filterCurrentGridData(FileCompareResult& currentGridData, const wxString& includeFilter, const wxString& excludeFilter)
{
    wxString includeFilterTmp(includeFilter);
    wxString excludeFilterTmp(excludeFilter);

    //make sure filters end with ";" - no problem with empty strings here
    if (!includeFilterTmp.EndsWith(";"))
        includeFilterTmp.Append(';');
    if (!excludeFilterTmp.EndsWith(";"))
        excludeFilterTmp.Append(';');

    //load filters into vectors
    vector<wxString> includeList;
    vector<wxString> excludeList;

    unsigned int indexStart = 0;
    unsigned int indexEnd = 0;
    while ((indexEnd = includeFilterTmp.find(';', indexStart )) != string::npos)
    {
        if (indexStart != indexEnd) //do not add empty strings
            includeList.push_back( includeFilterTmp.substr(indexStart, indexEnd - indexStart) );
        indexStart = indexEnd + 1;
    }

    indexStart = 0;
    indexEnd = 0;
    while ((indexEnd = excludeFilterTmp.find(';', indexStart )) != string::npos)
    {
        if (indexStart != indexEnd) //do not add empty strings
            excludeList.push_back( excludeFilterTmp.substr(indexStart, indexEnd - indexStart) );
        indexStart = indexEnd + 1;
    }

//###########################

    //filter currentGridData
    for (FileCompareResult::iterator i = currentGridData.begin(); i != currentGridData.end(); i++)
    {
        //process include filters
        if (i->fileDescrLeft.objType != isNothing)
        {
            bool includedLeft = false;
            for (vector<wxString>::const_iterator j = includeList.begin(); j != includeList.end(); ++j)
                if (i->fileDescrLeft.filename.Matches(*j))
                {
                    includedLeft = true;
                    break;
                }

            if (!includedLeft)
            {
                i->selectedForSynchronization = false;
                continue;
            }
        }

        if (i->fileDescrRight.objType != isNothing)
        {
            bool includedRight = false;
            for (vector<wxString>::const_iterator j = includeList.begin(); j != includeList.end(); ++j)
                if (i->fileDescrRight.filename.Matches(*j))
                {
                    includedRight = true;
                    break;
                }

            if (!includedRight)
            {
                i->selectedForSynchronization = false;
                continue;
            }
        }

        //process exclude filters
        bool excluded = false;
        for (vector<wxString>::const_iterator j = excludeList.begin(); j != excludeList.end(); ++j)
            if (i->fileDescrLeft.filename.Matches(*j) ||
                    i->fileDescrRight.filename.Matches(*j))
            {
                excluded = true;
                break;
            }

        if (excluded)
        {
            i->selectedForSynchronization = false;
            continue;
        }

        i->selectedForSynchronization = true;
    }
}

void FreeFileSync::removeFilterOnCurrentGridData(FileCompareResult& currentGridData)
{
    //remove all filters on currentGridData
    for (FileCompareResult::iterator i = currentGridData.begin(); i != currentGridData.end(); i++)
        i->selectedForSynchronization = true;
}


wxString FreeFileSync::getFormattedDirectoryName(const wxString& dirname)
{  //this formatting is needed since functions in FreeFileSync.cpp expect the directory to end with '\' to be able to split the relative names
    //Actually all it needs, is the length of the directory

    //let wxWidgets do the directory formatting, e.g. replace '/' with '\' for Windows
    wxString result = wxDir(dirname).GetName();

    result.Append(GlobalResources::fileNameSeparator);
    return result;
}


inline
bool deletionImminent(const FileCompareLine& line, const SyncConfiguration& config)
{   //test if current sync-line will result in deletion of files    -> used to avoid disc space bottlenecks
    if ((line.cmpResult == fileOnLeftSideOnly && config.exLeftSideOnly == syncDirLeft) ||
            (line.cmpResult == fileOnRightSideOnly && config.exRightSideOnly == syncDirRight))
        return true;
    else
        return false;
}


class AlwaysWriteResult //this class ensures, that the result of the method below is ALWAYS written on exit, even if exceptions were thrown!
{
public:
    AlwaysWriteResult(FileCompareResult& grid) :
            gridToWrite(grid)
    {}

    ~AlwaysWriteResult()
    {
        removeRowsFromVector(gridToWrite, rowsProcessed);
    }

    void rowProcessedSuccessfully(int nr)
    {
        rowsProcessed.insert(nr);
    }

private:
    FileCompareResult& gridToWrite;
    set<int> rowsProcessed;
};


//synchronizes while processing rows in grid and returns all rows that have not been synced
void FreeFileSync::startSynchronizationProcess(FileCompareResult& grid, const SyncConfiguration& config, StatusUpdater* statusUpdater, bool useRecycleBin)
{
    assert (statusUpdater);

    AlwaysWriteResult writeOutput(grid);  //ensure that grid is always written to, even if method is exitted via exceptions

    //inform about the total amount of data that will be processed from now on
    int objectsTotal = 0;
    double dataTotal = 0;
    FreeFileSync::calcTotalBytesToSync(objectsTotal, dataTotal, grid, config);
    statusUpdater->initNewProcess(objectsTotal, dataTotal, FreeFileSync::synchronizeFilesProcess);

    try
    {
        FreeFileSync fileSyncObject;    //currently only needed for recycle bin
        fileSyncObject.setRecycleBinUsage(useRecycleBin);

        // it should never happen, that a directory on left side has same name as file on right side. GetModelDiff should take care of this
        // and split into two "exists on one side only" cases
        // Note: this case is not handled by this tool as this is considered to be a bug and must be solved by the user

        //synchronize folders:
        for (FileCompareResult::const_iterator i = grid.begin(); i != grid.end(); ++i)
        {
            if (i->fileDescrLeft.objType == isDirectory || i->fileDescrRight.objType == isDirectory)
            {
                while (true)
                {   //trigger display refresh
                    statusUpdater->triggerUI_Refresh();

                    try
                    {
                        if (fileSyncObject.synchronizeFolder(*i, config, statusUpdater))
                            //progress indicator update
                            //indicator is updated only if directory is synched correctly  (and if some sync was done)!
                            statusUpdater->updateProcessedData(1, 0);  //each call represents one processed file/directory

                        writeOutput.rowProcessedSuccessfully(i - grid.begin());
                        break;
                    }
                    catch (FileError& error)
                    {
                        //if (updateClass) -> is mandatory
                        int rv = statusUpdater->reportError(error.show());

                        if ( rv == StatusUpdater::continueNext)
                            break;
                        else if (rv == StatusUpdater::retry)
                            ;  //continue with loop
                        else
                            assert (false);
                    }
                }
            }
        }

        //synchronize files:
        for (int k = 0; k < 2; ++k) //loop over all files twice; reason: first delete, then copy (no sorting necessary: performance)
        {
            bool deleteLoop = !k;   //-> first loop: delete files, second loop: copy files

            for (FileCompareResult::const_iterator i = grid.begin(); i != grid.end(); ++i)
            {
                if (i->fileDescrLeft.objType == isFile || i->fileDescrRight.objType == isFile)
                {
                    if (deleteLoop && deletionImminent(*i, config) ||
                            !deleteLoop && !deletionImminent(*i, config))
                    {
                        while (true)
                        {    //trigger display refresh
                            statusUpdater->triggerUI_Refresh();

                            try
                            {
                                if (fileSyncObject.synchronizeFile(*i, config, statusUpdater))
                                {
                                    //progress indicator update
                                    //indicator is updated only if file is synched correctly (and if some sync was done)!
                                    double processedData = 0;
                                    if (getBytesToTransfer(processedData, *i, config))  //update status if some work was done (answer is always "yes" in this context)
                                        statusUpdater->updateProcessedData(1, processedData);
                                }

                                writeOutput.rowProcessedSuccessfully(i - grid.begin());
                                break;
                            }
                            catch (FileError& error)
                            {
                                //if (updateClass) -> is mandatory
                                int rv = statusUpdater->reportError(error.show());

                                if ( rv == StatusUpdater::continueNext)
                                    break;
                                else if (rv == StatusUpdater::retry)
                                    ;   //continue with loop
                                else
                                    assert (false);
                            }
                        }
                    }
                }
            }
        }
    }
    catch (std::runtime_error& theException)
    {
        wxMessageBox(_(theException.what()), _("An exception occured!"), wxOK | wxICON_ERROR);
        return;
    }
}


bool FreeFileSync::isFFS_ConfigFile(const wxString& filename)
{
    ifstream config(filename.c_str());
    if (!config)
        return false;

    char bigBuffer[10000];

    //read FFS identifier
    config.get(bigBuffer, FreeFileSync::FFS_ConfigFileID.Len() + 1);

    return (FFS_ConfigFileID == wxString(bigBuffer));
}


//add(!) all files and subfolder gridlines that are dependent from the directory
void FreeFileSync::addSubElements(set<int>& subElements, const FileCompareResult& grid, const FileCompareLine& relevantRow)
{
    wxString relevantDirectory;

    if (relevantRow.fileDescrLeft.objType == isDirectory)
        relevantDirectory = relevantRow.fileDescrLeft.relFilename;

    else if (relevantRow.fileDescrRight.objType == isDirectory)
        relevantDirectory = relevantRow.fileDescrRight.relFilename;

    else
        return;

    for (FileCompareResult::const_iterator i = grid.begin(); i != grid.end(); ++i)
        if (i->fileDescrLeft.relFilename.StartsWith(relevantDirectory) ||
                i->fileDescrRight.relFilename.StartsWith(relevantDirectory))
            subElements.insert(i - grid.begin());
}


void FreeFileSync::deleteOnGridAndHD(FileCompareResult& grid, const set<int>& rowsToDelete, StatusUpdater* statusUpdater, bool useRecycleBin)
{
    FreeFileSync fileSyncObject;    //currently only needed for recycle bin
    fileSyncObject.setRecycleBinUsage(useRecycleBin);

    set<int> rowsToDeleteInGrid;

    //remove from hd
    for (set<int>::iterator i = rowsToDelete.begin(); i != rowsToDelete.end(); ++i)
    {
        const FileCompareLine& currentCmpLine = grid[*i];

        while (true)
        {
            try
            {
                if (currentCmpLine.fileDescrLeft.objType == isFile)
                    fileSyncObject.removeFile(currentCmpLine.fileDescrLeft.filename);
                else if (currentCmpLine.fileDescrLeft.objType == isDirectory)
                    fileSyncObject.removeDirectory(currentCmpLine.fileDescrLeft.filename);

                if (currentCmpLine.fileDescrRight.objType == isFile)
                    fileSyncObject.removeFile(currentCmpLine.fileDescrRight.filename);
                else if (currentCmpLine.fileDescrRight.objType == isDirectory)
                    fileSyncObject.removeDirectory(currentCmpLine.fileDescrRight.filename);

                rowsToDeleteInGrid.insert(*i);

                break;
            }
            catch (FileError& error)
            {

                //if (updateClass) -> is mandatory
                int rv = statusUpdater->reportError(error.show());

                if (rv == StatusUpdater::continueNext)
                    break;

                else if (rv == StatusUpdater::retry)
                    ;   //continue with loop
                else
                    assert (false);
            }
        }
    }

    //retrieve all files and subfolder gridlines that are dependent from deleted directories and add them to the list
    set<int> additionalRowsToDelete;
    for (set<int>::iterator i = rowsToDeleteInGrid.begin(); i != rowsToDeleteInGrid.end(); ++i)
        addSubElements(additionalRowsToDelete, grid, grid[*i]);

    for (set<int>::iterator i = additionalRowsToDelete.begin(); i != additionalRowsToDelete.end(); ++i)
        rowsToDeleteInGrid.insert(*i);


    //remove deleted rows from grid
    removeRowsFromVector(grid, rowsToDeleteInGrid);
}

bgstack15