File: CBaitRecord.h

package info (click to toggle)
baitfisher 1.2.7%2Bgit20180107.e92dbf2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 28,216 kB
  • sloc: cpp: 30,737; makefile: 30; sh: 6
file content (1728 lines) | stat: -rw-r--r-- 56,114 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
/*  BaitFisher (version 1.2.8) a program for designing DNA target enrichment baits
 *  BaitFilter (version 1.0.6) a program for selecting optimal bait regions
 *  Copyright 2013-2017 by Christoph Mayer
 *
 *  This source file is part of the BaitFisher-package.
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with BaitFisher.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 *  For any enquiries send an Email to Christoph Mayer
 *  c.mayer.zfmk@uni-bonn.de
 *
 *  When publishing work that is based on the results please cite:
 *  Mayer et al. 2016: BaitFisher: A software package for multi-species target DNA enrichment probe design
 *  
 */
// Uses modified comparison functions to make sort stable.

#include <iostream>
#include <fstream>
#include "faststring2.h"
#include <vector>
#include <set>
#include "Ctriple.h"
#include "print_container.h"
#include "CBlastParser.h"

// Introducing this define has several advantages:
// - simple switch to stable_sort and back
// - simple find all calls to sort in this file.
#define MYSORT  sort
// Instead of using stable_sort we now use modified comparison functions. So this switch should not be necessary any more.
// #define MYSORT  stable_sort

class CBaitRegionSelectorSets
{
  std::set<faststring>                               set_of_alignment_names;
  std::set<std::pair<faststring, unsigned> >         set_of_alignment_names_feature_num;
  std::set<Ctriple<faststring, unsigned, unsigned> > set_of_alignment_name_feature_num_start__ie_locus;

 public:
  void add(const faststring &str, unsigned i, unsigned j)
  {
    set_of_alignment_names.insert(str);
    set_of_alignment_names_feature_num.insert(std::make_pair(str, i));
    set_of_alignment_name_feature_num_start__ie_locus.insert(Ctriple<faststring, unsigned, unsigned>(str,i, j));
  }


  bool exists(const faststring &str) const
  {
    if (set_of_alignment_names.find(str) != set_of_alignment_names.end() )
      return true;
    else
      return false;
  }

  bool exists(const faststring &str, unsigned i) const
  {
    if (set_of_alignment_names_feature_num.find(std::make_pair(str, i)) != set_of_alignment_names_feature_num.end() )
      return true;
    else
      return false;
  }

  bool exists(const faststring &str, unsigned i, unsigned j) const
  {
    if (set_of_alignment_name_feature_num_start__ie_locus.find(Ctriple<faststring, unsigned, unsigned>(str,i,j)) != set_of_alignment_name_feature_num_start__ie_locus.end() )
      return true;
    else
      return false;
  }

  void print_all(std::ostream &os) const
  {
    os << "Selector string (alignment) argument:" << std::endl;
    print_container(os, set_of_alignment_names, "", "\n" , "\n");
    os << "Selector string (alignment) argument, unsigned (feature number): " << std::endl;
    print_container(os, set_of_alignment_names_feature_num, "", "\n" , "\n");
    os << "Selector string (alignment) argument, unsigned (feature number), unsigned (start): " << std::endl;
    print_container(os, set_of_alignment_name_feature_num_start__ie_locus, "", "\n" , "\n");
  }

  void print_num_genes_num_features(std::ostream &os, const char *s, bool print_num_featues) const
  {
    os << s << "The bait regions belong to this number of alignment files: " << set_of_alignment_names.size() << std::endl;
    os << s << "Number of bait regions:                                    " << set_of_alignment_name_feature_num_start__ie_locus.size() << std::endl;
    if (print_num_featues)
      os << s << "Number of features                                       " << set_of_alignment_names_feature_num.size() << std::endl;
  }
};

class CBait
{
  faststring bait;
  double     CG;
  double     max_dist;
  unsigned   tiling_index;  // 1 based index in tiling array. 1: first tile; 2: second tile, etc.

 public:

  CBait(faststring &str)
  {
    faststring pre, post1, post2;

    // The error messages below could be improved. It would be a good idea to tell the user the line in the file which causes the error.
    // At the moment the user is being told the bait string or the number that causes the problem. While this should help in most cases to find the problem
    // it would be much more convenient for the user to have the line number in the file.

    str.divide_at(' ', pre, post2);
    if (!pre.isAnUnsigned())
    {
      std::cerr << "Error when parsing the bait file: Has it been edited manually?" << std::endl;
      std::cerr << "Before each bait string BaitFilter expects a number indicating the index of the tiling design column. This number could not be found for the following bait:"
		<< std::endl;
      std::cerr << str << std::endl;
      std::cerr << "Exiting." << std::endl;
      exit(-4);
    }
    tiling_index = pre.ToUnsigned();
    post2.divide_at(' ', pre, post1);
    bait = pre;
    post1.divide_at(' ', pre, post2);
    if (!pre.isADouble())
    {
      std::cerr << "Error when parsing the bait file: Has it been edited manually?" << std::endl;
      std::cerr << "After each bait string BaitFilter expects two double numbers containing the baits' CG content and its maximum distance to the MSA.\n"
		<< "Expecting a double number for the CG content but found: " << pre 
		<< std::endl;
      std::cerr << "Exiting." << std::endl;
      exit(-4);
    }
    if (!post2.isADouble())
    {
      std::cerr << "Error when parsing the bait file: Has it been edited manually?" << std::endl;
      std::cerr << "After each bait string BaitFilter expects two double numbers containing the baits' CG content and its maximum distance in the MSA.\n"
		<< "Expecting a double number for the distance value but found: " << post2 
		<< std::endl;
      std::cerr << "Exiting." << std::endl;
      exit(-4);
    }

    CG       = pre.ToDouble();
    max_dist = post2.ToDouble();
  }
  
  faststring& get_bait()
  {
    return bait;
  }

  unsigned get_tiling_index()
  {
    return tiling_index;
  }

  void print(std::ostream &os)
  {
    os << tiling_index  << " " << bait << " " << CG << " " << max_dist;
  }

  double get_max_distance()
  {
    return max_dist;
  }

  double get_CG_content()
  {
    return CG;
  }

}; // END CBait

// Forward declaration of friend functions of the CBaitLocus class. Avoids friend injection problems:
class CBaitLocus;
bool num_baits_lessThanCBaitLocus(CBaitLocus *a, CBaitLocus *b);
bool num_sequences_in_region_lessThanCBaitLocus(CBaitLocus *a, CBaitLocus *b);
bool gene_name__feature_num_lessThanCBaitLocus(CBaitLocus *a, CBaitLocus *b);

bool num_baits_greaterThanCBaitLocus(CBaitLocus *a, CBaitLocus *b);
bool num_sequences_in_region_greaterThanCBaitLocus(CBaitLocus *a, CBaitLocus *b);
bool gene_name__feature_num_greaterThanCBaitLocus(CBaitLocus *a, CBaitLocus *b);

bool gene_name__feature_num_lessThanOrEqualCBaitLocus(CBaitLocus *a, CBaitLocus *b);

// bool original_file_name__feature_num_start_lessThanCBaitLocus(CBaitLocus *a, CBaitLocus *b);

bool locus_start_lessThanCBaitLocus(CBaitLocus *a, CBaitLocus *b);


// Information about a bait region, i.e. a locus with a tiling design and its baits.
// Basically this is the information stored in one line of a BaitFisher output file.

class CBaitLocus
{
  faststring original_file_name;
  faststring gene_name;
  unsigned   feature_num;
  unsigned   num_features;
  unsigned   start;
  unsigned   num_sequences_in_region;
  unsigned   num_baits;
  unsigned   bait_length;
  unsigned   number_of_tiles;

  std::vector<CBait*> bait_vec;

 public:

  CBaitLocus(faststring &str)
  {
    std::vector<faststring> container;
    container.reserve(7);
    split(container, str, "\t|#");
    //split(container, str, "\t");

    if (container.size() != 8)
    {
      std::cerr << std::endl;
      std::cerr << "An error occurred while parsing the bait file. The line of input that causes the problem is:\n";
      std::cerr << str << std::endl;
      std::cerr << "The line does not contain 8 tab delimited fields as required." << std::endl;
      exit(-1);
    }

    container[0].removeSpacesFront();
    container[0].removeSpacesBack();
    container[1].removeSpacesFront();
    container[1].removeSpacesBack();
    container[2].removeSpacesFront();
    container[2].removeSpacesBack();
    container[3].removeSpacesFront();
    container[3].removeSpacesBack();
    container[4].removeSpacesFront();
    container[4].removeSpacesBack();
    container[5].removeSpacesFront();
    container[5].removeSpacesBack();
    container[6].removeSpacesFront();
    container[6].removeSpacesBack();
    container[7].removeSpacesFront();
    container[7].removeSpacesBack();

    original_file_name      = container[0];
    gene_name               = container[1];
    feature_num             = container[2].ToUnsigned();
    num_features            = container[3].ToUnsigned();
    start                   = container[4].ToUnsigned();
    num_sequences_in_region = container[5].ToUnsigned();
    num_baits               = container[6].ToUnsigned();

    std::list<faststring> b;
    split(b, container[7], ",");

    std::list<faststring>::iterator it, it_end;

    CBait *p_tmp;

    it     = b.begin();
    it_end = b.end();

    number_of_tiles = 0;
    // For all baits in this bait region:
    while(it != it_end)
    {
      p_tmp = new CBait(*it);
      bait_vec.push_back(p_tmp);
      if (p_tmp->get_tiling_index() > number_of_tiles)
	number_of_tiles = p_tmp->get_tiling_index();

/*       if (0) */
/*       { */
/* 	std::cerr << "Adding bait:" << std::endl; */
/* 	bait_vec.back()->print(std::cerr); */
/* 	std::cerr << std::endl; */
/*       } */

      ++it;
    }
    if (bait_vec.size() != 0)
    {
      bait_length = bait_vec[0]->get_bait().size();
    }
    else
    {
      bait_length = 0;
    }
  }

  ~CBaitLocus()
  {
    std::vector<CBait *>::iterator it, it_end;
    it     = bait_vec.begin();
    it_end = bait_vec.end();

    while (it != it_end)
    {
      delete *it;
      ++it;
    }
  }

  bool has_feature_information()
  {
    return (num_features == 0);
  }

  faststring &get_original_file_name()
  {
    return original_file_name;
  }

  const faststring &get_gene_name() const
  {
    return gene_name;
  }

  void get_vector_of_baits(unsigned tiling_index, std::vector<CBait*> &v)
  {
    std::vector<CBait*>::iterator it, it_end;
    it     = bait_vec.begin();
    it_end = bait_vec.end();

    v.clear();
    v.reserve(bait_vec.size());

    if (tiling_index == 0) // all
    {
      while (it != it_end)
      {
	v.push_back(*it);
	++it;
      }
    }
    else
    {
      while (it != it_end)
      {
	if ((**it).get_tiling_index() == tiling_index)
	{
	  v.push_back(*it);
	}
	++it;
      }
    }
  }

  unsigned get_feature_num() const
  {
    return feature_num;
  }

  unsigned get_start() const
  {
    return start;
  }
  
  unsigned get_number_of_tiles() const
  {
    return number_of_tiles;
  }

  unsigned get_bait_length() const
  {
    return bait_length;
  }

  faststring get_bait_region_name_string()
  {
    return original_file_name + "|" + gene_name + "|" + faststring(feature_num) + "|" + faststring(start);
  }

  // TODO: Change this to FILE * instead of using ostream.
  // Known formats are 'f', 's' for the 2 parameter version of this function.
  void print(std::ostream &os, char format)
  {
    std::vector<CBait *>::iterator i1, i2, i3;
    //    faststring name;
    unsigned count = 1;

    i1 = bait_vec.begin();
    i2 = bait_vec.end();

    if (format == 'f') // fasta
    {
      //      name = ">" + original_file_name + "|" + gene_name + "|" + faststring(feature_num) + "|" + faststring(start);

      while (i1 != i2)
      {
	os << ">" << get_bait_region_name_string()  << "|" << (**i1).get_tiling_index(); 
	os         << "|" << count    << std::endl;
	os << (**i1).get_bait()       << std::endl;
	++i1;
	++count;
      }
      
    } // END if (format == 'f') // fasta
    else if (format == 's') // standard - same as input
    {
      i3 = i2;
      --i3;
      os << original_file_name << "\t"
	 << gene_name << "\t"
	 << feature_num << "\t"
	 << num_features  << "\t"
	 << start  << "\t"
	 << num_sequences_in_region  << "\t"
	 << num_baits << "\t";

      // Works for 0, 1, or more elements in vector:
      if (i1 != i2) // Should always be the case, but be cautious
      {
	while (true)
	{
	  
	  (**i1).print(os);
	  if (i1 == i3)
	    break;
	  os << ",";
	  ++i1;
	  ++count;
	}
      }
      os << std::endl;
    }
  }

  // TODO: Change this to FILE * instead of using ostream.
  // Known formats are 'A' for the 3 parameter version of this function.
  void print(std::ostream &os, char format, const char *probeIDprefix)
  {
    std::vector<CBait *>::iterator i1, i2, i3;
    //    faststring name;

    i1 = bait_vec.begin();
    i2 = bait_vec.end();

    if (format == 'A') // Agilent-Germany format:
    {
      unsigned t_index, t_index_old = 0;
      unsigned count = 1;

      while (i1 != i2)
      {
	t_index = (**i1).get_tiling_index();
	
	if (t_index != t_index_old)
	{
	  t_index_old = t_index;
	  count = 1;
	}

	os << gene_name     << "_" << feature_num << '\t'
	   << probeIDprefix
	   << gene_name     << "_" 
	   << feature_num   << "_" 
	   << num_features  << "_"
	   << start         << "_"
	   << t_index       << "_"
	   << count                              << '\t' 
	   << (**i1).get_bait()
	   << "\t1"        << std::endl;
	++i1;
	++count;
      }
    }
  }



  void print_stats(std::ostream &os)
  {
    os << "Locus: " << gene_name << " " << feature_num << " " << start << " Num baits: " << bait_vec.size() << " bait-length :" << bait_length << std::endl;
  }

  unsigned get_num_baits()
  {
    return num_baits;
  }

  unsigned get_num_sequences()
  {
    return num_sequences_in_region;
  }

  // Can be used to compute mean values together with get_num_baits()
  double get_sum_max_distances()
  {
    int     i, N=num_baits;
    double  sum=0;

    for (i=0; i<N; ++i)
    {
      sum += bait_vec[i]->get_max_distance();
    }
    return sum;
  }

  double get_overall_max_dist()
  {
    int     i, N = num_baits;
    double  overall_max  = -1000;  // True values must be in the range 0..1
    double  dist;

    for (i=0; i<N; ++i)
    {
      dist = bait_vec[i]->get_max_distance();
      if (dist > overall_max)
	overall_max = dist;
    }
    return overall_max;
  }

  // Can be used to compute mean values together with get_num_baits()
  double get_sum_CG()
  {
    int     i, N=num_baits;
    double  sum=0;

    for (i=0; i<N; ++i)
    {
      sum += bait_vec[i]->get_CG_content();
    }
    return sum;
  }


  friend bool num_baits_lessThanCBaitLocus(CBaitLocus *a, CBaitLocus *b)
  {
    // First criterion:
    if (a->num_baits != b->num_baits)
      return a->num_baits < b->num_baits;

    // Second criterion: (opposite to first, therefore we use > and not <:
    if (a->num_sequences_in_region != b->num_sequences_in_region)
      return a->num_sequences_in_region > b->num_sequences_in_region;

    // Otherwise we sort by starting position. This makes the program output independent of
    // different versions of the sort algorithm. They are guaranteed to differ in different alignments files.
    return a->start < b->start;
  }

  // Not used:
  friend bool num_sequences_in_region_lessThanCBaitLocus(CBaitLocus *a, CBaitLocus *b)
  {
    // For loci based on an equal number of sequences, we prefer the one with less needed baits.
    // Note: This comparator sorts in the order greater is better, less is worse.
    // Better loci come later in a sorted list.

    // First criterion:
    if (a->num_sequences_in_region != b->num_sequences_in_region)
      return a->num_sequences_in_region < b->num_sequences_in_region;

    // Second criterion: (opposite to first, therefore we use > and not <:
    if (a->num_baits != b->num_baits)
      return a->num_baits > b->num_baits;
   
    // Otherwise we sort by starting position. This makes the program output independent of
    // different versions of the sort algorithm. They are guaranteed to differ in different alignments files.
    return a->start < b->start;
  }

  // First criterion:  gene_name
  // Second criterion: feature num
  // Third  criterion: locus start coordinate
  friend bool gene_name__feature_num_lessThanCBaitLocus(CBaitLocus *a, CBaitLocus *b)
  {
    // First criterion
    if (a->gene_name != b->gene_name)
      return a->gene_name < b->gene_name;

    // Second criterion
    if (a->feature_num != b->feature_num)
      return a->feature_num < b->feature_num;
    
    // Third criterion
    return a->start < b->start;
  }

/*   // not used: */
/*   friend bool num_baits_greaterThanCBaitLocus(CBaitLocus *a, CBaitLocus *b) */
/*   { */
/*    // First criterion: */
/*     if (a->num_baits != b->num_baits) */
/*       return a->num_baits > b->num_baits; */

/*     // Second criterion: (for the sequence coverage, more is better , therefore we use > and not <: */
/*     if (a->num_sequences_in_region != b->num_sequences_in_region) */
/*       return a->num_sequences_in_region < b->num_sequences_in_region; */

/*     // Otherwise we sort by starting position. This makes the program output independent of */
/*     // different versions of the sort algorithm. They are guaranteed to differ in different alignments files. */
/*     return a->start < b->start; */
/*   } */

  friend bool num_sequences_in_region_greaterThanCBaitLocus(CBaitLocus *a, CBaitLocus *b)
  {
    // First criterion: more sequence (coverage)
    if (a->num_sequences_in_region != b->num_sequences_in_region)
      return a->num_sequences_in_region > b->num_sequences_in_region;

    // Second criterion: less baits, opposite comparison
    if (a->num_baits != b->num_baits)
      return a->num_baits < b->num_baits;

   // Otherwise we sort by starting position. This makes the program output independent of
    // different versions of the sort algorithm. They are guaranteed to differ in different alignments files.
    return a->start < b->start;
  }

  friend bool gene_name__feature_num_greaterThanCBaitLocus(CBaitLocus *a, CBaitLocus *b)
  {
    if (a->gene_name != b->gene_name)
      return a->gene_name > b->gene_name;

    if (a->feature_num != b->feature_num)
      return a->feature_num > b->feature_num;
    
    return a->start > b->start;
  }


  friend bool locus_start_lessThanCBaitLocus(CBaitLocus *a, CBaitLocus *b)
  {
    // First criterion:
    if (a->gene_name != b->gene_name)
      return a->gene_name < b->gene_name;

    // Second criterion:
    return a->start < b->start;
  }

/*   friend bool original_file_name__feature_num_start_lessThanCBaitLocus(CBaitLocus *a, CBaitLocus *b) */
/*   { */
/*     // First criterion: */
/*     if (a->original_file_name != b->original_file_name) */
/*       return a->original_file_name < b->original_file_name; */

/*     // Second criterion: */
/*     if (a->feature_num != b->feature_num) */
/*       return a->feature_num < b->feature_num; */
    
/*     // Third criterion: */
/*     return a->start < b->start; */
/*   } */

}; // END CBaitLocus



// Contains usually multiple loci of bait regions. 
// Usually, loci come from multiple alignments, genes and features.

class CBaitLoci_collection
{
  std::vector<CBaitLocus*>                                       baitLoci_vec;
  std::map<Ctriple<faststring, unsigned, unsigned>, CBaitLocus*> baitLoci_map;
  bool                                                           delete_in_destructor;
  bool                                                           has_feature_information_bool;

  //  unsigned                                                       bait_length; // Will be set to 0 in constructor and will be adjusted to its true value in the add method.
  //                                                                              // The fact that we have one value for a collection of baits implies, that we assume that all baits in all loci have the same length.

  // Internal add 
  void add_locus(CBaitLocus *p)
  {
    baitLoci_vec.push_back(p);
    baitLoci_map.insert(std::pair<Ctriple<faststring, unsigned, unsigned>, CBaitLocus*>(Ctriple<faststring, unsigned, unsigned>(p->get_original_file_name(), p->get_feature_num(), p->get_start()), p) );

    if (p->has_feature_information())
      has_feature_information_bool = true;
    //    unsigned new_bait_length = p->get_bait_length();

/*     if (bait_length == 0) */
/*       bait_length = new_bait_length; */
/*     else */
/*     { */
/*       if (bait_length != new_bait_length) */
/*       { */
/* 	std::cerr << "ERROR: It is assumed that all baits in all bait loci have identical lenghts." << std::endl;  */
/* 	exit(-4); */
/*       } */
/*     } */
  }


 public:
 CBaitLoci_collection(std::ifstream &is):delete_in_destructor(true), has_feature_information_bool(false) //, bait_length(0)
  {
    faststring line;

    getline(is, line);
    while (!is.eof())
    {
      line.removeSpacesBack();
      line.removeSpacesFront();
      if (line[0] != '#' && !line.empty() )
	add_locus(new CBaitLocus(line) );
      getline(is, line);
    }
    if (!is_partially_ordered() )
    {
      std::cerr << "Note: Bait loci in input file are not ordered or genes appear twice." << std::endl;
      std::cerr << "Note: Lets try to order them." << std::endl;
      sort_by_gene_name__feature_num(baitLoci_vec.begin(), baitLoci_vec.end());
    }
  }


 CBaitLoci_collection(CBaitLoci_collection &source, char genes_or_features, char num_baits_or_sequences):delete_in_destructor(false), has_feature_information_bool(false) //, bait_length(0)
  {
/*     { */
/*       std::cout << "++++++++++++++" << std::endl; */
/*       std::cout << "Full set: DEBUG OUT" << std::endl; */
/*       source.print_all(std::cout, 's'); */
/*       std::cout << "++++++++++++++" << std::endl; */
/*     } */


    if (!source.is_partially_ordered() )
    {
      //      std::cout << "Source loci have to be sorted partially:" << std::endl;
      source.sort_within_genes(gene_name__feature_num_lessThanCBaitLocus);
      if (!source.is_partially_ordered() )
	if (global_verbosity >= 1)
	{
	  std::cerr << "WARNING: Sorting NOT successful." << std::endl;
	}
/*       else */
/* 	std::cout << "Sorting was successful." << std::endl; */
    }

/*     { */
/*       std::cout << "**************" << std::endl; */
/*       std::cout << "Full set: DEBUG OUT" << std::endl; */
/*       source.print_all(std::cout, 's'); */
/*       std::cout << "**************" << std::endl; */
/*     } */

    // Sort such the the best loci is first in each "group" of loci.
    if (genes_or_features == 'g')
    {
      //      std::cout << "Sorting within genes" << std::endl;
      if (num_baits_or_sequences == 'b')
	source.sort_within_genes(num_baits_lessThanCBaitLocus);
      else if (num_baits_or_sequences == 's')
	source.sort_within_genes(num_sequences_in_region_greaterThanCBaitLocus);
    }
    else if (genes_or_features == 'f')
    {
      //      std::cout << "Sorting within features" << std::endl;
      if (num_baits_or_sequences == 'b')
	source.sort_within_featues(num_baits_lessThanCBaitLocus);
      else if (num_baits_or_sequences == 's')
	source.sort_within_featues(num_sequences_in_region_greaterThanCBaitLocus);
    }

/*     { */
/*       std::cout << "##############" << std::endl; */
/*       std::cout << "Full set: DEBUG OUT" << std::endl; */
/*       source.print_all(std::cout, 's'); */
/*       std::cout << "##############" << std::endl; */
/*     } */

    // Add best to this:
    std::vector<CBaitLocus*>::iterator it, it_end, it_tmp;
    it     = source.baitLoci_vec.begin();
    it_end = source.baitLoci_vec.end();

    if (genes_or_features == 'g')
    {
      while (it != it_end)
      {
	add_locus(*it);
	//	baitLoci_vec.push_back(*it);
	it = source.find_end_this_gene(it);
      }
    }
    else if (genes_or_features == 'f')
    {
      while (it != it_end)
      {
	//	std::cout << "Next it:" << std::endl;
	//	(**it).print(std::cout, 's');
	//	std::cout << "==" << std::endl;
	add_locus(*it);
	//	baitLoci_vec.push_back(*it);
	it = source.find_end_this_feature(it);
      }
    }
    // We restore the original sorting of the source CBaitLoci_collection
    sort_within_genes(gene_name__feature_num_lessThanCBaitLocus);
  } // END CBaitLoci_collection(CBaitLoci_collection &source, char genes_or_features, char num_baits_or_sequences)


 CBaitLoci_collection(const CBaitLoci_collection &source, const CBaitRegionSelectorSets &lss, char mode):delete_in_destructor(false), has_feature_information_bool(false) // , bait_length(0)
 {
   unsigned i, N;
   N=source.baitLoci_vec.size();

   if (mode == 'b')      // Remove all loci from ALIGNMENT if a double hit occurs in this set
   {
     for (i=0; i<N; ++i)
     {
       CBaitLocus *p = source.baitLoci_vec[i];

       if (!lss.exists(p->get_original_file_name()) )
       {
	 add_locus(p);
	 //	 baitLoci_vec.push_back(p);
       }
     }
   }
   else if (mode == 'B') // Remove all loci from FEATURE if a double hit occurs in this set
   {
     for (i=0; i<N; ++i)
     {
       CBaitLocus *p = source.baitLoci_vec[i];

       if (!lss.exists(p->get_original_file_name(), p->get_feature_num()) )
       {
	 add_locus(p);
       }
     }
   }
   if (mode == 'x')      // Remove Locus if a double hit occurs in it
   {
     for (i=0; i<N; ++i)
     {
       CBaitLocus *p = source.baitLoci_vec[i];

       if (!lss.exists(p->get_original_file_name(), p->get_feature_num(), p->get_start()) )
       {
	 add_locus(p);
       }
     }
   }
   else if (mode == 'C') // In this mode we simply copy the loci to this collector.
   {
     for (i=0; i<N; ++i)
     {
       CBaitLocus *p = source.baitLoci_vec[i];
       add_locus(p);
     }
   }
   else
   {
     std::cerr << "Error: Unknown mode in constructor: CBaitLoci_collection(const CBaitLoci_collection &source, const CBaitRegionSelectorSets &lss, char mode): " << std::endl;
     std::cerr << "Bad mode character: " << mode << std::endl;
     exit(-1);
   }
 }


 CBaitLoci_collection(const CBaitLoci_collection &source, CBlast_parser &bp, double minimum_coverage):delete_in_destructor(false), has_feature_information_bool(false) //, bait_length(source.bait_length)
  {
    unsigned    tile_index, number_of_tiles;
    faststring  recognition_string;
    double      best_coverage_this_tiling_stack;
    bool        bait_region_has_tiling_stack_with_insufficient_coverage;
    int         max_hit_length, bait_length_this_bait_region;
    unsigned    count, N;

    std::vector<CBaitLocus*>::const_iterator it, it_end;

    it     = source.baitLoci_vec.begin();
    it_end = source.baitLoci_vec.end();

    N      = source.baitLoci_vec.size();
    count  = 0;

    // for each bait region
    while (it != it_end)
    {
      ++count;
      number_of_tiles                 = (**it).get_number_of_tiles();
      bait_length_this_bait_region    = (**it).get_bait_length();;
/*             std::cout << "Number of tiles for: " << (**it).get_bait_region_name_string() */
/* 		<< " " << number_of_tiles << std::endl; */

      if (bait_length_this_bait_region == 0)
      {
	// We have a problem. Something seems to have gone wrong. This should not happen.
	// We catch this potential error, since it leads to division by 0 and a crash would be expected.
	std::cerr << "The bait length has been determined to be 0 for the bait region: " << std::endl;  
	(**it).print(std::cerr, 's');
	std::cerr << "This bug should be reported. It should not occur. It might be caused by malformatted input files,"
	             " but the error should be caught earlier than here." << std::endl;
	exit(-5);
      }

      if (global_verbosity >= 3)
      {
	std::cout << "Handling region: " << count << " outof " << N << std::endl;
      }

      // Within each bait region determine the maximum hit coverage of all baits
      // For each tiling stack of baits:

      // Each tiling stack has to be checked individually.
      // A single tiling stack with insufficient query coverage should result in the exclusion of this bait region.
      bait_region_has_tiling_stack_with_insufficient_coverage = false;
      for (tile_index=1; tile_index <= number_of_tiles; ++tile_index)
      {
	// Do something with (**it):
	// Determine string to identify blast hits of baits of this bait region and tiling_index against the genome. 
	recognition_string = (**it).get_bait_region_name_string() + "|" + tile_index + "|";  

	//	std::cout << "T1: " << time(NULL) << std::endl;
	max_hit_length = bp.get_max_hit_query_span__matching_beginning2(recognition_string, global_verbosity);
	//	std::cout << "T2: " << time(NULL) << std::endl;

	best_coverage_this_tiling_stack = (double) max_hit_length/bait_length_this_bait_region;

	if (global_verbosity >= 50)
	{
	  std::cout << "Tile: " << tile_index << " " << recognition_string << " " << max_hit_length << "/" << bait_length_this_bait_region << "=" 
                    << best_coverage_this_tiling_stack << std::endl;
	}

	if (best_coverage_this_tiling_stack < 0)
	{
	  if (global_verbosity >= 50)
	  {
	    std::cout << "No hit for recognition string: " << recognition_string << " --> "
		      << 0.00 << std::endl;
	  }
	}
	else
	{
	  if (global_verbosity >= 50)
	  {
	    std::cout << "Determined best coverage of this tiling design column: " << recognition_string << " --> "
		      << best_coverage_this_tiling_stack << std::endl;
	  }
	}

	if (best_coverage_this_tiling_stack < minimum_coverage)
	  bait_region_has_tiling_stack_with_insufficient_coverage = true;
      }

      if (!bait_region_has_tiling_stack_with_insufficient_coverage)
      {
	add_locus(*it);
      }
      ++it;
    }
  }

  ~CBaitLoci_collection()
  {
    if (delete_in_destructor)
    {
      std::vector<CBaitLocus*>::iterator it, it_end;
      it     = baitLoci_vec.begin();
      it_end = baitLoci_vec.end();

      while (it != it_end)
      {
	delete *it;
	++it;
      }
    }
  }

  bool has_feature_information() const
  {
    return has_feature_information_bool;
  }

  void get_map_of_baits_to_locus_info(faststring original_file_name_match, unsigned tiling_index, std::map<faststring, CBaitLocus *> &bait_map)
  {
    //    sort_by_original_file_name__feature_num_start();

    std::vector<CBaitLocus*>::iterator it_Locus, it_Locus_end;
    it_Locus     = baitLoci_vec.begin();
    it_Locus_end = baitLoci_vec.end();

    std::vector<CBait *> tmp_bait_vec;

    unsigned i, N;

    std::map<faststring, CBaitLocus *>::iterator find_it;

    while (it_Locus != it_Locus_end)
    {
      if ( (**it_Locus).get_original_file_name().find(original_file_name_match) != faststring::npos)
      {
	(**it_Locus).get_vector_of_baits(tiling_index, tmp_bait_vec);

	N=tmp_bait_vec.size();
	for (i=0; i<N; ++i)
	{
	  faststring &thebait = tmp_bait_vec[i]->get_bait();
	  find_it = bait_map.find(thebait);
	  if (find_it == bait_map.end())  // Insert, if not present yet.
	    bait_map[thebait] = *it_Locus;
	}
      }
      ++it_Locus;
    }
  }

/*   void clean_NULL_elements_form_baitLoci_vec() */
/*   { */
/*     std::vector<CBaitLocus*>::iterator it_end, it1, it2; */
/*     unsigned count = 0; */
    
/*     it1 = it2 = baitLoci_vec.begin(); */
/*     it_end    = baitLoci_vec.end(); */

/*     // Advance it2 until we have the first NULL element: */
/*     while (*it2 != NULL && it2 != it_end) */
/*     { */
/*       ++it1; */
/*       ++it2; */
/*       ++count; */
/*     } */

/*     // if it2 is not at the end, it will point to a NULL element */
/*     while (it2 != it_end) */
/*     { */
/*       // Find next non-NULL element: */
/*       while (*it2 == NULL && it2 != it_end) */
/*       { */
/* 	++it2; */
/*       } */
/*       if (it2 == it_end) */
/* 	break; */
/*       //Copy: */
/*       *it1 = *it2; */
/*       ++count; */
      
/*       ++it1; */
/*       ++it2; */
/*     } */

/*     // Resize vector: */
/*     baitLoci_vec.resize(count, 0); */

/*   } */


/*   void sort_by_num_baits(std::vector<CBaitLocus*>::iterator it, std::vector<CBaitLocus*>::iterator it_end) */
/*   { */
/*     MYSORT (it, it_end, num_baits_lessThanCBaitLocus); */
/*   } */

/*   void sort_by_num_sequences(std::vector<CBaitLocus*>::iterator it, std::vector<CBaitLocus*>::iterator it_end) */
/*   { */
/*     MYSORT (it, it_end, num_sequences_in_region_greaterThanCBaitLocus); */
/*   } */

  void sort_by_gene_name__feature_num(std::vector<CBaitLocus*>::iterator it, std::vector<CBaitLocus*>::iterator it_end)
  {
    MYSORT (it, it_end, gene_name__feature_num_lessThanCBaitLocus);
  }

  unsigned get_number_of_loci() const
  {
    return baitLoci_vec.size();
  }


  void print_stats(std::ostream &os)
  {
    unsigned numBaits = 0;
    
    os << "Number of loci: " << baitLoci_vec.size() << std::endl;

    std::vector<CBaitLocus*>::iterator it, it_end;
    it     = baitLoci_vec.begin();
    it_end = baitLoci_vec.end();

    while (it != it_end)
    {
      (**it).print_stats(os);
      numBaits += (**it).get_num_baits();
      ++it;
    }
    os << "Total number of baits: " << numBaits << std::endl;
    //    os << "Bait length:           " << bait_length  << std::endl;
  }


  //////////////////
  // We now impelmented this in a constructor to be consistent with other filtering steps.
  //////////////////
/*   void filter_hit_coverage(double minimum_coverage, CBlast_parser &bp) */
/*   { */
/*     unsigned    tile_index, number_of_tiles; */
/*     faststring  recognition_string; */
/*     double      best_coverage_this_tiling_stack; */
/*     bool        bait_region_has_tiling_stack_with_insufficient_coverage; */

/*     std::vector<CBaitLocus*>::iterator it, it_end; */

/*     it     = baitLoci_vec.begin(); */
/*     it_end = baitLoci_vec.end(); */

/*     // for each bait region */
/*     while (it != it_end) */
/*     { */
/*       number_of_tiles = (**it).get_number_of_tiles(); */
/* /\*             std::cout << "Number of tiles for: " << (**it).get_bait_region_name_string() *\/ */
/* /\* 		<< " " << number_of_tiles << std::endl; *\/ */

/*       // Within each bait region determine the maximum hit coverage of all baits */
/*       // For each tiling stack of baits: */

/*       // Each tiling stack has to be checked individually. */
/*       // A single tiling stack with insufficient query coverage should result in the exclusion of this bait region. */
/*       bait_region_has_tiling_stack_with_insufficient_coverage = false; */
/*       for (tile_index=1; tile_index <= number_of_tiles; ++tile_index) */
/*       { */
/* 	// Do something with (**it): */
/* 	// Determine string to identify blast hits of baits of this bait region and tiling_index against the genome.  */
/* 	recognition_string = (**it).get_bait_region_name_string() + "|" + tile_index + "|";   */
	
/* 	best_coverage_this_tiling_stack = (double) bp.get_max_hit_query_span__matching_beginning1(recognition_string)/bait_length; */

/* 	if (best_coverage_this_tiling_stack < 0) */
/* 	{ */
/* 	  std::cout << "No hit for recognition string: " << recognition_string << " --> " */
/* 		    << 0.00 << std::endl; */
/* 	} */
/* 	else */
/* 	{ */
/* 	  std::cout << "Determined best coverage of this tiling stack: " << recognition_string << " --> " */
/* 		    << best_coverage_this_tiling_stack << std::endl; */
/* 	} */

/* 	if (best_coverage_this_tiling_stack < minimum_coverage) */
/* 	  bait_region_has_tiling_stack_with_insufficient_coverage = true; */
/*       } */

/*       if (bait_region_has_tiling_stack_with_insufficient_coverage) */
/*       { */
/* 	if (delete_in_destructor) */
/* 	  delete *it; */
/* 	*it = NULL; */
/*       } */
/*     } */

/*     clean_NULL_elements_form_baitLoci_vec(); */
/*   } */


  void print_all(std::ostream &os, char format)
  {
    std::vector<CBaitLocus*>::iterator it, it_end;
    it     = baitLoci_vec.begin();
    it_end = baitLoci_vec.end();

    // TODO: In case we have no alignment cutting we should use an alternative heading in the output file.
    //       This is not urgent, just more elegant. It requires some work to get the information to this point.
    if (format == 's')
    {
      //  if (alignment_cutting)
      os << "# Original-file-name\tGene-name\tFeature-number\tNumber-of-features-of-specified-type-for-this-gene-in-gff-file\tStart-coordinate-of-bait-region-in-alignment\tNumber-of-sequences-in-region-the-baits-are-based-on\tNumber-of-baits-constructed-for-this-bait-region\tList of baits - for each bait the tiling design column is given, then the bait string, its CG content and its maximum distance to the sequences in the alignment." << std::endl;
      //  else
      //    os << "# Corresponding sequence name\tGene-name\tn.a.\tn.a.\tStart-coordinate-of-bait-region-in-alignment\t Number-of-sequences-in-region-the-baits-are-based-on\tNumber-of-baits-constructed-for-this-bait-region\tList of baits - for each bait the tiling design column is given, then the bait string, its CG content and its maximum distance to the sequences in the alignment." << std::endl;
    }

    if ( !(format == 's' || format == 'f' ) )
    {
      std::cerr << "ERROR: Unknown internal format " << format << " found in call to CBaitLoci_collection::print_all(2 parameters)" << std::endl;
      exit(-24);
    }

    while (it != it_end)
    {
      (**it).print(os, format);
      ++it;
    }
  }


  void print_all(std::ostream &os, char format, const char *probeIDprefix)
  {
    std::vector<CBaitLocus*>::iterator it, it_end;
    it     = baitLoci_vec.begin();
    it_end = baitLoci_vec.end();

    if (format == 'A')
    {
      os << "TargetID\tProbeID\tSequence\tReplication" << std::endl;
    }
    else
    {
      std::cerr << "ERROR: Unknown internal format " << format << " found in call to CBaitLoci_collection::print_all(3 parameters)" << std::endl;
      exit(-25);
    }

    while (it != it_end)
    {
      (**it).print(os, format, probeIDprefix);
      ++it;
    }
  }


  void fill_locus_selector(CBaitRegionSelectorSets &ls) const
  {
    std::vector<CBaitLocus*>::const_iterator it, it_end;
    it     = baitLoci_vec.begin();
    it_end = baitLoci_vec.end();

    while (it != it_end)
    {
      ls.add( (**it).get_gene_name(),
	      (**it).get_feature_num(),
	      (**it).get_start() );
      ++it;
    }
  }


  void print_with_start_stepwidth(std::ostream &os, char format, unsigned start, unsigned step)
  {
    // TODO: In case we have no alignment cutting we should use an alternative heading in the output file.
    //       This is not urgent, just more elegant. It requires some work to get the information to this point.
    if (format == 's')
    {
      //  if (alignment_cutting)
      os << "# Original-file-name\tGene-name\tFeature-number\tNumber-of-features-of-specified-type-for-this-gene-in-gff-file\tStart-coordinate-of-bait-region-in-alignment\tNumber-of-sequences-in-region-the-baits-are-based-on\tNumber-of-baits-constructed-for-this-bait-region\tList of baits - for each bait the tiling design column is given, then the bait string, its CG content and its maximum distance to the sequences in the alignment." << std::endl;
      //  else
      //    os << "# Corresponding sequence name\tGene-name\tn.a.\tn.a.\tStart-coordinate-of-bait-region-in-alignment\t Number-of-sequences-in-region-the-baits-are-based-on\tNumber-of-baits-constructed-for-this-bait-region\tList of baits - for each bait the tiling design column is given, then the bait string, its CG content and its maximum distance to the sequences in the alignment." << std::endl;
    }

    unsigned i,N = baitLoci_vec.size();

    i = start-1;  // start is 1 based, i is 0 based. Therefore we have to subtract 1.
    while (i < N)
    {
      baitLoci_vec[i]->print(os, format);
      i += step;
    }
  }

  void print_with_start_stepwidth_multi_gene_feature_aware(std::ostream &os, char format, unsigned start_count, unsigned offset_count,
							   std::vector<CBaitLocus*>::iterator it_start_this_alignment)
  {
    if (format == 's')
    {
      //  if (alignment_cutting)
      os << "# Original-file-name\tGene-name\tFeature-number\tNumber-of-features-of-specified-type-for-this-gene-in-gff-file\tStart-coordinate-of-bait-region-in-alignment\tNumber-of-sequences-in-region-the-baits-are-based-on\tNumber-of-baits-constructed-for-this-bait-region\tList of baits - for each bait the tiling design column is given, then the bait string, its CG content and its maximum distance to the sequences in the alignment." << std::endl;
      //  else
      //    os << "# Corresponding sequence name\tGene-name\tn.a.\tn.a.\tStart-coordinate-of-bait-region-in-alignment\t Number-of-sequences-in-region-the-baits-are-based-on\tNumber-of-baits-constructed-for-this-bait-region\tList of baits - for each bait the tiling design column is given, then the bait string, its CG content and its maximum distance to the sequences in the alignment." << std::endl;
    }

    std::vector<CBaitLocus*>::iterator it_tmp, it;

    it = it_start_this_alignment;

    if ( (**it).has_feature_information() )
      it_tmp = find_end_this_feature(it);
    else
      it_tmp = find_end_this_gene(it);

    // First we determine the starting point for the iterator it "at start_count"
    unsigned i=0, startdiff, laststart, start;

    laststart = (**it).get_start();
    while (i < start_count) // We won't walk past the end of this feature  or alignment
    {
      ++it;
      if (it == it_tmp)
	break;
      // If we had to skip possible starting points, we try to correct for this.
      start = (**it).get_start();
      startdiff = start - laststart; // Difference of indices, should be at least 1.
      i += startdiff; 
      laststart = start;
    }

    if (it != it_tmp) // we should never have it == it_tmp, but if we have, we will crash, so we better check.
    {
      // Loop over all loci in steps of offset_count
      while (true) // We won't walk past the end of this feature or alignment. We break inside the loop if it == it_tmp.
      {
	// This locus will be printed.
	(*it)->print(os, format);

	i = 0; // Count the number of loci we skip in next iteration.	
	// Move to next locus we want to print:
	// We move by one locus position. (The first move.)  
	// We can handle the first move outside the loop below since offset_count must be > 0.
	++it;
	if (it == it_tmp)
	  break;

	// If we had to skip possible starting points, we try to correct for this.
	start = (**it).get_start();
	startdiff = start - laststart;
	i += startdiff; // Diff is 1 or larger.
	laststart = start;
	  
	// Skip offset_count loci.
	while (it < it_tmp && i < offset_count)
	{
	  // Next iteration.
	  ++it;
	  if (it == it_tmp)
	    break;
	  start = (**it).get_start();
	  startdiff = start - laststart;
	  i += startdiff;
	  laststart = start;
	}
	  
	// If it == it_tmp, we have an iterator not pointing into this alignment/feature any more.
	// So we have to break immediately.
	if (it == it_tmp)
	  break;
	  
	// In the ideal case i == offset_count. Then we are at the next locus we wanted to count.
	// If i < offset_count we have not reached the next good locus in this alignment/gene/feature
	//   before we moved past the end. In this case we have it == it_tmp and we leave the
	//   loop with the next while check.
	// If i > offset_count, then we had to skip more loci than we wanted to skip, since not all
	// loci are valid starting points. In this case we add a penalty.
       
      } // END while true
    } // END if (it != it_tmp)
  } // END print_with_start_stepwidth_multi_gene_feature_aware



  std::vector<CBaitLocus*>::iterator find_end_this_feature(std::vector<CBaitLocus*>::iterator it)
  {
    unsigned   the_feature_num = (**it).get_feature_num();
    faststring the_gene_name    = (**it).get_gene_name();

    while (it != baitLoci_vec.end() )
    {
      if (the_feature_num != (**it).get_feature_num() || the_gene_name != (**it).get_gene_name())
      {
	break;
      }
      ++it;
    }
    return it;
  }

  std::vector<CBaitLocus*>::iterator find_end_this_gene(std::vector<CBaitLocus*>::iterator it)
  {
    faststring the_gene_name    = (**it).get_gene_name();

    while (it != baitLoci_vec.end() )
    {
      if (the_gene_name != (**it).get_gene_name())
      {
	break;
      }
      ++it;
    }
    return it;
  }

  void sort_within_featues(bool (*f)(CBaitLocus*,CBaitLocus*))
  {
    std::vector<CBaitLocus*>::iterator it, it_end, it_tmp;
    it     = baitLoci_vec.begin();
    it_end = baitLoci_vec.end();

    while (it != it_end)
    {
      // Find end of this gene:
      it_tmp = find_end_this_feature(it);
      //      std::cout << "Sort range: " << distance(baitLoci_vec.begin(), it) << " " << distance(baitLoci_vec.begin(), it_tmp) << std::endl;
      MYSORT(it,it_tmp, f);
      it = it_tmp;
    }
  }

  void sort_within_genes(bool (*f)(CBaitLocus*,CBaitLocus*))
  {
    std::vector<CBaitLocus*>::iterator it, it_end, it_tmp;
    it     = baitLoci_vec.begin();
    it_end = baitLoci_vec.end();

    while (it != it_end)
    {
      // Find end of this gene:
      it_tmp = find_end_this_gene(it);
      MYSORT(it,it_tmp, f);
      it = it_tmp;
    }
  }

/*   void sort_by_original_file_name__feature_num_start() */
/*   { */
/*     MYSORT(baitLoci_vec.begin(), baitLoci_vec.end(), original_file_name__feature_num_start_lessThanCBaitLocus); */
/*   } */


  bool is_ordered_within_genes()
  {
    std::vector<CBaitLocus*>::iterator it, it_end, it_tmp;
    it     = baitLoci_vec.begin();
    it_end = baitLoci_vec.end();

    if (it == it_end)
      return true;

    it_tmp = it;
    ++it_tmp;

    while (it_tmp != it_end)
    {
      if (!gene_name__feature_num_lessThanCBaitLocus(*it, *it_tmp) )
	return false;
      it = it_tmp;
      ++it_tmp;
    }
    return true;
  }


  // Determines whether feature numbers reappear in successive loci
  // if a different feature number was found in between.
  // This ordering is assumed when filtering for the best loci in a feature.
  bool is_partially_ordered()
  {
    std::set<faststring> set_genes_features;

    std::vector<CBaitLocus*>::iterator it, it_end;
    it     = baitLoci_vec.begin();
    it_end = baitLoci_vec.end();

    unsigned   the_feature_num;
    faststring the_gene_name;

    if (it == it_end)
      return true;

    the_feature_num  = (**it).get_feature_num();
    the_gene_name    = (**it).get_gene_name();

    faststring gene_feature_name;
    gene_feature_name = the_gene_name + "_" + the_feature_num;
    set_genes_features.insert(gene_feature_name);

    while (it != it_end)
    {
      if (the_feature_num != (**it).get_feature_num() || the_gene_name != (**it).get_gene_name() )
      {
	// new gene or exon:
	the_feature_num   = (**it).get_feature_num();
	the_gene_name     = (**it).get_gene_name();
	gene_feature_name = the_gene_name + "_" + the_feature_num;

	if ( set_genes_features.find(gene_feature_name) != set_genes_features.end() )
	{
	  return false;  // We have seen this gene/exon combination before. So we return false;
	}
	set_genes_features.insert(gene_feature_name);
      }
      ++it;
    }
    return true;
  }

  void get_seqs_baits_count(unsigned &NumSeqs, unsigned &NumBaits) const
  {
    std::vector<CBaitLocus*>::const_iterator it, it_end;
    it     = baitLoci_vec.begin();
    it_end = baitLoci_vec.end();
    
    unsigned local_NumSeqs  = 0;
    unsigned local_NumBaits = 0;

    while (it != it_end)
    {
      local_NumSeqs  += (**it).get_num_sequences();
      local_NumBaits += (**it).get_num_baits();
      ++it;
    }

    NumSeqs  = local_NumSeqs;
    NumBaits = local_NumBaits; 
  }

  // Used to evaluate a starting index in thinning mode.
  // Thinning can be done for multiple alignment files even though we originally had one file in mind.
  // At the moment we do not start at position 1 when coming to the next alignment.

  void count_seqs_baits_for_start_and_offset(unsigned start_count, unsigned offset_count,
					     unsigned &sum_seq,    unsigned &sum_baits)
  {
    unsigned i,N;
    N = baitLoci_vec.size();

    sum_seq = sum_baits = 0;

    for (i=start_count; i<N; i += offset_count)
    {
      sum_baits += baitLoci_vec[i]->get_num_baits();
      sum_seq   += baitLoci_vec[i]->get_num_sequences();
    }
  }

  // Used to evaluate a starting index in thinning mode.
  // Thinning can now be done for multiple alignment files even though we it was originally designed to work only for single files.
  // This function is called for the loci of each alignment individually.
  // This functions obtains the first locus it should consider and walks through all loci until the loci belong to the next alignment.
  // It passes back the start locus for the next alignment.
  //// At the moment we do not start at position 1 when coming to the next alignment.

  void count_seqs_baits_for_start_and_offset_multi_gene_feature_aware(unsigned alignment_counter,
								      std::vector<CBaitLocus*>::iterator &it_start_this_alignment,
								      std::vector<CBaitLocus*>::iterator &it_start_next_alignment,
								      bool     &finished,
								      unsigned start_count, unsigned offset_count,
								      unsigned &sum_seq,    unsigned &sum_baits,
								      unsigned &penalty_diff)
  {
    unsigned i;
    unsigned lastLocusStart, thisLocusStart, locusStartDiff;
    int penalty_diff_local = 0;

    sum_seq = sum_baits = 0;

    if (global_verbosity >= 50)
    {
      std::cerr << "Working on alignment number: " << alignment_counter << " start " << start_count << std::endl;
    }

    std::vector<CBaitLocus*>::iterator it, it_end_al;

    if (alignment_counter == 1)  // Since the calling function does not have access to the baitLoci_vec, the start is initialized in this function, if alignment_counter == 1.
    {
      it = it_start_this_alignment = baitLoci_vec.begin();
    }
    else
    {
      it = it_start_this_alignment;
    }

    if ( (**it).has_feature_information() )
      it_end_al = find_end_this_feature(it);
    else
      it_end_al = find_end_this_gene(it);

    
    // First we determine the start for iterator at start_count
    i=0;
    lastLocusStart = (**it).get_start();  // This information is used to keep track of already deleted starting positions of loci.
                                          // This variable is initialised with the locus staring coordinate of the first bait region starting position.

    while (i < start_count) // We won't walk past the end of this feature  or alignment
    {
      ++it;
      if (it == it_end_al)
	break;
      // If we had to skip possible starting points, we try to correct for this.
      thisLocusStart = (**it).get_start();
      locusStartDiff = thisLocusStart - lastLocusStart; // Difference of indices, should be at least 1. Is 0 for first bait region.
      i += locusStartDiff; 
      lastLocusStart = thisLocusStart;
    }

    //      std::cout << "Found start (index:start_count, index-found:i): " << start_count << " " << i << std::endl;

    // Differences are not penalised if they occur while searching for the starting position.
    // In the ideal case, i == start_count. i < start_count should not be possible.
    // However, if we moved passed the ideal start_count, we penalise this.
    if (i > start_count)
    {
      penalty_diff_local = i-start_count;
    }

    // If we moved past the end of the alignment, we found no valid starting point in this alignment.
    // This will be penalised. This penalty might superseed a previous penalty.
    if (it == it_end_al)
    {
      // The amount of the penalty could be a matter of debate. A small/moderate penalty is the
      // start_count itself. It penalises larger start counts more.
      penalty_diff_local = start_count;
    }
    else
    {
      // Loop over all loci in steps of offset_count
      while (true) // We won't walk past the end of this feature or alignment. We break inside the loop if it == it_end_al.
      {
	// This locus is scored.
	//	  std::cout << "Score locus (seq-coord:start,counter:i): " <<  (**it).get_start() << " " << i << std::endl;
	sum_baits += (**it).get_num_baits();
	sum_seq   += (**it).get_num_sequences();

	i = 0; // Count the number of loci we skip in next iteration.
	
	// Move to next loci we want to add:
	// We move by one locus position. (The first move.)  
	// We can handle the first move outside the loop below since offset_count must be > 0.
	++it;
	if (it == it_end_al)
	  break;

	// If we had to skip possible starting points, we try to correct for this.
	thisLocusStart = (**it).get_start();
	locusStartDiff = thisLocusStart - lastLocusStart;
	i += locusStartDiff; // Diff is 1 or larger.
	lastLocusStart = thisLocusStart;
	  
	// Skip offset_count loci.
	while (it < it_end_al && i < offset_count)
	{
	  // Next iteration.
	  ++it;
	  if (it == it_end_al)
	    break;
	  thisLocusStart = (**it).get_start();
	  locusStartDiff = thisLocusStart - lastLocusStart;
	  i += locusStartDiff;
	  lastLocusStart = thisLocusStart;
	}
	  
	// If it == it_end_al, we have an iterator not pointing this alignment/feature any more.
	// So we have break immediately.
	if (it == it_end_al)
	  break;
	  
	// In the ideal case i == offset_count. Then we are at the next locus we wanted to count.
	// If i < offset_count we have not reached the next good locus in this alignment/gene/feature
	//   before we moved past the end. In this case we have it == it_end_al and we leave the
	//   loop with the next while check.
	// If i > offset_count, then we had to skip more loci than we wanted to skip, since not all
	// loci are valid starting points. In this case we add a penalty.
	  
	if (i > offset_count)
	{
	  penalty_diff_local += (i-offset_count);
	}
      } // END while true
    } // END ELSE if (it == it_end_al)

    penalty_diff = penalty_diff_local;
    if (it == baitLoci_vec.end() )
      finished = true;
    else
      finished = false;

    it_start_next_alignment = it_end_al;

  } //END FUNCTION count_seqs_baits_for_start_and_offset_multi_gene_feature_aware


  void get_original_file_name_gene_name(unsigned alignment_counter,
			      std::vector<CBaitLocus*>::iterator &it_start_this_alignment,
			      faststring &P_original_file_name,
			      faststring &P_gene_name
			      )
  {
    if (alignment_counter == 1)
    {
      it_start_this_alignment = baitLoci_vec.begin();
    }

    P_original_file_name  = (**it_start_this_alignment).get_original_file_name();
    P_gene_name           = (**it_start_this_alignment).get_gene_name();
  }




  double get_max_dist_mean() const
  {
    double   sum=0;
    double   num=0;
    int     i, N = baitLoci_vec.size();
    
    for (i=0; i<N; ++i)
    {
      sum += baitLoci_vec[i]->get_sum_max_distances();
      num += baitLoci_vec[i]->get_num_baits();
    }

    //    std::cerr << "sum max distances: " << sum << std::endl;
    //    std::cerr << "num baits:         " << num << std::endl;

    return sum/num;
  }
  
  double get_overall_max_dist() const
  {
    double overall_max_dist = -1000;  // True values must be in the range 0..1.
    double om_dist;
    int    i, N             = baitLoci_vec.size();
    
    for (i=0; i<N; ++i)
    {
      om_dist = baitLoci_vec[i]->get_overall_max_dist();
      if (om_dist > overall_max_dist)
      {
	overall_max_dist = om_dist;
      }
    }
    return overall_max_dist;
  }


  double get_CG_mean() const
  {
    double   sum=0;
    double   num=0;
    int     i, N = baitLoci_vec.size();
    
    for (i=0; i<N; ++i)
    {
      sum += baitLoci_vec[i]->get_sum_CG();
      num += baitLoci_vec[i]->get_num_baits();
    }
    return sum/num;
  }

}; // END CBaitLoci_collection