File: options.cc

package info (click to toggle)
murasaki 1.68.6-6
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 1,928 kB
  • ctags: 3,100
  • sloc: cpp: 16,010; perl: 8,365; makefile: 186
file content (983 lines) | stat: -rw-r--r-- 35,024 bytes parent folder | download | duplicates (4)
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
/*
Copyright (C) 2006-2008 Keio University
(Kris Popendorf) <comp@bio.keio.ac.jp> (2006)

This file is part of Murasaki.

Murasaki 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.

Murasaki 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 Murasaki.  If not, see <http://www.gnu.org/licenses/>.
*/

/////////////////////
// murasaki config options manager
////////////////////

#include "genopts.h"
#include "options.h"
#include "murasaki.h"
#include "murasaki_mpi.h"
#include "timing.h"
#include "dinkymath.h"
#include "sequence.h"

#include <boost/filesystem/operations.hpp> //graceful handling of directories
#include <boost/lexical_cast.hpp>
#include <functional>
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <string.h>
#include <getopt.h>
#include <map>

#include <err.h>
#include <stdarg.h>


#ifdef MURASAKI_MPI
#include "mpi.h"
#endif

using namespace std;
using namespace boost::filesystem;

//stupid static inits
bool Options::staticInited=false;
map<int,string> Options::optionSwitch;
map<string,int> Options::optionSwitchToInt;

void optErr(const char *infmt, ...){
  va_list argp;
  char buff[2048];
  char fmt[1024];
  va_start(argp,infmt);

  sprintf(fmt,"Options: %s",infmt);
  vsprintf(buff,fmt,argp);
  throw MurasakiException(string(buff));
}

void Options::staticInit(){
  if(staticInited)
    return;

  //Actually this should probably be all wrapped in a singleton, but this avoids the mac os static init problem for now.
  map<int,string> ma;
  map<string,int> mb;

  for(static struct option *oi=long_options;oi->name!=0;++oi){
    ma[oi->val]=oi->name;
    mb[oi->name]=oi->val;
  }

  optionSwitch = ma;
  optionSwitchToInt = mb;

  staticInited=true;
}

int Options::getOptSource(string name){
  assert(optionSwitchToInt.count(name));
  return optionSource[optionSwitchToInt[name]];
}

Options::Options():
  verbose(0),quick_hash(3),randomHashInputs(0),
  hitfilter(0),histogram(0),
  user_seed(false),rand_seed(time(NULL)),repeatMask(false),
  skip1to1(false),skipFwd(false),skipRev(false),
  hashOnly(false),hashCache(false),bitscore(true),
  probingMethod(1),
  hashPref(EcoHash_t),alignment_name("test"),output_dir("output"),
  seedfilter(0),hashfilter(0),mergeFilter(100),scoreFilter(0),
  joinNeighbors(false),joinSpec(-1),joinDist(-1),
  hashSkip(1),
  auto_hashbits(true),
  dumpRegions(false),leaveRecords(false),
  targetMemory(sysinfo.totalMemory*90/100),userSetMemory(false),
  retainMembers(true),useHumanTime(true),
  repeatMap(true),anchorProgressCheck(0),
  tfidf(true),reverseOtf(true),inplaceDf(false),
  rifts(0),set_islands(0),
  fuzzyExtend(true),
  gappedAnchors(false), //sounds attractive, but ungapped are actually much more useful
  fuzzyExtendLossLimit(0), //blastz uses 10*(A-to-A match score) as a default, we probably should too
  scoreByMinimumPair(true),
  measureHashCollisions(false),
  ecolistFrugal(false),
  hasherFairEntropy(true),hasherCorrelationAdjust(true),hasherTargetGACycles(1000),hasherEntropyAgro(1),
  useSeqBinary(true),
  //mpi related
  mpi_hashers(0),mpi_noCake(false),mpi_fileDistro(true),
  mpi_anchorInSpareTime(true),mpi_maxBuffers(0),mpi_bigFirst(false),
  mpi_hostbalance(true),mpi_memoryBalance(true),mpi_distMerge(true),mpi_distCollect(true),
  mpi_outputRedirect(true),
  mpi_keepstdoe(false),
  use_shm_mmap(false),mmap_writePerHost(false),
#if defined(MURASAKI_MPI) && defined(USE_SHM_SYSV)
  use_shm_sysv(true)
#else
  use_shm_sysv(false)
#endif
{
  staticInit();
  try {
    if(getenv("HOME"))
      config_file=string(getenv("HOME"))+"/.murasaki";
    if(exists(config_file)){
	loadConfig(config_file); //load both!
    }
  }catch(exception &e){}
  try {
    config_file="murasaki.cfg";
    if(exists(config_file)){
      loadConfig(config_file);//load both!
    }
  }catch(exception &e){}
}

void Options::preInit(){
#ifdef MURASAKI_MPI
  if(mpi_capable)
    mpi_maxBuffers=1024/mpi_procs+1;
#endif
}

struct option Options::long_options[] = {
  {"verbose",0,0,'v'},
  {"help",0,0,'h'},
  {"directory",1,0,'d'},
  {"pattern",1,0,'p'},
  {"name",1,0,'n'},
  {"version",0,0,'V'},
  {"quickhash",1,0,'q'},
  {"hashbits",1,0,'b'},
  {"histogram",2,0,'H'},
  {"hashtype",1,0,'t'},
  {"repeatmask",2,0,'r'},
  {"rseed",1,0,'s'},
  {"skip1to1",2,0,'1'},
  {"skipfwd",2,0,'F'},
  {"skiprev",2,0,'R'},
  {"hashonly",2,0,'Q'},
  {"hashcache",2,0,'c'},
  {"seedfilter",1,0,'f'},
  {"hashfilter",1,0,'m'},
  {"bitscore",2,0,'B'},
  {"join",2,0,'j'},
  {"hashskip",2,0,'S'},
  {"dumpregions",2,0,'G'},
  {"memory",1,0,'M'},
  {"seedterms",2,0,'T'},
  {"hashers",1,0,'A'},
  {"nocake",0,0,'K'},
  {"localhash",0,0,'K'},
  {"mpidistro",0,0,'L'},
  {"sectime",0,0,'e'},
  {"waittoanchor",2,0,'w'},
  {"mergefilter",1,0,'Y'},
  {"mmap",2,0,'P'},
  {"mmapperhost",2,0,'W'},
  {"sysvipc",2,0,'y'},
  {"nobuffer",0,0,'U'},
  {"buffers",1,0,'u'},
  {"bigfirst",2,0,'I'},
  {"repeatmap",2,0,'i'},
  {"hostbalance",2,0,'l'},
  {"tfidf",2,0,'k'},
  {"reverseotf",2,0,'o'},
  {"anchorprogress",1,0,'g'},
  {"memorybalance",2,0,'a'},
  {"leaverecords",2,0,'J'}, //J for junk
  {"distmerge",2,0,'<'}, //running out of letters!!!!
  {"distcollect",2,0,'>'}, 
  {"rifts",1,0,'/'},
  {"islands",1,0,'%'},
  {"fuzzyextend",2,0,'z'},
  {"fuzzyextendlosslimit",1,0,'Z'},

  //It's official. I've run out of letters
  {"gappedanchors",2,0,256},
  {"frugalecolist",2,0,257},
  {"scorefilter",1,0,258},
  {"probing",1,0,259},
  {"scorebyminimumpair",2,0,260},
  {"collisionprofile",2,0,261},
  {"mpioutputredirect",2,0,262},
  {"hitfilter",1,0,263},
  {"hasherfairentropy",2,0,264},
  {"hashercorrelationadjust",2,0,265},
  {"hashertargetgacycles",1,0,266},
  {"hasherentropyagro",1,0,267},
  {"keepstdoe",2,0,268},
  {"binaryseq",2,0,269},

  //uppercased
  {"hasherFairEntropy",2,0,264},
  {"hasherCorrelationAdjust",2,0,265},
  {"hasherTargetGACycles",1,0,266},
  {"hasherEntropyAgro",1,0,267},

  //testing purposes only
  {"randomHashInputs",1,0,1024},
  {0,0,0,0}
};

void Options::commandline_opts(int argc,char **argv){
  using namespace boost;

  int optc;
  char msgbuf[80]; //hate to do this...
  opterr=0;
  while(1){
    //options struct:
    // name, has_arg, store_pointer, return_value
    int longindex=0;
    string prefreq;
    optc=getopt_long(argc,argv,":>::<::%:/:1::A:B::C::F::G::H::I::J::L::M:P::Q::R::S:T::V?W::Y:Z:a::b:c::d:e::f:g:hi::j:k::l::m:n:o::p:q:r::s:t:u:vw::y::z::",long_options,&longindex);
    if(optc==-1)break;
    switch(optc){
    case 'h':
      cout << program_help(true);//ran --help or -h
      throw MurasakiAbortException("Help",0);
    case 'j':
      if(optarg && (strcmp(optarg,"0"))){
	string optstr(optarg);
	if(optstr==string("0") || isNo(optarg)){
	  joinNeighbors=false;
	  break;
	}
      }
      joinNeighbors=true;
      joinSpec=-1;
      if(optarg && !sscanf(optarg,"%f",&joinSpec))
	optErr("Could not parse join specification.");
      break;
    case 'S':
      if(optarg){
	if(!sscanf(optarg,"%d",&hashSkip))
	  optErr("Could not parse hashskip specification.");
      }else{
	hashSkip++;
      }
      if(hashSkip<=0)
	optErr("Skip has to be at least 1.");
      break;
    case 'A':
#ifdef MURASAKI_MPI      
      if(mpi_capable){
	if(optarg){
	  double percent;
	  if(sscanf(optarg,"%lf",&percent)){
	    if(percent>=0 && percent<1){
	      mpi_hashers=(int)(percent*(double)mpi_procs);
	      if(mpi_hashers==0)
		mpi_hashers=1;
	    }else{
	      if(!sscanf(optarg,"%d",&mpi_hashers))
		optErr("Could not parse hashers specification.");
	    }
	  }
	}
	if(hashSkip<=0)
	  optErr("Hashers has to be at least 1.");
      }else{
#endif
	cerr << "Option --hashers has no effect without MPI"<<endl;
#ifdef MURASAKI_MPI
      }
#endif
      break;
      
    case 'c':
      hashCache=true;
      if(optarg) cache_dir=string(optarg)+"/";
      else cache_dir="cache/";
      break;
    case 'v': verbose++;break;
    case 'V': cout << program_version();throw MurasakiAbortException("version request",0);break;
    case 'd': output_dir=string(optarg);break;
    case 'p': pattern_src=string(optarg);break;
    case 'n': alignment_name=string(optarg);break;
    case 'J': parseYesNo(optarg,leaveRecords,"leaverecords");break;
    case 'q':
      if(!sscanf(optarg,"%d",&quick_hash))
	optErr("Could not parse quickhash specification.");
      if( (quick_hash<100) && //call it a crazy way of writing, but this keeps syntax formatters from wigging out
#ifdef USE_LIBCRYPTOPP
	  (quick_hash>8 || quick_hash<0)
#else
	   (quick_hash>3 || quick_hash<0)
#endif
	  ){
	cerr << "Invalid quickhash specification ("<<quick_hash<<")."<<endl;
	quick_hash=3;
	cerr << "Setting quickhash to "<<quick_hash<<" instead."<<endl;
      }
      break;
    case 259:
      if(!sscanf(optarg,"%d",&probingMethod) || (probingMethod!=0 && probingMethod!=1))
	optErr("Invalid probing specification.");
      break;
    case 260:
      parseYesNo(optarg ,scoreByMinimumPair,"scoreByMinimumPair"); break;
    case 261:
      parseYesNo(optarg ,measureHashCollisions,"collisionprofile"); break;
    case 262:
      parseYesNo(optarg ,mpi_outputRedirect,"mpiOutputRedirect"); break;
    case 264:
      parseYesNo(optarg ,hasherFairEntropy,"hasherFairEntropy"); break;
    case 265:
      parseYesNo(optarg ,hasherCorrelationAdjust,"hasherCorrelationAdjust"); break;
    case 268:
      parseYesNo(optarg ,mpi_keepstdoe,"keepstdoe"); break;
    case 269:
      parseYesNo(optarg ,useSeqBinary,"binaryseq"); break;
    case 263:
      if(!sscanf(optarg,"%lu",&hitfilter))
	optErr("Could not parse hitfilter specification.");
      break;
    case 'b':
      if(!sscanf(optarg,"%d",&max_hash_bits))
	optErr("Could not parse hash size specification.");
      if(max_hash_bits>WORDSIZE || max_hash_bits<1){
	cout << "*** Warning *** "<<max_hash_bits << " hash bits?\n";
	cout << "A hash that big would get you in trouble...\nI'm going to make that "<<(WORDSIZE-2)<<" for you... (and even that may be too big for your system)\n" << endl;
	max_hash_bits=(WORDSIZE-2);
      }
      auto_hashbits=false;
      break;
    case 'H':
      histogram=1;
      if(optarg && sscanf(optarg,"%d",&histogram) && (histogram<0 || histogram>4)){
	cerr << histogram << " is not a valid choice for histogram.\n";
	histogram=2;
	cerr << "Using "<<histogram<<" instead.\n";
      }
      break;
    case 't':
      prefreq=optarg;
      if(prefreq=="ArrayHash")
	hashPref=ArrayHash_t;
      else if(prefreq=="MSetHash" || prefreq=="MultisetHash")
	hashPref=MSetHash_t;
      else if(prefreq=="EcoHash")
	hashPref=EcoHash_t;
      else if(prefreq=="OpenHash")
	hashPref=OpenHash_t;
      else cerr << "Unknown hash specification: "<<prefreq<<". Sticking with "<<hashPref_s()<<endl;
      break;
    case 'r':
      parseYesNo(optarg,repeatMask,"repeatmask");break;
    case 's':
      if(!sscanf(optarg,"%d",&rand_seed))
	optErr("Could not parse random seed specification (should be a number).");
      user_seed=true;
      break;
    case 'f':
      if(!sscanf(optarg,"%lu",&seedfilter))
	optErr("Could not parse seedfilter specification (should be a number).");
      if(seedfilter<0)
	seedfilter=0;
      break;
    case 258:
      if(!sscanf(optarg,"%lu",&scoreFilter))
	optErr("Could not parse scorefilter specification (should be a number).");
      if(scoreFilter<0)
	scoreFilter=0;
      break;
    case 'm':
      if(!sscanf(optarg,"%lu",&hashfilter))
	optErr("Could not parse hashfilter specification (should be a number).");
      if(hashfilter<0)
	hashfilter=0;
      break;
    case 'Y':
      if(!sscanf(optarg,"%lu",&mergeFilter))
	optErr("Could not parse mergefilter specification (should be a number).");
      if(mergeFilter<0)
	mergeFilter=0;
      break;
    case 'M':
      double val;
      if(strchr(optarg,'%') && sscanf(optarg,"%lf%%",&val)){
	targetMemory=(int)(sysinfo.totalMemory*val/100);
      }else if(sscanf(optarg,"%lf",&val)){
	targetMemory=(int)(val*1024*1024);
      }else{
	optErr("Could not parse target memory value (should be a number of gigabytes or a percent).");
      }
      userSetMemory=true;
      break;
    case 257:parseYesNo(optarg,ecolistFrugal,"frugalecolist");break;
    case 'z':parseYesNo(optarg,fuzzyExtend,"fuzzyextend");break;
    case 'i':parseYesNo(optarg,repeatMap,"repeatmap");break;
    case 'B': parseYesNo(optarg,bitscore,"bitscore");break;
    case 'F': parseYesNo(optarg,skipFwd,"skipfwd");break;
    case 'R': parseYesNo(optarg,skipRev,"skiprev");break;
    case '1':case '7': parseYesNo(optarg,skip1to1,"skip1to1");break;
    case 'Q': parseYesNo(optarg,hashOnly,"hashonly");break;
    case 'G': parseYesNo(optarg,dumpRegions,"dumpregions");break;
    case 'K': mpi_noCake=true;break;
    case 'L': parseYesNo(optarg,mpi_fileDistro,"mpidistro");break;
    case 'e': useHumanTime=false;break;
    case 'w': mpi_anchorInSpareTime=false;break;
    case 'T': parseYesNo(optarg,retainMembers,"retainMembers");
      if(!retainMembers && tfidf){
	cout << "Warning: tfidf requires --retainmembers=yes. Disabling tfidf."<<endl;
	tfidf=false;
      }
      break;
    case 'g': try {
	anchorProgressCheck=lexical_cast<word>(optarg);
      }catch(bad_lexical_cast& e){
	optErr("--anchorprogress needs a non-negative integer argument");
      }
      break;
    case 'U': 
#ifdef MURASAKI_MPI
      if(!mpi_capable)
#endif
	cout << "Warning: --nobuffer has no effect without MPI."<<endl;
      mpi_maxBuffers=1;break;
    case 'u': 
#ifdef MURASAKI_MPI
      if(!mpi_capable)
#endif
	cerr << "Warning: --buffers has no effect without MPI."<<endl;
#ifdef MURASAKI_MPI
      else
	try {
	  mpi_maxBuffers=lexical_cast<word>(optarg);
	}catch(bad_lexical_cast& e){
	  cerr << "Error: --buffers needs a non-negative integer argument"<<endl;
	}
#endif
      break;
    case 'I': 
#ifdef MURASAKI_MPI
      if(!mpi_capable)
#endif
	cerr << "Warning: --bigfirst has no effect without MPI."<<endl;
      parseYesNo(optarg,mpi_bigFirst,"bigfirst");
    case 'P': 
#if defined(USE_SHM_MMAP) && defined(MURASAKI_MPI)
      parseYesNo(optarg,use_shm_mmap,"mmap");
      if(use_shm_mmap)
	use_shm_sysv=false; //don't use both
#else
      cerr <<"Warning: The --mmap option requires MMAP support at compile time. (ignoring)"<<endl;
#endif
      break;
    case 'l': 
#ifdef MURASAKI_MPI
      parseYesNo(optarg,mpi_hostbalance,"hostbalance");
#else
      cerr <<"Warning: The --hostbalance option requires MPI support at compile time. (ignoring)"<<endl;
#endif
      break;
    case 'a': 
#ifdef MURASAKI_MPI
      parseYesNo(optarg,mpi_memoryBalance,"memorybalance");
#else
      cerr <<"Warning: The --memorybalance option requires MPI support at compile time. (ignoring)"<<endl;
#endif
      break;
    case 'W': 
#if defined(USE_SHM_MMAP) && defined(MURASAKI_MPI)
      parseYesNo(optarg,mmap_writePerHost,"mmapperhost");
#else
      cerr << "Warning: --mmapperhost requires MMAP support at compile time. (ignoring)"<<endl;
#endif
      break;
    case 'y': 
#ifdef USE_SHM_SYSV
      parseYesNo(optarg,use_shm_sysv,"sysvipc");
      if(use_shm_sysv)
	use_shm_mmap=false; //don't use both
#else
      cerr << "Warning: --sysvipc requires System V IPC support at compile time. (ignoring)"<<endl;
#endif
      break;
    case '<': 
#ifdef MURASAKI_MPI
      parseYesNo(optarg,mpi_distMerge,"distmerge");
      if(mpi_distMerge && !mpi_distCollect){
	cerr << "Warning: --distmerge requires --distcollect (enabling distcollect)"<<endl;
	mpi_distCollect=true;
      }
#else
      cerr <<"Warning: The --distmerge option requires MPI support at compile time. (ignoring)"<<endl;
#endif
      break;
    case '>': 
#ifdef MURASAKI_MPI
      parseYesNo(optarg,mpi_distCollect,"distcollect");
      if(!mpi_distCollect && mpi_distMerge){
	cerr << "Warning: --distmerge requires --distcollect (disabling distmerge)"<<endl;
	mpi_distMerge=false;
      }
#else
      cerr <<"Warning: The --distcollect option requires MPI support at compile time. (ignoring)"<<endl;
#endif
      break;
    case 'k':
      parseYesNo(optarg,tfidf,"tfidf");
      break;
    case 'o':parseYesNo(optarg,reverseOtf,"reverseotf");break;
    case '/':try {
	rifts=lexical_cast<int>(optarg);
      }catch(bad_lexical_cast& e){
	optErr("Error: --rifts needs a non-negative integer argument");
      }
      break;
    case '%':try {
	set_islands=lexical_cast<int>(optarg);
      }catch(bad_lexical_cast& e){
	optErr("Error: --rifts needs a non-negative integer argument");
      }
      break;
    case 'Z':try {
	fuzzyExtendLossLimit=lexical_cast<Score>(optarg);
      }catch(bad_lexical_cast& e){
	optErr("Error: --fuzzyextendlosslimit needs a non-negative integer argument");
      }
      break;
    case 266:try {
	hasherTargetGACycles=lexical_cast<word>(optarg);
      }catch(bad_lexical_cast& e){
	optErr("Error: --hasherTargetGACycles needs a non-negative integer argument");
      }
      break;
    case 267:try {
	hasherEntropyAgro=lexical_cast<double>(optarg);
      }catch(bad_lexical_cast& e){
	optErr("Error: --hasherEntropyAgro needs a real numeric argument");
      }
      break;
    case 256: parseYesNo(optarg,gappedAnchors,"gappedanchors");break;

      //testing
    case 1024:
      parseLexical(optarg,randomHashInputs,"randomHashInputs");break;


      //error cases:
    case ':':
      sprintf(msgbuf,"Option -%c requires an argument",optopt);
      optErr(msgbuf);break;
    case '?':
      snprintf(msgbuf,sizeof(msgbuf),"Unknown option %s",argv[optind-1]);
      optErr(msgbuf);break;
    default: optErr("Unknown argument. Try --help");break;
    }
    optionSource[optc]=OPT_SRC_MANUAL;
  }

  if(tfidf && !retainMembers){
    cout << "Warning: tfidf requires --retainmembers=yes, disablign tfidf."<<endl;
    tfidf=false;
  }
}

template<typename T>
void parseLexical(const char* str,T& ref,const char *name){
  using namespace boost;
  try {
    ref=lexical_cast<T>(optarg);
  }catch(bad_lexical_cast& e){
    optErr("Invaild argument for %s.",name);
  }  
}

void parseYesNo(const char* str,bool& toggle,const char *name){
  if(str){
    if(isYes(str))toggle=true;
    else if(isNo(str))toggle=false;
    else {
      optErr("Please specify either yes/t/true or no/n/false as an argument to --%s",name);
    }
  }else{
    toggle=!toggle;
  }
}

void Options::solidify(){ //finalize annoying names and crap
#ifdef MURASAKI_MPI
#ifdef USE_SHM_SYSV
  if(!mpi_capable)
    use_shm_sysv=false;
#endif
#endif
  //transfer options to other modules
  timing_useHumanTime=useHumanTime;

  if((int)set_islands>1 && (int)set_islands<seq_count)
    rifts=seq_count-set_islands;
  if((int)rifts>seq_count-2){
    cerr << "Warning: User supplied rifts ("<<rifts<<") is set to high.";
    rifts=seq_count-2;
    cerr << " Setting to "<<rifts<<endl;
  }

  //Any postprocessing
  if(joinNeighbors){
    if(joinSpec<0)
      joinDist=(int)(-1.0*joinSpec*(float)pattern_src.length());
    else
      joinDist=(int)joinSpec;
  }

  if(fuzzyExtendLossLimit<1){ //set fuzzyExtendLimit automatically if unset
    //blastz uses 10*(A-to-A match score) as a default, we probably should too
    fuzzyExtendLossLimit=ScoreMatrix[BASE_A][BASE_A]*10;
  }

  //make necessary directories
  if(hashCache){
    path cachedir(cache_dir);
    if(exists(cachedir)){
      if(!is_directory(cachedir)){
	optErr("Cache directory (%s) is not a directory.",cache_dir.c_str());
      }
    }else{
      bool res=false;
      try{res=create_directory(cachedir);}
      catch(exception &e){optErr("Error creating directory %s: %s",cache_dir.c_str(),e.what());}
      if(res)
	cout << "Created cache directory: "
	     <<system_complete(cachedir).string()<<endl;
    }
  }
  
  prefix=output_dir+"/"+alignment_name;
  path dir(output_dir);
  if(dir.empty())
    dir=current_path();
  else {
    if(exists(dir)){
      if(!is_directory(dir)){
	optErr("Output directory (%s) is not a directory.",output_dir.c_str());
      }
    }else{
      bool res=false;
      try{res=create_directory(dir);}
      catch(exception &e){optErr("Error creating directory %s: %s",output_dir.c_str(),e.what());}
      if(res)
	cout << "Created output directory: "<<system_complete(dir).string()<<endl;
    }
  }

  //make up file names
#ifdef MURASAKI_MPI
  if( mpi_id!=0 ){
    char mpi_id_str[81];
    snprintf(mpi_id_str, 80, "%d", mpi_id);
    status_record=prefix+"."+mpi_id_str+".status";
  }
  else
#endif
    status_record=prefix+".status";

  hashStatus_record=prefix+".hashstatus";
  seq_record=prefix+".seqs";
  anchor_record=prefix+".anchors";
  repeat_record=prefix+".repeats";
  pat_record=prefix+".pat";
  region_record=prefix+".regions";
  hashHisto_record=(prefix+".histogram");
  hashDetailed_record=(prefix+".histogram.details");
  options_record=prefix+".options";
  anchorProgress_record=prefix+".anchors.progress";

  if(opt.verbose)
    seqreadOptions=SEQO_VERBOSE;
  if(opt.repeatMask)
    seqreadOptions|=SEQO_RMASK;
}

ostream& operator<<(ostream &opf,const Options &a){
  opf << "Verbosity level is: "<<verbose<<endl;
  opf << "Writing to: " << a.prefix<<endl;
  opf << "Pattern is: " << pattern_src<<endl;
  opf << "Max usable hash bits: "<<max_hash_bits<<endl;
  opf << "Hit filter is: "<<a.hitfilter<<endl;
  opf << "Hash table type is: "<<a.hashPref_s()<<endl;
  if(a.hashPref==OpenHash_t)
    opf << "Probing method is: "<<a.probingMethod<<endl;
  opf << "Hashing every: "<<(a.hashSkip)<<" base"<<endl;
  opf << "Histogram detail is: "<<a.histogram<<endl;
  opf << "Hashing function is: "<<a.quick_hash<<endl;
#ifdef MURASAKI_MPI
  if(!mpi_capable)
    opf << "Collision profiling is: "<<(a.measureHashCollisions ? "enabled":"disabled")<<endl;
  else
    opf << "Collision profiling is: unavailable with MPI"<<endl;
#else
    opf << "Collision profiling is: "<<(a.measureHashCollisions ? "enabled":"disabled")<<endl;  
#endif
  opf << "Repeats are: "<<(a.repeatMask ? "masked":"unmasked")<<endl;
  if(a.seedfilter)
    opf << "Seedfilter is at: "<<a.seedfilter<<endl;
  if(a.hashfilter)
    opf << "Hashfilter is at: "<<a.hashfilter<<endl;
  if(a.mergeFilter)
    opf << "Mergefilter is at: "<<a.mergeFilter<<endl;
  if(a.scoreFilter)
    opf << "Scorefilter is at: "<<a.scoreFilter<<endl;
  opf << "Random seed: "<<(a.rand_seed)<<(a.user_seed ? " (custom)":" (automatic)")<<endl;
  if(a.skipFwd || a.skipRev || a.skip1to1)
    opf << "Skip: "<<(a.skipFwd ? "forward ":"")<<(a.skipRev ? "reverse ":"")
	<< (a.skip1to1 ? "1-to-1 ":"") << endl;
  opf << "Bitscore output: "<<(a.bitscore ? "on":"off")<<endl;
  opf << "Leave status records: "<<(a.leaveRecords ? "yes":"no")<<endl;
  opf << "Join neighbors is: "<<(a.joinNeighbors ? (string("at ")+dstring(a.joinDist)):"off")<<endl;
  opf << "Target memory is: "<<humanMemory(a.targetMemory*1024)<<endl;
  opf << "Retain members is: "<<(a.retainMembers ? "true":"false")<<endl;
  opf << "Store repeatmap? "<<(a.repeatMap ? "yes":"no")<<endl;
  opf << "Reverse complement data is "<<(a.reverseOtf ? "generated on the fly":"computed at sequence loading")<<endl;
  opf << "Rifts allowed: "<<(a.rifts)<<endl;
  opf << "Fuzzy Extension: "<<(a.fuzzyExtend ? "yes":"no")<<endl;
  opf << "Score by minimum pair: "<<(a.scoreByMinimumPair ? "yes":"no")<<endl;
  opf << "Gapped anchors: "<<(a.gappedAnchors ? "yes":"no")<<endl;
#ifdef LARGESEQ_SUPPORT
  bool largeSeqs=true;
#else
  bool largeSeqs=false;
#endif
  opf << "Large sequence support is: "<<(largeSeqs ? "enabled":"disabled");
  opf <<" => seqpos is "<<(sizeof(SeqPos))<<" bytes"<<endl;
#ifdef MURASAKI_MPI  
  opf << "MPI>MPI is: "<<(mpi_capable ? "enabled":"disabled")<<endl;
  if(mpi_capable){
#ifdef USE_SHM_MMAP
  opf << "MPI>MMAP is: "<<(a.use_shm_mmap ? "enabled":"disabled")<<endl;
#endif
#ifdef USE_SHM_SYSV
  opf << "MPI>System V IPC shared memory is: "<<(a.use_shm_sysv ? "enabled":"disabled")<<endl;
#endif
    opf << "MPI>Hashers is: "<<(a.mpi_hashers)<<endl;
    opf << "MPI>np is: "<<mpi_procs<<endl;
    opf << "MPI>MPI-based file distribution is: "<<(a.mpi_fileDistro ? "enabled":"disabled")<<endl;
    opf << "MPI>Distributed hashing? "<<(a.mpi_noCake ? "no":"yes")<<endl;
    opf << "MPI>Wait to anchor? "<<(a.mpi_anchorInSpareTime ? "no":"yes")<<endl;
    opf << "MPI>Max buffers: "<<(a.mpi_maxBuffers ? boost::lexical_cast<string>(a.mpi_maxBuffers):string("unlimited"))<<endl;
    opf << "MPI>Allocate hashers on "<<(a.mpi_bigFirst ? "big":"small")<<" nodes first"<<endl;
    opf << "MPI>Balance hasher allocation? "<<(a.mpi_hostbalance ? "yes":"no")<<endl;
    opf << "MPI>Balance storage allocation? "<<(a.mpi_memoryBalance ? "yes":"no")<<endl;
    opf << "MPI>Distributed merging? "<<(a.mpi_distMerge ? "yes":"no")<<endl;
    opf << "MPI>Distributed collection? "<<(a.mpi_distCollect ? "yes":"no")<<endl;
  }
#endif
  opf << program_version();
  return opf;
}

string Options::hashPref_s() const{
  switch(hashPref){
  case ArrayHash_t:return string("Array");
  case MSetHash_t:return string("Multiset");
  case EcoHash_t:return string("EcoHash");
  case OpenHash_t:return string("OpenHash");
  default: return string("Unknown????");
  }
}

void Options::loadConfig(string file){
  ifstream cfg(file.c_str());
  //construct a phony argv
  vector<char*> argv;
  char cmd[]="murasaki";
  argv.push_back(cmd);
  string tmp;
  char buf[2048];
  while(cfg.good()){
    cfg.getline(buf,sizeof(buf));
    tmp=string(buf);
    while(cfg.fail()){ //for absurdly long inputs
      cfg.getline(buf,sizeof(buf));
      tmp+=buf;
    }
    argv.push_back(new char[tmp.length()]);
    strcpy(argv.back(),tmp.c_str());
  }
  commandline_opts(argv.size(),&argv.front()); //hoho stl rocks
}

string program_help(bool longhelp){
  
  string ret("\
Usage: murasaki -p<patternSpec> [options] seq1 [seq2 [seq3 ... ]]\n");
  if(longhelp)
    ret+=string("\
Options:\n\
  --pattern|-p   = seed pattern (eg. 11101001010011011).\n\
                    using the format [<w>:<l>] automatically generates a\n\
                    random pattern of weight <w> and length <l>\n\
  --directory|-d = output directory (default: output)\n\
  --name|-n      = alignment name (default: test)\n\
  --quickhash|-q = specify a hashing function:\n\
                    0 - adaptive with S-boxes\n\
                    1 - don't pack bits to make hash (use first word only)\n\
                    2 - naively use the first hashbits worth of pattern\n\
                    3 - adaptivevely find a good hash (default)\n")+
#ifdef USE_LIBCRYPTOPP
    string("\
                    **experimental CryptoPP hashes**\n\
                    4 - MD5\n\
                    5 - SHA1\n\
                    6 - Whirlpool\n\
                    7 - CRC-32\n\
                    8 - Adler-32\n")+
#endif
    string("\
  --hashbits|-b  = use n bit hashes (for n's of 1 to WORDSIZE. default 26)\n\
  --hashtype|-t  = select hash table data structure to use:\n\
                    OpenHash  - open sub-word packing of hashbits\n\
                    EcoHash   - chained sub-word packing of hashbits (default)\n\
                    ArrayHash - malloc/realloc (fast but fragmenty)\n\
                    MSetHash  - memory exorbanant, almost pointless.\n\
  --probing      = 0 - linear, 1 - quadratic (default)\n\
  --hitfilter|-h = minimum number of hits to be outputted as an anchor\n\
                   (default 1)\n\
  --histogram|-H = histogram computation level: (-H alone implies -H1)\n\
                    0 - no histogram (default)\n\
                    1 - basic bucketsize/bucketcount histogram data\n\
		    2 - bucket-based scores to anchors.detils\n\
                    3 - perbucket count data\n\
		    4 - perbucket + perpattern count data\n\
  --repeatmask|-r= skip repeat masked data (ie: lowercase atgc)\n\
  --seedfilter|-f= skip seeds that occur more than N times\n\
  --hashfilter|-m= like --seedfilter but works on hash keys instead of\n\
                   seeds. May cause some collateral damage to otherwise\n\
                   unique seeds, but it's faster. Also non-sequence-specific\n\
                   so more like at best 1/N the tolerance of seedfilter.\n\
  --rseed|-s     = random number seed for non-deterministic algorithms\n\
                   (ie: the adative hash-finding). If you're doing any\n\
                   performance comparisons, it's probably imperative that you\n\
                   use the same seed for each run of the same settings.\n\
                   Default is obtained from time() (ie: seconds since 1970).\n\
  --skipfwd|-F   = Skip forward facing matches\n\
  --skiprev|-R   = Skip reverse facing matches\n\
  --skip1to1|-1  = Skip matches along the 1:1 line (good for comparing to self)\n\
  --hashonly|-Q  = Hash Only. no anchors. just statistics.\n\
  --hashskip|-S  = Hashes every n bases. (Default is 1. ie all)\n\
                   Not supplying any argument increments the skip amount by 1.\n\
  --hashCache|-c = Caches hash tables in the directory. (default: cache/)\n\
  --join|-j      = Join anchors within n bases of eachother (default: 0)\n\
                   Specifying a negative n implies -n*patternLength\n\
  --bitscore|-B  = toggles compututation of a bitscore for all anchors\n\
                   (default is on)\n\
  --memory|-M    = set the target amount of total memory\n\
                    (either in gb or as % total memory)\n\
  --seedterms|-T = toggles retention of seed terms (defaults to off)\n\
                    (these are necessary for computing TF-IDF scores)\n\
  --sectime|-e   = always display times in seconds\n\
  --repeatmap|-i = toggles keeping of a repeat map when --mergefilter\n\
                   is used (defaults to yes).\n\
  --mergefilter|-Y = filter out matches which would would cause more than N\n\
                     many anchors to be generated from 1 seed (default -Y100).\n\
                     Use -Y0 to disable.\n\
  --scorefilter    = set a minimum ungapped score for seeds\n\
  --tfidf|-k       = perform accurate tfidf scoring from within murasaki\n\
                     (requires extra memory at anchor generation time)\n\
  --reverseotf|-o  = generate reverse complement on the fly (defaults to on)\n\
  --rifts|-/       = allow anchors to skip N sequences (default 0)\n\
  --islands|-%     = same as --rifts=S-N (where S is number of seqs)\n\
  --fuzzyextend|-z = enable (default) or disable fuzzy extension of hits\n\
  --fuzzyextendlosslimit|-Z = set the cutoff at which to stop extending\n\
                      fuzzy hits (ie. the BLAST X parameter).\n\
  --gappedanchors  = use gapped (yes) or ungapped (no (default)) anchors.\n\
  --scorebyminimumpair = do anchor scoring by minimum pair when appropriate\n\
                     (default). Alternative is mean (somewhat illogical, but\n\
                     theoretically faster).\n\
  --binaryseq      = enable (default) or disable binary sequence read/write\n\
\n\
Adaptive has function related:\n\
  --hasherFairEntropy = use more balanced entropy estimation (default: yes)\n\
  --hasherCorrelationAdjust = adjust entropy estimates for nearby sources\n\
        assuming some correlation (default: yes)\n\
  --hasherTargetGACycles = GA cycle cutoff\n\
  --hasherEntropyAgro = how aggressive to be about pursuing maximum\n\
        entropy hash functions (takes a real. default is 1).\n\
")+
#ifdef MURASAKI_MPI
    string("MPI Specific: \n\
  --hashers|-A   = specify the number of processes to be used as hashers\n\
                    (only applies to MPI. If a number between 0 and 1\n\
                     it refers to a % of np)\n\
  --localhash|-K  = perform hashing locally on each storage node rather than\n\
                   sending it over the network (helpful for slow networks)\n\
  --mpidistro|-L  = toggles use of MPI to distribute sequence data over\n\
                    (if the sequence is available on local disk on each\n\
                     node then turning this off may increase performance)\n\
  --waittoanchor|-w = postpone actual anchor computation until all location\n\
                      sets have been received.\n\
  --buffers|-u  = maximum number of unfinished buffers to allow while\n\
                     message passing (0 means unlimited)\n\
  --nobuffers|-U   = same as --buffers=1\n\
  --bigfirst|-I    = assign hashers to large memory nodes first\n\
  --hostbalance|-l = if yes (default): spread out hashers evenly among hosts\n\
                     if no: ignore host name when assigning jobs\n\
  --memorybalance|-a = if yes (default): balance hash storage between nodes\n\
                       based on the amount of available ram.\n\
                       if no: distribute storage evently.\n\
  --distmerge|-< = if yes (default): during the merge step, send seeds to\n\
                   all participating hashers.\n\
                   if no: send all seeds to one node only\n\
  --distcollect|-> = if yes (default): collect anchor data from all hashers\n\
                     if no: send all seeds to the final assembly node only\n\
  --mpiredirectoutput = if yes (default): each rank redirects its stdout/stderr\n\
                          to a separate file\n\
                        if no: do what comes naturally (ie: managed by mpirun).\n\
  --keepstdoe      = don't erase the murasaki-mpiout files on success.\n\
")+
#endif
#ifdef USE_SHM_MMAP
    string("\
  --mmap|-P      = use filebacked mmap() to store sequence data\n\
                    (saves memory when one host runs multiple nodes)\n\
  --mmapperhost|-W = create files for mmap() on each host\n\
                     (ie: for when sequence sources aren't stored on NFS)\n\
")+
#endif
#ifdef USE_SHM_SYSV
    string("\
  --sysvipc|-V   = use System V IPC to negotiate shared memory regions\n\
                    (saves memory when one host runs multiple nodes)\n\
")+
#endif
#ifndef NDEBUG
    string("\n\
Debugging options:\n\
  --leaverecords|-J= don't erase .status and -mpiout files on successful\n\
                     completion (default is to erase them)\n\
  --dumpregions|-G = dump list of comparable regions for each sequence\n\
                     (ie: the areas between N's)\n\
  --anchorprogress|-g = log the number of anchors in memory and the amount\n\
                        of free memory every N location-sets processed\n\
  --collisionprofile  = analyze hash function collision performance (no MPI)\n\
\n")+
#endif
    
    string("\
...and of course\n\
  --verbose|-v   = increases verbosity\n\
  --version|-V   = prints version information and quits\n\
  --help|-?      = prints this help message and quits\n\
\n")+platformInfo()+program_version();
  else
    ret+=string("For more information try --help\n\n")+program_version();
  return ret;
}