File: find2_backtracking.h

package info (click to toggle)
seqan2 2.5.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 228,748 kB
  • sloc: cpp: 257,602; ansic: 91,967; python: 8,326; sh: 1,056; xml: 570; makefile: 229; awk: 51; javascript: 21
file content (1359 lines) | stat: -rw-r--r-- 60,794 bytes parent folder | download
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
// ==========================================================================
//                 SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2026, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Knut Reinert or the FU Berlin nor the names of
//       its contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Enrico Siragusa <enrico.siragusa@fu-berlin.de>
// ==========================================================================
// Approximate string matching via backtracking on two substring indices.
// ==========================================================================

#ifndef SEQAN_FIND_BACKTRACKING_MULTIPLE_H_
#define SEQAN_FIND_BACKTRACKING_MULTIPLE_H_

//#define SEQAN_DEBUG

namespace seqan2 {

// ============================================================================
// Forwards
// ============================================================================

template <typename TDistance, typename TSpec>
struct Backtracking;

struct StageInitial_;
struct StageUpper_;
struct StageDiagonal_;
struct StageLower_;
struct StageFinal_;
struct StageExact_;

// ============================================================================
// Metafunctions
// ============================================================================

// ----------------------------------------------------------------------------
// Metafunction TextIterator_
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec>
struct TextIterator_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> >
{
    typedef typename Iterator<Index<TText, TTextIndexSpec>, TopDown<> >::Type   Type;
};

// ----------------------------------------------------------------------------
// Metafunction PatternIterator_
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec>
struct PatternIterator_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> >
{
    typedef typename Iterator<Index<TPattern, TPatternIndexSpec>, TopDown<> >::Type    Type;
};

// ----------------------------------------------------------------------------
// Metafunction VertexScore_
// ----------------------------------------------------------------------------

template <typename TBacktracking>
struct VertexScore_ {};

template <typename TSpec>
struct VertexScore_<Backtracking<HammingDistance, TSpec> >
{
    typedef unsigned char           Type;
};

template <typename TSpec>
struct VertexScore_<Backtracking<EditDistance, TSpec> >
{
    typedef String<unsigned char>                   TString;
    typedef Segment<TString, InfixSegment>          Type;
    typedef Segment<const TString, InfixSegment>    ConstType;
};

// ----------------------------------------------------------------------------
// Metafunction VertexScoreStack_
// ----------------------------------------------------------------------------

template <typename TBacktracking>
struct VertexScoreStack_ {};

template <typename TSpec>
struct VertexScoreStack_<Backtracking<HammingDistance, TSpec> >
{
    typedef String<typename VertexScore_<Backtracking<HammingDistance, TSpec> >::Type> Type;
};

template <typename TSpec>
struct VertexScoreStack_<Backtracking<EditDistance, TSpec> >
{
    typedef StringSet<typename VertexScore_<Backtracking<EditDistance, TSpec> >::TString, Owner<ConcatDirect<> > > Type;
};

// ----------------------------------------------------------------------------
// Metafunction NextStage_
// ----------------------------------------------------------------------------

template <typename TBacktracking, typename TStage>
struct NextStage_
{
    typedef Nothing         Type;
};

// HammingDistance: StageInitial|StageExact -> StageFinal

template <typename TSpec>
struct NextStage_<Backtracking<HammingDistance, TSpec>, StageInitial_>
{
    typedef StageFinal_     Type;
};

template <typename TSpec>
struct NextStage_<Backtracking<HammingDistance, TSpec>, StageExact_>
{
    typedef StageFinal_     Type;
};

// EditDistance: StageInitial -> StageUpper -> StageDiagonal -> StageLower -> StageFinal

template <typename TSpec>
struct NextStage_<Backtracking<EditDistance, TSpec>, StageInitial_>
{
    typedef StageUpper_     Type;
};

template <typename TSpec>
struct NextStage_<Backtracking<EditDistance, TSpec>, StageUpper_>
{
    typedef StageDiagonal_  Type;
};

template <typename TSpec>
struct NextStage_<Backtracking<EditDistance, TSpec>, StageDiagonal_>
{
    typedef StageLower_     Type;
};

template <typename TSpec>
struct NextStage_<Backtracking<EditDistance, TSpec>, StageLower_>
{
    typedef StageFinal_     Type;
};

// ============================================================================
// Tags, Classes, Enums
// ============================================================================

// ----------------------------------------------------------------------------
// Tags for backtracking stages
// ----------------------------------------------------------------------------

struct StageInitial_ {};
struct StageUpper_ {};
struct StageDiagonal_ {};
struct StageLower_ {};
struct StageFinal_ {};
struct StageExact_ {};

// ----------------------------------------------------------------------------
// Class Finder_
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec,
          typename TDistance, typename TSpec>
struct Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> >
{
    typedef Index<TText, TTextIndexSpec>                                                TTextIndex;
    typedef Index<TPattern, TPatternIndexSpec>                                          TPatternIndex;
    typedef Backtracking<TDistance, TSpec>                                              TBacktracking;
    typedef typename TextIterator_<TTextIndex, TPatternIndex, TBacktracking>::Type      TTextIterator;
    typedef typename PatternIterator_<TTextIndex, TPatternIndex, TBacktracking>::Type   TPatternIterator;
    typedef String<TTextIterator>                                                       TTextStack;
    typedef String<TPatternIterator>                                                    TPatternStack;
    typedef typename VertexScoreStack_<TBacktracking>::Type                             TVertexScoreStack;
    typedef typename Score_<TBacktracking>::Type                                        TScore;

    TTextStack              textStack;
    TPatternStack           patternStack;
    TVertexScoreStack       scoreStack;
    TScore                  maxScore;

    Finder_() :
        textStack(),
        patternStack(),
        scoreStack(),
        maxScore(0)
    {}
};

// ============================================================================
// Functions
// ============================================================================

// ----------------------------------------------------------------------------
// Function _min3()
// ----------------------------------------------------------------------------

template <typename TValue>
inline TValue
_min3(TValue a, TValue b, TValue c)
{
    TValue m = a;
    if (m > b) m = b;
    if (m > c) m = c;
    return m;
}

// ----------------------------------------------------------------------------
// Function _updateVertexScore()
// ----------------------------------------------------------------------------

template <typename TVertexScore>
inline void
_updateVertexScore(TVertexScore current,
                   TVertexScore const previous,
                   StageInitial_ const & /* tag */)
{
    // Update last cell.
    // C[i,0] = C[i-1,0] + 1 [Upper]
    back(current) = back(previous) + 1;
}

template <typename TVertexScore, typename TTextValue, typename TPatternIterator, typename TStage>
inline void
_updateVertexScore(TVertexScore current,
                   TVertexScore const previous,
                   TTextValue textChar,
                   TPatternIterator patternIt,
                   TStage const & /* tag */)
{
    typedef typename Iterator<TVertexScore, Standard>::Type         TVertexScoreIterator;
    typedef typename Iterator<TVertexScore const, Standard>::Type   TVertexScoreConstIterator;
    typedef typename Value<TVertexScore>::Type                      TScore;

    TVertexScoreIterator currentIt = begin(current, Standard());
    TVertexScoreIterator columnEnd = end(current, Standard());
    TVertexScoreConstIterator previousIt = begin(previous, Standard());

    // Update first cell.
    SEQAN_IF_CONSTEXPR (IsSameType<TStage, StageUpper_>::VALUE)
    {
        // C[0,j] = C[0,j-1] + 1 [Left]
        value(currentIt) = value(previousIt) + 1;
    }
    else
    {
        TScore score = ordEqual(textChar, value(patternIt)) ? 0 : 1;

        // C[i,j] = min { C[i-1,j-1] + d(t,p), C[i-1,j] + 1 } [Diagonal, Left]
        value(currentIt) = _min(value(previousIt) + score, value(previousIt + 1) + 1);

        ++previousIt;
        ++patternIt;
    }

    // Update central cells.
    for (++currentIt; currentIt != columnEnd - 1; ++currentIt, ++previousIt, ++patternIt)
    {
        TScore score = ordEqual(textChar, value(patternIt)) ? 0 : 1;

        // C[i,j] = min { C[i-1,j-1] + d(t,p), C[i-1,j] + 1, C[i,j-1] + 1 } [Diagonal, Left, Upper]
        value(currentIt) = _min3(value(previousIt) + score, value(previousIt + 1) + 1, value(currentIt - 1) + 1);
    }

    // Update last cell.
    SEQAN_IF_CONSTEXPR (IsSameType<TStage, StageLower_>::VALUE)
    {
        TScore score = ordEqual(textChar, value(patternIt)) ? 0 : 1;

        // C[i,j] = min { C[i-1,j-1] + d(t,p), C[i-1,j] + 1, C[i,j-1] + 1 } [Diagonal, Left, Upper]
        value(currentIt) = _min3(value(previousIt) + score, value(previousIt + 1) + 1, value(currentIt - 1) + 1);

        ++previousIt;
    }
    else
    {
        TScore score = ordEqual(textChar, value(patternIt)) ? 0 : 1;

        // C[i,j] = min { C[i-1,j-1] + d(t,p), C[i,j-1] + 1 } [Diagonal, Upper]
        value(currentIt) = _min(value(previousIt) + score, value(currentIt - 1) + 1);
    }

    // Assert end of columns.
    SEQAN_ASSERT_EQ(currentIt + 1, end(current, Standard()));
    SEQAN_ASSERT_EQ(previousIt + 1, end(previous, Standard()));
}

template <typename TVertexScore, typename TTextValue, typename TPatternValue>
inline void
_updateVertexScore(TVertexScore current,
                   TVertexScore const previous,
                   TTextValue textChar,
                   TPatternValue patternChar,
                   StageFinal_ const & /* tag */)
{
    typedef typename Iterator<TVertexScore, Standard>::Type         TVertexScoreIterator;
    typedef typename Iterator<TVertexScore const, Standard>::Type   TVertexScoreConstIterator;
    typedef typename Value<TVertexScore>::Type                      TScore;

    TVertexScoreIterator currentIt = begin(current, Standard());
    TVertexScoreConstIterator previousIt = begin(previous, Standard());

    // Update last cell.
    TScore score = ordEqual(textChar, patternChar) ? 0 : 1;

    // C[i,j] = min { C[i-1,j-1] + d(t,p), C[i-1,j] + 1 } [Diagonal, Left]
    value(currentIt) = _min(value(previousIt) + score, value(previousIt + 1) + 1);

    // Assert end of columns.
    SEQAN_ASSERT_EQ(currentIt + 1, end(current, Standard()));
    SEQAN_ASSERT_EQ(previousIt + 2, end(previous, Standard()));
}

// ----------------------------------------------------------------------------
// Function copyBackAndResize()                                     [StringSet]
// ----------------------------------------------------------------------------

template <typename TString, typename TSSetSpec, typename TDelta>
inline void
copyBackAndResize(StringSet<TString, TSSetSpec> & stringSet, TDelta delta)
{
    // Copy last element to the back.
    appendValue(stringSet, back(stringSet));

    // Update limits.
    back(stringSet.limits) += delta;

    // Resize concat.
    resize(stringSet.concat, length(stringSet.concat) + delta);
}

// ----------------------------------------------------------------------------
// Function clear()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec>
inline void
clear(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder)
{
    clear(finder.textStack);
    clear(finder.patternStack);
    clear(finder.scoreStack);
}

// ----------------------------------------------------------------------------
// Function _initState()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TTextIterator, typename TPatternIterator>
inline void
_initState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
           TTextIterator const & textIt, TPatternIterator const & patternIt)
{
    // Init iterators.
    appendValue(finder.textStack, textIt);
    appendValue(finder.patternStack, patternIt);

    _initScore(finder);

#ifdef SEQAN_DEBUG
        _printState(finder, StageInitial_());
#endif
}

// ----------------------------------------------------------------------------
// Function _initScore()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec>
inline void
_initScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder)
{
    typedef Backtracking<TDistance, TSpec>              TBacktracking;
    typedef typename Score_<TBacktracking>::Type        TScore;

    // Push zero.
    appendValue(finder.scoreStack, TScore());
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_initScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder)
{
    typedef Backtracking<EditDistance, TSpec>           TBacktracking;
    typedef typename Score_<TBacktracking>::Type        TScore;

    // Push a column with one zero cell.
    append(finder.scoreStack.limits, 1);
    appendValue(finder.scoreStack.concat, TScore());
}

// ----------------------------------------------------------------------------
// Function _pushState()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline bool
_pushState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
           TStage const & /* tag */)
{
    _pushIterators(finder, TStage());
    _pushScore(finder, TStage());

    if (_moveIteratorsDown(finder, TStage()))
    {
        _updateScore(finder, TStage());

#ifdef SEQAN_DEBUG
        _printPush(finder, TStage());
#endif
        return true;
    }

    _popIterators(finder, TStage());
    _popScore(finder, TStage());

    return false;
}

// ----------------------------------------------------------------------------
// Function _pushIterators()
// ----------------------------------------------------------------------------
// TODO(esiragusa): Specialize _pushIterators() for StageInitial_ and StageFinal_ of EditDistance

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_pushIterators(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
               TStage const & /* tag */)
{
    appendValue(finder.patternStack, back(finder.patternStack));
    appendValue(finder.textStack, back(finder.textStack));
}

// ----------------------------------------------------------------------------
// Function _pushScore()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_pushScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
           TStage const & /* tag */)
{
    // Copy the last score on top of the stack.
    appendValue(finder.scoreStack, back(finder.scoreStack));
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_pushScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > & /* finder */,
           StageExact_ const & /* tag */)
{
    // Do nothing.
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_pushScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
           StageInitial_ const & /* tag */)
{
    // Copy the last column on top of the stack and add one cell.
    copyBackAndResize(finder.scoreStack, 1);
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_pushScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
           StageUpper_ const & /* tag */)
{
    _pushScore(finder, StageInitial_());
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_pushScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
           StageLower_ const & /* tag */)
{
    // Copy the last column on top of the stack and remove one cell.
    copyBackAndResize(finder.scoreStack, -1);
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_pushScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
           StageFinal_ const & /* tag */)
{
    _pushScore(finder, StageLower_());
}

// ----------------------------------------------------------------------------
// Function _moveIteratorsDown()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline bool
_moveIteratorsDown(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
                   TStage const & /* tag */)
{
    // Go down in text and pattern.
    return goDown(back(finder.textStack)) && goDown(back(finder.patternStack));
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveIteratorsDown(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > & finder,
                   StageExact_ const & /* tag */)
{
    typedef Index<TText, TTextIndexSpec>                                                TTextIndex;
    typedef Index<TPattern, TPatternIndexSpec>                                          TPatternIndex;
    typedef Backtracking<HammingDistance, TSpec>                                        TBacktracking;
    typedef typename TextIterator_<TTextIndex, TPatternIndex, TBacktracking>::Type      TTextIterator;
    typedef typename PatternIterator_<TTextIndex, TPatternIndex, TBacktracking>::Type   TPatternIterator;

    TTextIterator & textIt = back(finder.textStack);
    TPatternIterator & patternIt = back(finder.patternStack);

    // Go down in pattern and search pattern label in text.
    if (goDown(patternIt) && goDown(textIt, parentEdgeLabel(patternIt)))
        return true;

    // Otherwise go right in pattern.
    return _moveIteratorsRight(finder, StageExact_());
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveIteratorsDown(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
                   StageInitial_ const & /* tag */)
{
    // Go down in pattern.
    return goDown(back(finder.patternStack));
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveIteratorsDown(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
                   StageLower_ const & /* tag */)
{
    // Go down in text.
    return goDown(back(finder.textStack));
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveIteratorsDown(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
                   StageFinal_ const & /* tag */)
{
    return _moveIteratorsDown(finder, StageLower_());
}

// ----------------------------------------------------------------------------
// Function _nextState()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline bool
_nextState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
           TStage const & /* tag */)
{
    if (_moveIteratorsRight(finder, TStage()))
    {
        _updateScore(finder, TStage());

#ifdef SEQAN_DEBUG
        _printState(finder, TStage());
#endif
        return true;
    }

    return false;
}

// ----------------------------------------------------------------------------
// Function _moveIteratorsRight()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline bool
_moveIteratorsRight(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
                    TStage const & /* tag */)
{
    // Try to go right in the pattern.
    if (goRight(back(finder.patternStack)))
    {
        return true;
    }
    // Try to go right in the text.
    else if (goRight(back(finder.textStack)))
    {
        // Move to the leftmost pattern.
//        back(finder.patternStack) = finder.patternLeftmost;

        eraseBack(finder.patternStack);
        appendValue(finder.patternStack, back(finder.patternStack));
        goDown(back(finder.patternStack));
        return true;
    }

    return false;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveIteratorsRight(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > & finder,
                    StageExact_ const & /* tag */)
{
    typedef Index<TText, TTextIndexSpec>                                                TTextIndex;
    typedef Index<TPattern, TPatternIndexSpec>                                          TPatternIndex;
    typedef Backtracking<HammingDistance, TSpec>                                        TBacktracking;
    typedef typename TextIterator_<TTextIndex, TPatternIndex, TBacktracking>::Type      TTextIterator;
    typedef typename PatternIterator_<TTextIndex, TPatternIndex, TBacktracking>::Type   TPatternIterator;

    // TODO(esiragusa): Implement goRight(it, pattern).
//    TTextIterator & textIt = back(finder.textStack);
//    TPatternIterator & patternIt = back(finder.patternStack);
//    return goRight(patternIt) && goRight(textIt, parentEdgeLabel(patternIt));

    TPatternIterator & patternIt = back(finder.patternStack);

    // Try to go right in the pattern.
    while (goRight(patternIt))
    {
        // Move up in the text.
        back(finder.textStack) = finder.textStack[length(finder.textStack) - 2];

        // Search pattern label in text.
        TTextIterator & textIt = back(finder.textStack);
        if (goDown(textIt, parentEdgeLabel(patternIt)))
            return true;
    }

    return false;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveIteratorsRight(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
                    StageInitial_ const & /* tag */)
{
    // Try to go right in the pattern.
    return goRight(back(finder.patternStack));
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveIteratorsRight(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
                    StageLower_ const & /* tag */)
{
    // Try to go right in the text.
    return goRight(back(finder.textStack));
}

// ----------------------------------------------------------------------------
// Function _popState()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_popState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
          TStage const & /* tag */)
{
    _popIterators(finder, TStage());
    _popScore(finder, TStage());

#ifdef SEQAN_DEBUG
    _printPop(finder, TStage());
#endif
}

// ----------------------------------------------------------------------------
// Function _popIterators()
// ----------------------------------------------------------------------------
// TODO(esiragusa): Specialize _popIterators() for StageInitial_ and StageFinal_ of EditDistance

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_popIterators(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
              TStage const & /* tag */)
{
    eraseBack(finder.textStack);
    eraseBack(finder.patternStack);
}

// ----------------------------------------------------------------------------
// Function _popScore()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_popScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
          TStage const & /* tag */)
{
    eraseBack(finder.scoreStack);
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_popScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > & /* finder */,
          StageExact_ const & /* tag */)
{
    // Do nothing.
}

// ----------------------------------------------------------------------------
// Function _updateScore()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_updateScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & /* finder */,
             TStage const & /* tag */)
{}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec, typename TStage>
inline void
_updateScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > & finder,
             TStage const & /* tag */)
{
    typedef Backtracking<HammingDistance, TSpec>    TBacktracking;
    typedef typename Score_<TBacktracking>::Type    TScore;

    // Compute score of text and pattern.
    TScore score = ordEqual(parentEdgeLabel(back(finder.textStack)), parentEdgeLabel(back(finder.patternStack))) ? 0 : 1;

    // Add score to previous score.
    back(finder.scoreStack) = value(finder.scoreStack, length(finder.scoreStack) - 2) + score;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_updateScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > & /* finder */,
             StageExact_ const & /* tag */)
{
    // Do nothing.
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_updateScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
             StageInitial_ const & /* tag */)
{
    _updateVertexScore(back(finder.scoreStack), value(finder.scoreStack, length(finder.scoreStack) - 2), StageInitial_());
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_updateScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
             StageUpper_ const & /* tag */)
{
    typedef Index<TPattern, TPatternIndexSpec>                              TPatternIndex;
    typedef typename Fibre<TPatternIndex, FibreText>::Type const            TPatternFibreText;
    typedef typename InfixOnValue<TPatternFibreText>::Type                  TPatternRepr;
    typedef typename Iterator<TPatternRepr, Standard>::Type                 TPatternReprIterator;

    // Get pattern read so far.
    TPatternRepr pattern = representative(back(finder.patternStack));
    TPatternReprIterator patternIt = begin(pattern, Standard());

    _updateVertexScore(back(finder.scoreStack),
                       value(finder.scoreStack, length(finder.scoreStack) - 2),
                       parentEdgeLabel(back(finder.textStack)),
                       patternIt,
                       StageUpper_());
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_updateScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
             StageDiagonal_ const & /* tag */)
{
    typedef Index<TPattern, TPatternIndexSpec>                              TPatternIndex;
    typedef typename Fibre<TPatternIndex, FibreText>::Type const            TPatternFibreText;
    typedef typename InfixOnValue<TPatternFibreText>::Type                  TPatternRepr;
    typedef typename Iterator<TPatternRepr, Standard>::Type                 TPatternReprIterator;

    // Get last 2k + 1 pattern symbols.
    TPatternRepr pattern = representative(back(finder.patternStack));
    TPatternReprIterator patternIt = end(pattern, Standard()) - (2 * finder.maxScore + 1);

    _updateVertexScore(back(finder.scoreStack),
                       value(finder.scoreStack, length(finder.scoreStack) - 2),
                       parentEdgeLabel(back(finder.textStack)),
                       patternIt,
                       StageDiagonal_());
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_updateScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
             StageLower_ const & /* tag */)
{
    typedef Index<TPattern, TPatternIndexSpec>                              TPatternIndex;
    typedef typename Fibre<TPatternIndex, FibreText>::Type const            TPatternFibreText;
    typedef typename InfixOnValue<TPatternFibreText>::Type                  TPatternRepr;
    typedef typename Iterator<TPatternRepr, Standard>::Type                 TPatternReprIterator;

    // Get last pattern symbols.
    TPatternRepr pattern = representative(back(finder.patternStack));
    TPatternReprIterator patternIt = end(pattern, Standard()) - (length(back(finder.scoreStack)));

    _updateVertexScore(back(finder.scoreStack),
                       value(finder.scoreStack, length(finder.scoreStack) - 2),
                       parentEdgeLabel(back(finder.textStack)),
                       patternIt,
                       StageLower_());
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_updateScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > & finder,
             StageFinal_ const & /* tag */)
{
    _updateVertexScore(back(finder.scoreStack),
                       value(finder.scoreStack, length(finder.scoreStack) - 2),
                       parentEdgeLabel(back(finder.textStack)),
                       parentEdgeLabel(back(finder.patternStack)),
                       StageFinal_());
}

// ----------------------------------------------------------------------------
// Function _setScoreThreshold()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TMaxScore>
inline void
_setScoreThreshold(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
                  TMaxScore maxScore)
{
    finder.maxScore = maxScore;
}

// ----------------------------------------------------------------------------
// Function _getMinScore()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline typename Score_<Backtracking<HammingDistance, TSpec> >::Type
_getMinScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & finder)
{
    return _getScore(finder);
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline typename Score_<Backtracking<EditDistance, TSpec> >::Type
_getMinScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder)
{
    typedef Backtracking<EditDistance, TSpec>                       TBacktracking;
    typedef typename VertexScore_<TBacktracking>::ConstType         TVertexScore;

    TVertexScore column = back(finder.scoreStack);

    // Return the min value in column.
    return value(std::min_element(begin(column, Standard()), end(column, Standard())));
}

// ----------------------------------------------------------------------------
// Function _getScore()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline typename Score_<Backtracking<HammingDistance, TSpec> >::Type
_getScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & finder)
{
    // Return the last value.
    return back(finder.scoreStack);
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline typename Score_<Backtracking<EditDistance, TSpec> >::Type
_getScore(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder)
{
    // Return the value of last cell in column.
    return back(back(finder.scoreStack));
}

// ----------------------------------------------------------------------------
// Function _textIterator()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec>
inline
typename TextIterator_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> >::Type &
_textIterator(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder)
{
    return back(finder.textStack);
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec>
inline
typename TextIterator_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> >::Type const &
_textIterator(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & finder)
{
    return back(finder.textStack);
}

// ----------------------------------------------------------------------------
// Function _patternIterator()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec>
inline
typename PatternIterator_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> >::Type &
_patternIterator(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder)
{
    return back(finder.patternStack);
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec>
inline
typename PatternIterator_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> >::Type const &
_patternIterator(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & finder)
{
    return back(finder.patternStack);
}

// ----------------------------------------------------------------------------
// Function _inTerminalState()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline bool
_inTerminalState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & /* finder */,
                 TStage const & /* tag */)
{
    // The current state is not terminal by default.
    return false;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_inTerminalState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & finder,
                 StageFinal_ const & /* tag */)
{
    // Is the score within the max score?
    return _getScore(finder) <= finder.maxScore;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_inTerminalState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
                 StageLower_ const & /* tag */)
{
    // Is the score within the max score?
    return _getScore(finder) <= finder.maxScore;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_inTerminalState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
                 StageFinal_ const & /* tag */)
{
    // Is the score within the max score?
    return _getScore(finder) <= finder.maxScore;
}

// ----------------------------------------------------------------------------
// Function _inActiveState()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline bool
_inActiveState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & finder,
               TStage const & /* tag */)
{
    // Is the minimum score within the max score?
    return _getMinScore(finder) <= finder.maxScore;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_inActiveState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & /* finder */,
               StageExact_ const & /* tag */)
{
    // Exact search only walks through active states.
    return true;
}

// ----------------------------------------------------------------------------
// Function _moveToExactStage()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline bool
_moveToStageExact(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & /* finder */,
                  TStage const & /* tag */)
{
    // By default there is no exact stage.
    return false;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveToStageExact(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & finder,
                  StageInitial_ const & /* tag */)
{
    // Was the maximum score attained?
    return _getMinScore(finder) == finder.maxScore;
}

//template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec, typename TStage>
//inline bool
//_moveToStageExact(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
//                  TStage const & /* tag */)
//{
//    // TODO(esiragusa): Implement exact search speedup for EditDistance.
//    return _getMinScore(finder) == finder.maxScore;
//}

// ----------------------------------------------------------------------------
// Function _moveToNextStage()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline bool
_moveToNextStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & /* finder */,
                 TStage const & /* tag */)
{
    // By default there is no next stage.
    return false;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveToNextStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & finder,
                 StageInitial_ const & /* tag */)
{
    return isRightTerminal(back(finder.patternStack));
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveToNextStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & finder,
                 StageExact_ const & /* tag */)
{
    return isRightTerminal(back(finder.patternStack));
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveToNextStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
                 StageInitial_ const & /* tag */)
{
    // Move to upper stage when k pattern symbols have been consumed.
    return (repLength(back(finder.patternStack)) >= finder.maxScore) || isRightTerminal(back(finder.patternStack));
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveToNextStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
                 StageUpper_ const & /* tag */)
{
    // Move to diagonal stage when the diagonal has size 2k + 1.
    return (length(back(finder.scoreStack)) >= 2u * finder.maxScore + 1u) || isRightTerminal(back(finder.patternStack));
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveToNextStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
                 StageDiagonal_ const & /* tag */)
{
    // Move to lower stage when all pattern symbols have been consumed.
    return isRightTerminal(back(finder.patternStack));
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_moveToNextStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
                 StageLower_ const & /* tag */)
{
    // Move to final stage when there is only one cell left to compute.
    return length(back(finder.scoreStack)) <= 2;
}

// ----------------------------------------------------------------------------
// Function _stayInCurrentStage()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline bool
_stayInCurrentStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & /* finder */,
                    TStage const & /* tag */)
{
    // Stay in the current stage by default.
    return true;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_stayInCurrentStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
                    StageInitial_ const & /* tag */)
{
    return repLength(back(finder.patternStack)) < finder.maxScore;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_stayInCurrentStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
                    StageUpper_ const & /* tag */)
{
    return length(back(finder.scoreStack)) < 2u * finder.maxScore + 1u;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline bool
_stayInCurrentStage(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
                    StageLower_ const & /* tag */)
{
    return length(back(finder.scoreStack)) > 2;
}

// ----------------------------------------------------------------------------
// Functions _print*()
// ----------------------------------------------------------------------------
// NOTE(esiragusa): Debug functions.

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_printCall(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & finder,
           TStage const & /* tag */)
{
    std::cout << "call:           "; _printFindSignature(finder, TStage());
    std::cout << "past text:      " << representative(back(finder.textStack)) << std::endl;
    std::cout << "past pattern:   " << representative(back(finder.patternStack)) << std::endl;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_printReturn(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & finder,
             TStage const & /* tag */)
{
    std::cout << "return:         "; _printFindSignature(finder, TStage());
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_printPush(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & finder,
           TStage const & /* tag */)
{
    std::cout << "push:           "; _printFindSignature(finder, TStage());
    _printState(finder, TStage());
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_printPop(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & finder,
          TStage const & /* tag */)
{
    std::cout << "pop:            "; _printFindSignature(finder, TStage());
    _printState(finder, TStage());
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage>
inline void
_printFindSignature(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > const & /* finder */,
                    TStage const & /* tag */)
{
    std::cout << "<TDistance, TStage>" << std::endl;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_printFindSignature(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & /* finder */,
                    StageInitial_ const & /* tag */)
{
    std::cout << "<HammingDistance, StageInitial>" << std::endl;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_printFindSignature(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & /* finder */,
                    StageFinal_ const & /* tag */)
{
    std::cout << "<HammingDistance, StageFinal>" << std::endl;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_printFindSignature(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & /* finder */,
                    StageExact_ const & /* tag */)
{
    std::cout << "<HammingDistance, StageExact>" << std::endl;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_printFindSignature(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & /* finder */,
                    StageInitial_ const & /* tag */)
{
    std::cout << "<EditDistance, StageInitial>" << std::endl;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_printFindSignature(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & /* finder */,
                    StageUpper_ const & /* tag */)
{
    std::cout << "<EditDistance, StageUpper>" << std::endl;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_printFindSignature(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & /* finder */,
                    StageDiagonal_ const & /* tag */)
{
    std::cout << "<EditDistance, StageDiagonal>" << std::endl;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_printFindSignature(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & /* finder */,
                    StageLower_ const & /* tag */)
{
    std::cout << "<EditDistance, StageLower>" << std::endl;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec>
inline void
_printFindSignature(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & /* finder */,
                    StageFinal_ const & /* tag */)
{
    std::cout << "<EditDistance, StageFinal>" << std::endl;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec, typename TStage>
inline void
_printState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<HammingDistance, TSpec> > const & finder,
            TStage const & /* tag */)
{
    std::cout << "text:           " << parentEdgeLabel(back(finder.textStack)) << std::endl;
    std::cout << "pattern:        " << parentEdgeLabel(back(finder.patternStack)) << std::endl;
    std::cout << "errors:         " << static_cast<unsigned>(_getScore(finder)) << std::endl;
}

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TSpec, typename TStage>
inline void
_printState(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<EditDistance, TSpec> > const & finder,
            TStage const & /* tag */)
{
    std::cout << "text:           " << parentEdgeLabel(back(finder.textStack)) << std::endl;
    std::cout << "pattern:        " << parentEdgeLabel(back(finder.patternStack)) << std::endl;
    std::cout << "column:         " << "|";
    std::copy(begin(back(finder.scoreStack), Standard()),
              end(back(finder.scoreStack), Standard()),
              std::ostream_iterator<int>(std::cout, "|"));
    std::cout << std::endl;
}

// ----------------------------------------------------------------------------
// Function _find()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TStage, typename TDelegate>
inline void
_find(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
      TDelegate & delegate,
      TStage const & /* tag */)
{
    typedef Backtracking<TDistance, TSpec>                      TBacktracking;
    typedef typename NextStage_<TBacktracking, TStage>::Type    TNextStage;

#ifdef SEQAN_DEBUG
    _printCall(finder, TStage());
#endif

    if (_moveToStageExact(finder, TStage()))
    {
        _find(finder, delegate, StageExact_());
    }
    else
    {
        if (_moveToNextStage(finder, TStage()))
        {
            _find(finder, delegate, TNextStage());
        }
        if (_stayInCurrentStage(finder, TStage()))
        {
            if (_inTerminalState(finder, TStage()))
            {
                // Inversion of control.
                delegate(finder);
            }
            else if (_inActiveState(finder, TStage()))
            {
                if (_pushState(finder, TStage()))
                {
                    do
                    {
                        _find(finder, delegate, TStage());
                    }
                    while (_nextState(finder, TStage()));

                    _popState(finder, TStage());
                }
            }
        }
    }

#ifdef SEQAN_DEBUG
    _printReturn(finder, TStage());
#endif
}

// ----------------------------------------------------------------------------
// Function _find()
// ----------------------------------------------------------------------------

template <typename TText, typename TTextIndexSpec, typename TPattern, typename TPatternIndexSpec, typename TDistance, typename TSpec, typename TValue, typename TDelegate>
inline void
_find(Finder_<Index<TText, TTextIndexSpec>, Index<TPattern, TPatternIndexSpec>, Backtracking<TDistance, TSpec> > & finder,
      Index<TText, TTextIndexSpec> & text,
      Index<TPattern, TPatternIndexSpec> & pattern,
      TValue maxScore,
      TDelegate & delegate)
{
    typedef Index<TText, TTextIndexSpec>                                                TTextIndex;
    typedef Index<TPattern, TPatternIndexSpec>                                          TPatternIndex;
    typedef Backtracking<TDistance, TSpec>                                              TBacktracking;
    typedef typename TextIterator_<TTextIndex, TPatternIndex, TBacktracking>::Type      TTextIterator;
    typedef typename PatternIterator_<TTextIndex, TPatternIndex, TBacktracking>::Type   TPatternIterator;

    TTextIterator textIt(text);
    TPatternIterator patternIt(pattern);

    _setScoreThreshold(finder, maxScore);
    _initState(finder, textIt, patternIt);
    _find(finder, delegate, StageInitial_());
    _popState(finder, StageInitial_());
}

}

#endif  // #ifndef SEQAN_FIND_BACKTRACKING_MULTIPLE_H_