-
Notifications
You must be signed in to change notification settings - Fork 6
/
bwtindex.c
1696 lines (1646 loc) · 70.5 KB
/
bwtindex.c
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
/* ================================================================= *
* bwtindex.c : FM-Index *
* *
* slaMEM: MUMmer-like tool to retrieve Maximum Exact Matches using *
* an FM-Index and a Sampled Longest Common Prefix Array *
* *
* Copyright (c) 2013, Francisco Fernandes <[email protected]> *
* Knowledge Discovery in Bioinformatics group (KDBIO/INESC-ID) *
* All rights reserved *
* *
* This file is subject to the terms and conditions defined in the *
* file 'LICENSE', which is part of this source code package. *
* ================================================================= */
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include "bwtindex.h"
#include "packednumbers.h"
#define BUILD_LCP 1
//#define UNBOUNDED_LCP 1 // if the lcp values are unbounded (int) or truncated to 255 (unsigned char)
//#define DEBUG_INDEX 1
//#define FILL_INDEX 1
#ifdef DEBUG_INDEX
#include <sys/timeb.h>
#endif
//#define FILEHEADER "IDX0"
// TODO: implement BWT with an wavelet tree
typedef struct _IndexBlock { // 9*32 bits / 32 char per block = 9 bits per char
unsigned int bwtBits[3]; // 3 bits (x32) for the letters in this order: $NACGT (000 to 101)
unsigned int letterJumpsSample[5]; // cumulative counts for NACGT (not $) up to but *not* including this block
unsigned int textPositionSample; // position in the text of the first suffix in this block
} IndexBlock;
#define ALPHABETSIZE 6
//static const char letterChars[ALPHABETSIZE] = { '$' , 'N' , 'A' , 'C' , 'G' , 'T' }; // get letter char from letter id
#define LETTERCHARS "$NACGT"
//static const unsigned int sampleIntervalSize = 32; // = (1<<sampleIntervalShift) = 32
#define SAMPLEINTERVALSIZE 32
//static const unsigned int sampleIntervalShift = 5; // sample interval of 32 positions (2^5=32)
#define SAMPLEINTERVALSHIFT 5
//static const unsigned int sampleIntervalMask = 0x0000001F; // = ((1<<sampleIntervalShift)-1) = (32-1)
#define SAMPLEINTERVALMASK 0x0000001F
//static const unsigned int firstLetterMask = 0x00000001; // lowest bit
#define FIRSTLETTERMASK 0x00000001
// Masks to select only the bit at the offset = (1UL<<offset)
static const unsigned int offsetMasks[32] = {
0x00000001, // 1st bit
0x00000002, // 2nd bit
0x00000004, // 3rd bit
0x00000008, // 4th bit
0x00000010, // 5th bit
0x00000020, // 6th bit
0x00000040, // 7th bit
0x00000080, // 8th bit
0x00000100, // 9th bit
0x00000200, // 10th bit
0x00000400, // 11th bit
0x00000800, // 12th bit
0x00001000, // 13th bit
0x00002000, // 14th bit
0x00004000, // 15th bit
0x00008000, // 16th bit
0x00010000, // 17th bit
0x00020000, // 18th bit
0x00040000, // 19th bit
0x00080000, // 20th bit
0x00100000, // 21st bit
0x00200000, // 22nd bit
0x00400000, // 23rd bit
0x00800000, // 24th bit
0x01000000, // 25th bit
0x02000000, // 26th bit
0x04000000, // 27th bit
0x08000000, // 28th bit
0x10000000, // 29th bit
0x20000000, // 30th bit
0x40000000, // 31st bit
0x80000000 // 32nd bit
};
// Masks to select all the bits before (but not at) the offset = ((1UL<<offset)-1UL)
static const unsigned int searchOffsetMasks[33] = {
0x00000000, // lower 0 letters
0x00000001, // lower 1 letters
0x00000003, // lower 2 letters
0x00000007, // lower 3 letters
0x0000000F, // lower 4 letters
0x0000001F, // lower 5 letters
0x0000003F, // lower 6 letters
0x0000007F, // lower 7 letters
0x000000FF, // lower 8 letters
0x000001FF, // lower 9 letters
0x000003FF, // lower 10 letters
0x000007FF, // lower 11 letters
0x00000FFF, // lower 12 letters
0x00001FFF, // lower 13 letters
0x00003FFF, // lower 14 letters
0x00007FFF, // lower 15 letters
0x0000FFFF, // lower 16 letters
0x0001FFFF, // lower 17 letters
0x0003FFFF, // lower 18 letters
0x0007FFFF, // lower 19 letters
0x000FFFFF, // lower 20 letters
0x001FFFFF, // lower 21 letters
0x003FFFFF, // lower 22 letters
0x007FFFFF, // lower 23 letters
0x00FFFFFF, // lower 24 letters
0x01FFFFFF, // lower 25 letters
0x03FFFFFF, // lower 26 letters
0x07FFFFFF, // lower 27 letters
0x0FFFFFFF, // lower 28 letters
0x1FFFFFFF, // lower 29 letters
0x3FFFFFFF, // lower 30 letters
0x7FFFFFFF, // lower 31 letters
0xFFFFFFFF // lower 32 letters
};
static const unsigned int inverseLetterBitMasks[ALPHABETSIZE][3] = {
{
0xFFFFFFFF, // 1st bit mask for '$' (000): ~0...0 = 1...1
0xFFFFFFFF, // 2nd bit mask for '$' (000): ~0...0 = 1...1
0xFFFFFFFF, // 3rd bit mask for '$' (000): ~0...0 = 1...1
},{
0x00000000, // 1st bit mask for 'N' (001): ~1...1 = 0...0
0xFFFFFFFF, // 2nd bit mask for 'N' (001): ~0...0 = 1...1
0xFFFFFFFF // 3rd bit mask for 'N' (001): ~0...0 = 1...1
},{
0xFFFFFFFF, // 1st bit mask for 'A' (010): ~0...0 = 1...1
0x00000000, // 2nd bit mask for 'A' (010): ~1...1 = 0...0
0xFFFFFFFF // 3rd bit mask for 'A' (010): ~0...0 = 1...1
},{
0x00000000, // 1st bit mask for 'C' (011): ~1...1 = 0...0
0x00000000, // 2nd bit mask for 'C' (011): ~1...1 = 0...0
0xFFFFFFFF // 3rd bit mask for 'C' (011): ~0...0 = 1...1
},{
0xFFFFFFFF, // 1st bit mask for 'G' (100): ~0...0 = 1...1
0xFFFFFFFF, // 2nd bit mask for 'G' (100): ~0...0 = 1...1
0x00000000 // 3rd bit mask for 'G' (100): ~1...1 = 0...0
},{
0x00000000, // 1st bit mask for 'T' (101): ~1...1 = 0...0
0xFFFFFFFF, // 2nd bit mask for 'T' (101): ~0...0 = 1...1
0x00000000 // 3rd bit mask for 'T' (101): ~1...1 = 0...0
}
};
static IndexBlock *Index = NULL;
static unsigned int bwtSize = 0; // textSize plus counting with the terminator char too
static unsigned int numSamples = 0;
static char *text = NULL;
//static PackedNumberArray *packedText = NULL;
static PackedNumberArray *packedBwt = NULL;
static char *textFilename = NULL;
static unsigned char *letterIds = NULL;
#ifdef BUILD_LCP
#ifdef UNBOUNDED_LCP
// use array of ints for storing LCP values
static int *LCPArray;
#else
// use array of chars for storing LCP values (truncate to 255)
static unsigned char *LCPArray;
#endif
#endif
#ifdef DEBUG_INDEX
// used to count number of backtracking steps when searching for a text position in function FMI_PositionInText()
static unsigned int numBackSteps;
#endif
// variables and arrays needed to support a text composed of multiple strings
static char **multiStringTexts;
static char *multiStringLastChar;
static unsigned int *multiStringFirstPos;
static unsigned int multiStringPosShift;
static unsigned int *multiStringIdInBlock;
void InitializeIndexArrays(){
int i;
letterIds=(unsigned char *)malloc(256*sizeof(unsigned char));
for(i=0;i<256;i++) letterIds[i]=(unsigned char)1; // ACGT, N and $
letterIds[(int)'\0']=(unsigned char)0;
letterIds[(int)'$']=(unsigned char)0;
letterIds[(int)'N']=(unsigned char)1;
letterIds[(int)'A']=(unsigned char)2;
letterIds[(int)'C']=(unsigned char)3;
letterIds[(int)'G']=(unsigned char)4;
letterIds[(int)'T']=(unsigned char)5;
letterIds[(int)'n']=(unsigned char)1;
letterIds[(int)'a']=(unsigned char)2;
letterIds[(int)'c']=(unsigned char)3;
letterIds[(int)'g']=(unsigned char)4;
letterIds[(int)'t']=(unsigned char)5;
/*
unsigned int mask, twoMasks[2];
offsetMasks = (unsigned int *)malloc(SAMPLEINTERVALSIZE*sizeof(unsigned int));
searchOffsetMasks = (unsigned int *)malloc((SAMPLEINTERVALSIZE+1)*sizeof(unsigned int));
searchOffsetMasks[0] = 0x00000000;
mask = 0x00000001;
for(i=1;i<=SAMPLEINTERVALSIZE;i++){
offsetMasks[(i-1)] = mask; // from 0 to 31
searchOffsetMasks[i] = ( searchOffsetMasks[(i-1)] | mask ); // from 1 to 32
mask = ( mask << 1 );
}
inverseLetterBitMasks = (unsigned int **)malloc(3*sizeof(unsigned int *));
for(i=0;i<3;i++) inverseLetterBitMasks[i] = (unsigned int *)malloc(ALPHABETSIZE*sizeof(unsigned int));
twoMasks[0] = 0xFFFFFFFF;
twoMasks[1] = 0x00000000;
for(i=0;i<ALPHABETSIZE;i++){
inverseLetterBitMasks[i][0] = twoMasks[ (i & 0x1) ]; // if 1st bit = 1 , mask = ~0xFFFFFFFF , else mask = ~0x00000000
inverseLetterBitMasks[i][1] = twoMasks[ ((i & 0x2) >> 1) ]; // 2nd bit
inverseLetterBitMasks[i][2] = twoMasks[ ((i & 0x4) >> 2) ]; // 3rd bit
}
*/
}
void FMI_FreeIndex(){
if(textFilename!=NULL){
free(textFilename);
textFilename=NULL;
}
if(Index!=NULL){
free(Index);
Index=NULL;
}
if(letterIds!=NULL){
free(letterIds);
letterIds=NULL;
}
if(multiStringTexts!=NULL){
free(multiStringLastChar);
free(multiStringFirstPos);
free(multiStringIdInBlock);
multiStringLastChar=NULL;
multiStringFirstPos=NULL;
multiStringIdInBlock=NULL;
multiStringTexts=NULL;
}
/*
if(offsetMasks!=NULL){
free(offsetMasks);
offsetMasks=NULL;
}
if(searchOffsetMasks!=NULL){
free(searchOffsetMasks);
searchOffsetMasks=NULL;
}
if(inverseLetterBitMasks!=NULL){
for(i=0;i<ALPHABETSIZE;i++) free(inverseLetterBitMasks[i]);
free(inverseLetterBitMasks);
inverseLetterBitMasks=NULL;
}
*/
}
unsigned int FMI_GetTextSize(){
return (bwtSize-1); // the bwtSize variable counts the terminator char too
}
unsigned int FMI_GetBWTSize(){
return bwtSize;
}
char *FMI_GetTextFilename(){
return textFilename;
}
static __inline void SetCharAtBWTPos( unsigned int bwtpos , unsigned int charid ){
unsigned int sample = ( bwtpos >> SAMPLEINTERVALSHIFT );
IndexBlock *block = &(Index[sample]); // get sample block
unsigned int offset = ( bwtpos & SAMPLEINTERVALMASK );
unsigned int mask = ( ~ offsetMasks[offset] ); // get all bits except the one at the offset
unsigned int *letterMasks = (unsigned int *)(inverseLetterBitMasks[charid]);
(block->bwtBits[0]) &= mask; // reset bits
(block->bwtBits[1]) &= mask;
(block->bwtBits[2]) &= mask;
mask = offsetMasks[offset]; // get only the bit at the offset
(block->bwtBits[0]) |= ( (~letterMasks[0]) & mask ); // set bits
(block->bwtBits[1]) |= ( (~letterMasks[1]) & mask );
(block->bwtBits[2]) |= ( (~letterMasks[2]) & mask );
}
// TODO: check if creating masks on-the-fly is faster than fetching them from array
static __inline unsigned int GetCharIdAtBWTPos( unsigned int bwtpos ){
unsigned int sample, offset, mask, charid;
IndexBlock *block;
sample = ( bwtpos >> SAMPLEINTERVALSHIFT );
offset = ( bwtpos & SAMPLEINTERVALMASK );
block = &(Index[sample]); // get sample block
mask = offsetMasks[offset]; // get only the bit at the offset
charid = ( ( (block->bwtBits[0]) >> offset ) & FIRSTLETTERMASK ); // get 1st bit
charid |= ( ( ( (block->bwtBits[1]) >> offset ) & FIRSTLETTERMASK ) << 1 ); // get 2nd bit
charid |= ( ( ( (block->bwtBits[2]) >> offset ) & FIRSTLETTERMASK ) << 2 ); // get 3rd bit
return charid;
/**/
// TODO: remove this!
mask = mask;
/**/
}
__inline char FMI_GetCharAtBWTPos( unsigned int bwtpos ){
IndexBlock *block;
unsigned int offset, charid;
offset = ( bwtpos & SAMPLEINTERVALMASK );
block = &(Index[( bwtpos >> SAMPLEINTERVALSHIFT )]); // get sample block
charid = ( ( (block->bwtBits[0]) >> offset ) & FIRSTLETTERMASK ); // get 1st bit
charid |= ( ( ( (block->bwtBits[1]) >> offset ) & FIRSTLETTERMASK ) << 1 ); // get 2nd bit
charid |= ( ( ( (block->bwtBits[2]) >> offset ) & FIRSTLETTERMASK ) << 2 ); // get 3rd bit
return LETTERCHARS[charid]; // get letter char
}
__inline unsigned int BitsSetCount( unsigned int bitArray ){
/*
while( bitArray ){
letterJump++; // if other equal letters exist, increase letter jump
bitArray &= ( bitArray - 1U ); // clear lower occurrence bit
}
*/
/*
letterJump += perByteCounts[ ( bitArray & 0x000000FF ) ];
letterJump += perByteCounts[ ( bitArray & 0x0000FF00 ) >> 8 ];
letterJump += perByteCounts[ ( bitArray & 0x00FF0000 ) >> 16 ];
letterJump += perByteCounts[ ( bitArray >> 24 ) ];
*/
//bitArray = ( bitArray & 0x55555555 ) + ( ( bitArray >> 1 ) & 0x55555555 ); // sum blocks of 1 bits ; 0x5 = 0101b ; 2 bits ( final max count = 2 -> 2 bits )
bitArray = bitArray - ( ( bitArray >> 1 ) & 0x55555555 );
bitArray = ( bitArray & 0x33333333 ) + ( ( bitArray >> 2 ) & 0x33333333 ); // sum blocks of 2 bits ; 0x3 = 0011b ; 4 bits ( final max count = 4 -> 3 bits )
bitArray = ( ( bitArray + ( bitArray >> 4 ) ) & 0x0F0F0F0F ); // sum blocks of 4 bits ; 0x0F = 00001111b ; 8 bits ( final max count = 8 -> 4 bits )
//bitArray = ( bitArray + ( bitArray >> 8 ) ); // sum blocks of 8 bits ; the final count will be at most 32, which is 6 bits, and since we now have blocks of 8 bits, we can add them without masking because there will not be any overflow
//bitArray = ( ( bitArray + ( bitArray >> 16 ) ) & 0x0000003F ); // sum blocks of 16 bits and get the last 6 bits ( final max count = 32 -> 6 bits )
bitArray = ( ( bitArray * 0x01010101 ) >> 24 );
return bitArray;
}
// NOTE: if letterId is not at position bwtPos, it considers the jump of the previous occurence behind/above
// NOTE: it assumes we will never try to do a letter jump by the terminator symbol, since there are no jumps stored in the index for it
static __inline unsigned int FMI_LetterJump( unsigned int letterId , unsigned int bwtPos ){
unsigned int offset, bitArray, letterJump, *letterMasks;
IndexBlock *block;
letterMasks = (unsigned int *)(inverseLetterBitMasks[letterId]);
offset = ( bwtPos & SAMPLEINTERVALMASK );
block = &(Index[( bwtPos >> SAMPLEINTERVALSHIFT )]);
bitArray = searchOffsetMasks[(offset+1)]; // all bits bellow and at offset (+1 otherwise it would not include the bit at the offset)
bitArray &= ( (block->bwtBits[0]) ^ letterMasks[0] ); // keep only positions with the same 1st bit
bitArray &= ( (block->bwtBits[1]) ^ letterMasks[1] ); // keep only positions with the same 2nd bit
bitArray &= ( (block->bwtBits[2]) ^ letterMasks[2] ); // keep only positions with the same 3rd bit
letterJump = (block->letterJumpsSample[(letterId-1)]); // get last letter jump before this block (jumps for '$' are not stored, so it is (letterId-1))
#if defined(__GNUC__) && defined(__SSE4_2__)
return ( letterJump + __builtin_popcount( bitArray ) );
#else
return ( letterJump + BitsSetCount( bitArray ) );
#endif
}
// NOTE: returns the size of the BWT interval if a match exists, and 0 otherwise
unsigned int FMI_FollowLetter( char c , unsigned int *topPointer , unsigned int *bottomPointer ){
/*
unsigned int charId;
unsigned int originalTopPointer;
charId = letterIds[(unsigned char)c];
originalTopPointer = (*topPointer);
(*topPointer) = FMI_LetterJump( charId , (*topPointer) );
if( GetCharIdAtBWTPos( originalTopPointer ) != charId ) (*topPointer)++; // if the letter is not in the topPointer position, its next occurrence is after that
(*bottomPointer) = FMI_LetterJump( charId , (*bottomPointer) );
*/
unsigned int letterId, offset, bitArray, *letterMasks;
IndexBlock *block;
letterId = letterIds[(unsigned char)c];
letterMasks = (unsigned int *)(inverseLetterBitMasks[letterId]);
offset = ( (*topPointer) & SAMPLEINTERVALMASK );
block = &(Index[( (*topPointer) >> SAMPLEINTERVALSHIFT )]);
bitArray = searchOffsetMasks[offset]; // exclusive search mask on top pointer (all bits only bellow offset)
bitArray &= ( (block->bwtBits[0]) ^ letterMasks[0] );
bitArray &= ( (block->bwtBits[1]) ^ letterMasks[1] );
bitArray &= ( (block->bwtBits[2]) ^ letterMasks[2] );
(*topPointer) = (block->letterJumpsSample[(letterId-1)]);
#if defined(__GNUC__) && defined(__SSE4_2__)
(*topPointer) += __builtin_popcount( bitArray );
#else
(*topPointer) += BitsSetCount( bitArray );
#endif
(*topPointer)++; // if the letter is not in the topPointer position, its next occurrence is after that: LF[top]=count(c,(top-1))+1
offset = ( (*bottomPointer) & SAMPLEINTERVALMASK );
block = &(Index[( (*bottomPointer) >> SAMPLEINTERVALSHIFT )]);
bitArray = searchOffsetMasks[(offset+1)]; // inclusive search mask on bottom pointer (all bits bellow and at offset)
bitArray &= ( (block->bwtBits[0]) ^ letterMasks[0] );
bitArray &= ( (block->bwtBits[1]) ^ letterMasks[1] );
bitArray &= ( (block->bwtBits[2]) ^ letterMasks[2] );
(*bottomPointer) = (block->letterJumpsSample[(letterId-1)]);
#if defined(__GNUC__) && defined(__SSE4_2__)
(*bottomPointer) += __builtin_popcount( bitArray );
#else
(*bottomPointer) += BitsSetCount( bitArray );
#endif
if( (*topPointer) > (*bottomPointer) ) return 0;
return ( (*bottomPointer) - (*topPointer) + 1 );
}
unsigned int FMI_PositionInText( unsigned int bwtpos ){
unsigned int charid, addpos;
addpos = 0;
while( bwtpos & SAMPLEINTERVALMASK ){ // move backwards until we land on a position with a sample
charid = GetCharIdAtBWTPos(bwtpos);
if( charid == 0 ){ // check if this is the terminator char
#ifdef DEBUG_INDEX
numBackSteps = addpos;
#endif
return addpos;
}
bwtpos = FMI_LetterJump( charid , bwtpos ); // follow the left letter backwards
addpos++; // one more position away from our original position
}
#ifdef DEBUG_INDEX
numBackSteps = addpos;
#endif
return ( (Index[( bwtpos >> SAMPLEINTERVALSHIFT )].textPositionSample) + addpos );
}
// returns the new position in the BWT array after left jumping by the char at the given BWT position
unsigned int FMI_LeftJump( unsigned int bwtpos ){
unsigned int charid;
charid = GetCharIdAtBWTPos( bwtpos );
if( charid == 0 ) return 0U; // terminator symbol jumps to the 0-th position of the BWT
else return FMI_LetterJump( charid , bwtpos ); // follow the left letter backwards
}
void FMI_GetCharCountsAtBWTInterval(unsigned int topPtr, unsigned int bottomPtr, int *counts){
unsigned int offset, charid;
IndexBlock *block;
counts[0] = 0; // reset counts for chars: A,C,G,T,N
counts[1] = 0;
counts[2] = 0;
counts[3] = 0;
counts[4] = 0;
block = &(Index[( topPtr >> SAMPLEINTERVALSHIFT )]);
offset = ( topPtr & SAMPLEINTERVALMASK );
while( topPtr <= bottomPtr ){ // process all positions of interval
if( offset == SAMPLEINTERVALSIZE ){ // go to next sample block if needed
offset = 0UL;
block++;
}
charid = ( ( (block->bwtBits[0]) >> offset ) & FIRSTLETTERMASK ); // get 1st bit
charid |= ( ( ( (block->bwtBits[1]) >> offset ) & FIRSTLETTERMASK ) << 1 ); // get 2nd bit
charid |= ( ( ( (block->bwtBits[2]) >> offset ) & FIRSTLETTERMASK ) << 2 ); // get 3rd bit
if( charid >= 2 ) counts[(charid - 2)]++; // ACGT
else counts[4]++; // '$' or 'N'
offset++;
topPtr++;
}
}
void PrintUnsignedNumber( unsigned int number ){
unsigned int num, denom, quot, rem;
if( number < 1000 ){
printf( "%u" , number );
return;
}
denom = 1;
num = number;
while( num >= 1000 ){
num /= 1000;
denom *= 1000;
}
printf( "%u," , num );
num = ( number - num * denom );
denom /= 1000;
while( denom > 1 ){
quot = ( num / denom );
rem = ( num - quot * denom );
printf( "%03u," , quot );
num = rem;
denom /= 1000;
}
printf( "%03u" , num );
}
/*
void FMI_LoadIndex(char *indexfilename){
FILE *indexfile;
size_t readcount;
fpos_t filepos;
unsigned int i;
long long int seqstart, seqend, seqsize;
char c;
char fileHeader[5] = FILEHEADER;
printf("> Loading index from file <%s> ... ",indexfilename);
fflush(stdout);
indexfile = fopen(indexfilename,"rb");
if( indexfile == NULL ){
printf("\n> ERROR: Cannot open file\n");
exit(0);
}
seqstart=(long long int)ftell(indexfile);
fseek(indexfile,0L,SEEK_END);
seqend=(long long int)ftell(indexfile);
seqsize=(seqend-seqstart);
rewind(indexfile);
printf("(");PrintNumber(seqsize);printf(" bytes)");
fflush(stdout);
for(i=0;i<4;i++){ // check if header is "IDX0"
fread( &c , sizeof(char) , (size_t)1 , indexfile );
if( c != fileHeader[i] ) break;
}
if( i != 4 ){
printf("\n> ERROR: Invalid index file\n");
exit(0);
}
fgetpos(indexfile,&filepos);
i=0;
while( c!='\0' && c!=EOF ){ // get text filename size
fread( &c , sizeof(char) , (size_t)1 , indexfile );
i++;
}
textFilename=(char *)malloc((i)*sizeof(char));
fsetpos(indexfile,&filepos);
fread( textFilename , sizeof(char) , (size_t)i , indexfile ); // get text filename chars
fread( &textSize , sizeof(unsigned int) , (size_t)1 , indexfile ); // counts the terminator char too, so it is actually the BWT size
fread( &numSamples , sizeof(unsigned int) , (size_t)1 , indexfile );
#ifdef DEBUG
printf("\n [textFilename=\"%s\";textSize=%u;numSamples=%u]",textFilename,textSize,numSamples);
fflush(stdout);
#endif
i = ( ( ( textSize-1 ) >> SAMPLEINTERVALSHIFT ) + 1 );
if( ((textSize-1) & SAMPLEINTERVALMASK) != 0 ) i++; // extra sample
if( numSamples != i ){ // check if number of samples is correct based on text size
printf("\n> ERROR: Invalid index data\n");
exit(0);
}
Index = (IndexBlock *)malloc( numSamples * sizeof(IndexBlock) ); // allocate memory for all index blocks
if( Index == NULL ){
printf("\n> ERROR: Not enough memory\n");
exit(0);
}
readcount = fread( Index , sizeof(IndexBlock) , (size_t)(numSamples) , indexfile ); // read all index blocks
if( readcount != (size_t)numSamples ){
printf("\n> ERROR: Incomplete index data\n");
exit(0);
}
fclose(indexfile);
InitializeLetterIdsArray(); // initialize arrays used by index functions
lastAlignedBwtPos = ((numSamples-1) << SAMPLEINTERVALSHIFT); // set last BWT pos for pattern matching initialization
printf(" OK\n");
fflush(stdout);
}
// TODO: ??? use indexBlocksStartInFile, distanceToNextBlockBits
void FMI_SaveIndex(char *indexfilename){
FILE *indexfile;
size_t writecount;
long long int filesize;
int i;
printf("> Saving index to file <%s> ... ",indexfilename);
fflush(stdout);
indexfile = fopen(indexfilename,"wb");
if( indexfile == NULL ){
printf("\n> ERROR: Cannot create file\n");
exit(0);
}
i=0;
while(textFilename[i]!='\0') i++; // get text filename size
i++;
fwrite( (FILEHEADER) , sizeof(char) , (size_t)4 , indexfile );
fwrite( textFilename , sizeof(char) , (size_t)i , indexfile );
fwrite( &textSize , sizeof(unsigned int) , (size_t)1 , indexfile );
fwrite( &numSamples , sizeof(unsigned int) , (size_t)1 , indexfile );
writecount = fwrite( Index , sizeof(IndexBlock) , (size_t)(numSamples) , indexfile );
if( writecount != (size_t)(numSamples) ){
printf("\n> ERROR: Cannot write file\n");
exit(0);
}
filesize=(long long int)ftell(indexfile);
fclose(indexfile);
printf("(");PrintNumber(filesize);printf(" bytes) OK\n");
fflush(stdout);
}
*/
// Function pointer to get char id at corresponding text position
unsigned int (*GetTextCharId)(unsigned int);
// TODO: add code/functions for circular text and for packed binary text
// NOTE: the last pos (pos=textSize) is '\0' which maps to the id of '$' through the letterIds lookup table
unsigned int GetTextCharIdFromPlainText(unsigned int pos){
return (unsigned int)letterIds[(unsigned char)text[pos]];
}
// Creates a lookup table with entries corresponding to blocks of size floor(log2(smallest_sequence)) and containing the sequence id at the first pos of each block
unsigned int InitializeMultiStringArrays(char **texts, unsigned int *textSizes, unsigned int numTexts){
unsigned int id, pos, blockSize, blockNum, globalStringSize;
multiStringTexts = texts;
multiStringLastChar = (char *)malloc(numTexts*sizeof(char)); // terminator chars for each string
multiStringFirstPos = (unsigned int *)malloc((numTexts+1)*sizeof(unsigned int)); // start pos in global string, plus one fake position after last one
blockSize = UINT_MAX; // size of shortest string
pos = 0; // position in global string
for (id = 0; id < numTexts; id++){
multiStringFirstPos[id] = pos;
multiStringLastChar[id] = 'N';
if (textSizes[id] < blockSize) blockSize = textSizes[id];
pos += (textSizes[id] + 1); // string size plus extra terminator char
}
multiStringLastChar[(numTexts-1)] = '$'; // terminator char for global string
multiStringFirstPos[numTexts] = pos; // fake next to last string
globalStringSize = pos;
multiStringPosShift = 1;
while ((1UL << (multiStringPosShift + 1)) < blockSize) multiStringPosShift++; // get highest power of two lower or equal to the minimum size
blockSize = (1UL << multiStringPosShift); // size of each block
blockNum = (((globalStringSize - 1) >> multiStringPosShift) + 1); // total number of blocks
multiStringIdInBlock = (unsigned int *)malloc(blockNum*sizeof(unsigned int)); // string id at the beginning of each block
id = 0;
pos = 0;
blockNum = 0;
while (pos <= (globalStringSize - 1)){ // fill the string id in all blocks
if (pos >= multiStringFirstPos[(id + 1)]) id++; // if the 1st pos of this block is at or after the 1st of the next string, set next string as current
multiStringIdInBlock[blockNum] = id;
pos += blockSize; // next block
blockNum++;
}
return globalStringSize;
}
// TODO: check implementation with binary search tree of shared and distinct bits of all numbers belonging to the same/different sequences
unsigned int GetTextCharIdFromMultipleStrings(unsigned int pos){
unsigned int id, lastPos;
id = multiStringIdInBlock[(pos >> multiStringPosShift)]; // string id at beginning of block containing this pos
lastPos = (multiStringFirstPos[id + 1] - 1); // last pos of this string
if (pos >= lastPos){
if (pos == lastPos) return (unsigned int)letterIds[(unsigned char)multiStringLastChar[id]]; // virtual last char of this string
id++; // the pos is on the next string
}
pos -= multiStringFirstPos[id]; // get pos inside string
return (unsigned int)letterIds[(unsigned char)(multiStringTexts[id][pos])];
}
void PrintBWT(unsigned int *letterStartPos){
unsigned int i, n, p;
printf("%u {", bwtSize);
for (n = 1; n < ALPHABETSIZE; n++){
printf(" %c [%02u-%02u] %c", LETTERCHARS[n], letterStartPos[n], (n == (ALPHABETSIZE - 1)) ? (bwtSize - 1) : (letterStartPos[(n + 1)] - 1), (n == (ALPHABETSIZE - 1)) ? '}' : ',');
}
printf(" 2^%u=%u %u %#.8X\n", SAMPLEINTERVALSHIFT, SAMPLEINTERVALSIZE, numSamples, SAMPLEINTERVALMASK);
printf("[ i] (SA) {");
for (n = 1; n < ALPHABETSIZE; n++){
printf(" %c%c", LETTERCHARS[n], (n == (ALPHABETSIZE - 1)) ? '}' : ',');
}
#ifdef BUILD_LCP
if (LCPArray != NULL) printf(" LCP");
#endif
printf(" BWT\n");
for (i = 0; i < bwtSize; i++){ // position in BWT
p = FMI_PositionInText(i);
printf("[%02u]%c(%2u) {", i, (i & SAMPLEINTERVALMASK) ? ' ' : '*', p);
for (n = 1; n < ALPHABETSIZE; n++){
printf("%02u%c", FMI_LetterJump(n, i), (n == (ALPHABETSIZE - 1)) ? '}' : ',');
}
#ifdef BUILD_LCP
if (LCPArray != NULL) printf(" %3d", (int)LCPArray[i]);
#endif
printf(" %c ", FMI_GetCharAtBWTPos(i));
n = 0;
while ((n < (ALPHABETSIZE - 1)) && (i >= letterStartPos[(n + 1)])) n++;
printf(" %c ", LETTERCHARS[n]);
if (p != (bwtSize - 1)) p++; // char at the right of the BWT char
else p = 0;
//if( text != NULL ) printf("%s", (char *)(text+p) );
while (p != bwtSize){
n = GetTextCharId(p);
printf(" %c ", LETTERCHARS[n]);
p++;
}
printf("\n");
}
}
typedef struct _LMSPos {
unsigned int pos;
#ifdef BUILD_LCP
int lcp;
#endif
int next;
} LMSPos;
static LMSPos *LMSArray;
static int numLMS;
char GetCharType(unsigned int pos){
char prevType, currentType;
if(pos==bwtSize) return 'S'; // last position
if(pos==0 || GetTextCharId(pos-1)<GetTextCharId(pos)) prevType='s';
else if(GetTextCharId(pos-1)>GetTextCharId(pos)) prevType='l';
else prevType='?';
while(pos!=(bwtSize-1) && GetTextCharId(pos)==GetTextCharId(pos+1)) pos++;
if(pos==(bwtSize-1) || GetTextCharId(pos)>GetTextCharId(pos+1)) currentType='l';
else currentType='s';
if(prevType=='?') prevType=currentType;
if(prevType!=currentType) currentType-=32; // S*-type or L*-type
return currentType;
}
// NOTE: fills the global LMSArray variable and the input charsCounts and charsFirstPos arrays
void GetLMSs( unsigned int *charsCounts , int *charsFirstPos , char verbose ){
int arrayMaxSize, arrayGrowSize;
int *charsLastPos;
unsigned int i, j, n;
char type;
unsigned int progressCounter, progressStep;
if(verbose){
printf("> Collecting LMS positions ");
fflush(stdout);
}
progressStep = (bwtSize/10);
progressCounter = 0;
charsLastPos = (int *)malloc(ALPHABETSIZE*sizeof(int));
for( i = 0 ; i < ALPHABETSIZE ; i++ ){ // initialize chars buckets
charsCounts[i] = 0;
charsFirstPos[i] = (-1);
charsLastPos[i] = (-1);
}
arrayGrowSize = (bwtSize/20); // how much to expand the LMS array each time we allocate more memory (5%)
if( arrayGrowSize == 0 ) arrayGrowSize = 20;
arrayMaxSize = 0;
LMSArray = NULL;
n = (bwtSize-1);
j = GetTextCharId(n); // last char ('$')
charsCounts[j]++;
type = 'S'; // type of last char
numLMS = 0; // current number of LMS (last char is S*-type but it will only be counted next)
while( n != 0 ){ // process text in reverse from end to start
if(verbose){
progressCounter++;
if(progressCounter==progressStep){ // print progress dots
printf(".");
fflush(stdout);
progressCounter=0;
}
}
n--; // previous position
i = GetTextCharId(n); // current char
charsCounts[i]++;
if( i < j ) type = 'S'; // lower suffix, S-type char
else if ( i > j ){ // higher suffix, L-type char
if( type == 'S' ){ // if last char was S-type and this one is L-type, last one was S*-type
if( numLMS == arrayMaxSize ){
arrayMaxSize += arrayGrowSize;
LMSArray = (LMSPos *)realloc(LMSArray,((size_t)arrayMaxSize)*sizeof(LMSPos));
if( LMSArray == NULL ){
printf("\n> ERROR: Failed to allocate %lld MB of memory\n",(((long long int)arrayMaxSize)*sizeof(LMSPos))/1000000LL);
exit(-1);
}
}
LMSArray[numLMS].pos = (n+1); // the previous position (to the right) is an S*-type char
if( charsFirstPos[j] != (-1) ) LMSArray[ charsLastPos[j] ].next = numLMS; // add to linked list of this char id
else charsFirstPos[j] = numLMS; // first char with this id
charsLastPos[j] = numLMS; // current last char with this id
numLMS++;
}
type = 'L';
} // else (i==j), so use last used type
j = i; // current char will be previous char on next step
}
LMSArray = (LMSPos *)realloc(LMSArray,numLMS*sizeof(LMSPos)); // shrink array to fit exact number of items
for( i = 0 ; i < ALPHABETSIZE ; i++ ){ // set last position for each char bucket
if( charsLastPos[i] != (-1) ) LMSArray[ charsLastPos[i] ].next = (-1);
}
free(charsLastPos);
if(verbose){
printf(" (%d) OK\n",numLMS);
fflush(stdout);
}
}
typedef struct _SortDepthState {
unsigned int depth;
int numChars;
int charsFirstPos[ALPHABETSIZE];
#ifdef DEBUG_INDEX
int charsIds[ALPHABETSIZE];
int charsCounts[ALPHABETSIZE];
#endif
} SortDepthState;
void SortLMSs( int *charsBuckets , char verbose ){
SortDepthState *sortStates;
unsigned int textPos, depth;
int prevSortedPos, prevLowestDepth, sortedCharId;
int arrayPos, charPos, statePos, maxStatePos;
int charId, numCharsToSort, nextNumCharsToSort;
int *firstPos, *lastPos;
unsigned int progressCounter, progressStep;
#ifdef DEBUG_INDEX
int prevDepth;
int *firstPosIds, *charsCounts;
int charIdToProcess;
unsigned int prevTextPos;
#endif
if(verbose){
printf("> Sorting LMS suffixes ");
fflush(stdout);
}
progressStep=(numLMS/10);
progressCounter=0;
maxStatePos = 32;
sortStates = (SortDepthState *)malloc(maxStatePos*sizeof(SortDepthState));
lastPos = (int *)malloc(ALPHABETSIZE*sizeof(int));
statePos = 0;
sortStates[0].depth = 0;
prevSortedPos = (-1);
prevLowestDepth = 0;
arrayPos = 0; // start at the first position of the linked array
/**/
depth = sortStates[0].depth;
firstPos = sortStates[0].charsFirstPos;
#ifdef DEBUG_INDEX
firstPosIds = sortStates[0].charsIds;
charsCounts = sortStates[0].charsCounts;
charIdToProcess = (-1);
prevDepth = (-1);
#endif
for( charId = 0 ; charId < ALPHABETSIZE ; charId++ ){ // initialize buckets with the already filled LMSs and reset them to save the output
firstPos[charId] = charsBuckets[charId];
charsBuckets[charId] = (-1);
#ifdef DEBUG_INDEX
firstPosIds[charId] = charId;
#endif
}
goto _skip_char_count; // consider the buckets at depth 0 already filled
/**/
while( arrayPos != (-1) ){
depth = sortStates[statePos].depth;
firstPos = sortStates[statePos].charsFirstPos;
#ifdef DEBUG_INDEX
firstPosIds = sortStates[statePos].charsIds;
charsCounts = sortStates[statePos].charsCounts;
#endif
for( charId = 0 ; charId < ALPHABETSIZE ; charId++ ){ // reset first/last pointers for each char
firstPos[charId] = (-1);
#ifdef DEBUG_INDEX
firstPosIds[charId] = (-1);
charsCounts[charId] = 0;
#endif
lastPos[charId] = (-1);
}
while( arrayPos != (-1) ){ // group all positions in this block by their first char (at the current depth)
textPos = ( LMSArray[arrayPos].pos + depth );
charId = GetTextCharId(textPos);
#ifdef DEBUG_INDEX
charsCounts[charId]++;
#endif
if( firstPos[charId] != (-1) ) LMSArray[ lastPos[charId] ].next = arrayPos; // add to already started char bucket
else {
firstPos[charId] = arrayPos; // first position in this char bucket
#ifdef DEBUG_INDEX
firstPosIds[charId] = charId;
#endif
}
lastPos[charId] = arrayPos; // set current position as the current last one of the char bucket
arrayPos = LMSArray[arrayPos].next; // next position
LMSArray[ lastPos[charId] ].next = (-1); // set end of char bucket
}
_skip_char_count:
numCharsToSort = ALPHABETSIZE; // number of char buckets to check on the next loop (if we are at a new depth, check all of them)
while(1){ // loop for backward steps (we do not need the part above because we have already stored the char buckets at lower depths)
arrayPos = (-1);
nextNumCharsToSort = 0;
#ifdef DEBUG_INDEX
charIdToProcess = (-1);
#endif
for( charId = 0 ; charId < numCharsToSort ; charId++ ){ // check count of each char bucket
charPos = firstPos[charId];
if( charPos == (-1) ) continue; // char count = 0
if( LMSArray[charPos].next == (-1) ){ // char count = 1 , which means this single position is sorted
if( nextNumCharsToSort == 0 ){ // if there is no non-single bucket to sort before, add to sorted list
if(verbose){
progressCounter++;
if(progressCounter==progressStep){ // print progress dots
printf(".");
fflush(stdout);
progressCounter=0;
}
}
if( prevLowestDepth == 0 ){ // if this is the first sorted position after a passage through depth 0, then set the top-level bucket
sortedCharId = GetTextCharId( LMSArray[charPos].pos ); // get bucket from first char
charsBuckets[sortedCharId] = charPos;
if( prevSortedPos != (-1) ){
LMSArray[prevSortedPos].next = (-1); // end previous top-level bucket
prevSortedPos = (-1);
}
}
#ifdef BUILD_LCP
LMSArray[charPos].lcp = prevLowestDepth; // set LCP for this LMS suffix
#endif
prevLowestDepth = depth; // update previously seen minimum depth between two consecutive sorted positions
if( prevSortedPos != (-1) ) LMSArray[prevSortedPos].next = charPos; // extend sorted list
prevSortedPos = charPos; // set current last position of sorted list
firstPos[charId] = (-1); // remove from list
} else { // if it's a single position but there's previous non-single buckets, we need to sort those before setting this one
firstPos[ (nextNumCharsToSort - 1) ] = charPos; // move the unprocessed buckets to the beginning of the array so they will be processed on the next time we come back to this depth
#ifdef DEBUG_INDEX
firstPosIds[ (nextNumCharsToSort - 1) ] = firstPosIds[charId];
#endif
nextNumCharsToSort++;
}
continue;
} // else, char count >= 2, which means the bucket needs further sorting
if( nextNumCharsToSort == 0 ){ // if this is the first non-singular bucket, set it to be processed next
arrayPos = charPos; // set next bucket to sort
firstPos[charId] = (-1); // set its index as free as it will be already taken care of
#ifdef DEBUG_INDEX
charIdToProcess = firstPosIds[charId];
firstPosIds[charId] = (-1);
#endif
} else { // else, there is at least one more non-singular bucket to sort
firstPos[ (nextNumCharsToSort - 1) ] = charPos; // move it to the beginning of the array to be checked when we later get back to this depth
#ifdef DEBUG_INDEX
firstPosIds[ (nextNumCharsToSort - 1) ] = firstPosIds[charId];
#endif
}
nextNumCharsToSort++;
} // end of loop to check the size of each bucket
#ifdef DEBUG_INDEX
for( charId = (nextNumCharsToSort-1) ; charId < ALPHABETSIZE ; charId++ ){
firstPosIds[charId] = (-1); // reset char ids that do not occur here
}
#endif
sortStates[statePos].numChars = (nextNumCharsToSort - 1); // update the number of unsorted buckets at this depth (the first one will already be finished when we get back to this depth)
if( nextNumCharsToSort != 0 ){ // if we have buckets left to sort, sort the first one (pointed by the previsouly set arrayPos) at the next depth
if( nextNumCharsToSort > 1 ){ // if we only have one bucket, we can save the information in the same state, otherwise we have to create a new one
statePos++;
if( statePos == maxStatePos ){ // realloc array of states if needed
maxStatePos += 32;
sortStates = (SortDepthState *)realloc(sortStates,maxStatePos*sizeof(SortDepthState));
}
}
#ifdef DEBUG_INDEX
prevDepth = depth;
#endif
depth++;
sortStates[statePos].depth = depth; // save depth for the following sorting step
break;
} // else, no more buckets left to sort at this depth, so check previous lower depths
if( statePos == 0 ){ // check if we reached the end of the array
arrayPos = (-1);
break;
}
statePos--; // previous state at lower depth
depth = sortStates[statePos].depth; // restore variables of previous state
firstPos = sortStates[statePos].charsFirstPos;
#ifdef DEBUG_INDEX
firstPosIds = sortStates[statePos].charsIds;
charsCounts = sortStates[statePos].charsCounts;
prevDepth = sortStates[(statePos+1)].depth;
#endif
numCharsToSort = sortStates[statePos].numChars;
prevLowestDepth = depth; // update previously seen minimum depth between two sorted positions
} // end of loop for backward steps
} // end of loop for all positions of the linked array
free(lastPos);
free(sortStates);
if(verbose){
printf(" OK\n");
fflush(stdout);
}
#ifdef DEBUG_INDEX
if(verbose){
printf("> Checking sort ");
fflush(stdout);
}
statePos = 0;
prevSortedPos = (-1);
for( charPos = 0 ; charPos < ALPHABETSIZE ; charPos++ ){
arrayPos = charsBuckets[charPos];
while( arrayPos != (-1) ){
if( prevSortedPos != (-1) ){
if(verbose){
progressCounter++;
if(progressCounter==progressStep){ // print progress dots
printf(".");
fflush(stdout);
progressCounter=0;
}
}
depth = 0;
while(1){
prevTextPos = (LMSArray[prevSortedPos].pos + depth);
textPos = (LMSArray[arrayPos].pos + depth);
sortedCharId = GetTextCharId(prevTextPos);
charId = GetTextCharId(textPos);
if( sortedCharId != charId ) break;
depth++;
}
if( sortedCharId > charId ){
printf("\n> ERROR: LMS[%d]@text[%d]='%c' > LMS[%d]@text[%d]='%c'\n",statePos,prevTextPos,LETTERCHARS[sortedCharId],(statePos+1),textPos,LETTERCHARS[charId]);
fflush(stdout);
charPos = INT_MAX;
break;