package hiseq;

import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLongArray;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import bloom.BloomFilter;
import bloom.KmerCountAbstract;
import bloom.PolyFilter;
import dna.AminoAcid;
import fileIO.ByteFile;
import fileIO.ByteStreamWriter;
import fileIO.FileFormat;
import fileIO.ReadWrite;
import jgi.Dedupe;
import shared.Parse;
import shared.Parser;
import shared.PreParser;
import shared.Shared;
import shared.Timer;
import shared.Tools;
import shared.TrimRead;
import stream.ConcurrentReadInputStream;
import stream.ConcurrentReadOutputStream;
import stream.FASTQ;
import stream.FastaReadInputStream;
import stream.Read;
import stream.SamLine;
import stream.SamReadStreamer;
import structures.ByteBuilder;
import structures.ListNum;
import structures.LongList;
import template.Accumulator;
import template.ThreadWaiter;

/**
 * Analyzes a flow cell for low-quality areas.
 * Removes reads in the low-quality areas.
 * 
 * @author Brian Bushnell
 * @date August 31, 2016
 *
 */
public class AnalyzeFlowCellMT0 implements Accumulator<AnalyzeFlowCellMT0.ProcessThread> {
	
	/*--------------------------------------------------------------*/
	/*----------------        Initialization        ----------------*/
	/*--------------------------------------------------------------*/
	
	/**
	 * Code entrance from the command line.
	 * @param args Command line arguments
	 */
	public static void main(String[] args){
		Timer t=new Timer();
		AnalyzeFlowCellMT0 x=new AnalyzeFlowCellMT0(args);
		x.process(t);
		
		//Close the print stream if it was redirected
		Shared.closeStream(x.outstream);
	}
	
	/**
	 * Constructor.
	 * @param args Command line arguments
	 */
	public AnalyzeFlowCellMT0(String[] args){
		
		{//Preparse block for help, config files, and outstream
			PreParser pp=new PreParser(args, getClass(), false);
			args=pp.args;
			outstream=pp.outstream;
		}
		
		//Set shared static variables
		ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
		ReadWrite.setZipThreads(Shared.threads());
		
		Parser parser=parse(args);
		
		if(gToN || discardG){MicroTile.TRACK_CYCLES=true;}
		
		{//Process parser fields
			Parser.processQuality();
			
			maxReads=parser.maxReads;
			
			overwrite=parser.overwrite;
			append=parser.append;
			setInterleaved=parser.setInterleaved;
			
			in1=parser.in1;
			in2=parser.in2;

			out1=parser.out1;
			out2=parser.out2;
			
			extin=parser.extin;
			extout=parser.extout;
			

			trimq=parser.trimq;
			trimE=parser.trimE();
			minlen=parser.minReadLength;
			trimLeft=parser.qtrimLeft;
			trimRight=parser.qtrimRight;
		}
		
		checkFiles();
		
		//Create output FileFormat objects
		ffout1=FileFormat.testOutput(out1, FileFormat.FASTQ, extout, true, overwrite, append, false);
		ffout2=FileFormat.testOutput(out2, FileFormat.FASTQ, extout, true, overwrite, append, false);
		ffoutbad=FileFormat.testOutput(outbad, FileFormat.FASTQ, extout, true, overwrite, append, false);

		//Create input FileFormat objects
		ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
		ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
	}
	
	/*--------------------------------------------------------------*/
	/*----------------    Initialization Helpers    ----------------*/
	/*--------------------------------------------------------------*/
	
	private Parser parse(String[] args){
		//Create a parser object
		Parser parser=new Parser();
		parser.qtrimRight=trimRight;
		parser.trimq=trimq;
		parser.minReadLength=minlen;
		
		//Parse each argument
		for(int i=0; i<args.length; i++){
			String arg=args[i];
			
			//Break arguments into their constituent parts, in the form of "a=b"
			String[] split=arg.split("=");
			String a=split[0].toLowerCase();
			String b=split.length>1 ? split[1] : null;
			
			if(a.equals("verbose")){
				verbose=Parse.parseBoolean(b);
			}else if(a.equals("outb") || a.equals("outbad")){
				outbad=b;
			}else if(a.equals("sam") || a.equals("insam") || 
					a.equals("samin") || a.equals("saminput")){
				samInput=b;
			}else if(a.equals("seed")){
				seed=Long.parseLong(b);
			}else if(a.equals("divisor") || a.equals("size")){
				Tile.xSize=Tile.ySize=Parse.parseIntKMG(b);
			}else if(a.equals("xdivisor") || a.equals("xsize")){
				Tile.xSize=Parse.parseIntKMG(b);
			}else if(a.equals("ydivisor") || a.equals("ysize")){
				Tile.ySize=Parse.parseIntKMG(b);
			}else if(a.equals("trackdepth")){
				MicroTile.trackDepth=Parse.parseBoolean(b);
			}else if(a.equals("target")){
				targetAverageReads=Parse.parseIntKMG(b);
			}else if(a.equals("dump") || a.equals("dumpout")){
				dumpOut=b;
			}else if(a.equals("indump") || a.equals("ind") || a.equals("dumpin")){
				dumpIn=b;
			}else if(a.equals("filterout") || a.equals("filterlist") || a.equals("coordinates")
					 || a.equals("coords") || a.equals("coordsout") || a.equals("coordinatesout")){
				coordsOut=b;
			}else if(a.equals("kdump") || a.equals("bloomout")){
				bloomOut=b;//TODO
			}else if(a.equals("kdumpin") || a.equals("bloomin") || a.equals("bloom")){
				bloomIn=b;//TODO
			}else if(a.equals("pound")){
				pound=Parse.parseBoolean(b);
			}else if(a.equals("loadkmers") || a.equals("usekmers")){
				loadKmers=Parse.parseBoolean(b);
			}else if(a.equals("loadthreads")){
				loadThreads=Integer.parseInt(b);
			}else if(a.equals("fillthreads")){
				fillThreads=Integer.parseInt(b);
			}else if(a.equals("allkmers")){
				kmersPerRead=(Parse.parseBoolean(b) ? 0 : 1);
			}else if(a.equals("kmersperread")){
				kmersPerRead=Integer.parseInt(b);
			}else if(a.equals("samples")){
				samples=Integer.parseInt(b);
			}else if(a.equals("minprob")){
				minProb=Float.parseFloat(b);
			}else if(a.equals("bits") || a.equals("cbits")){
				cbits=Integer.parseInt(b);
			}
			
			else if(a.equals("minpolyg")){
				MicroTile.MIN_POLY_G=Integer.parseInt(b);
			}else if(a.equals("trackcycles")){
				MicroTile.TRACK_CYCLES=Parse.parseBoolean(b);
			}else if(a.equals("extra")){
				if(b!=null) {
					for(String s : b.split(",")) {
						extra.add(s);
					}
				}
			}
			
			else if(a.equals("qdeviations") || a.equals("qd")){
				qDeviations=Float.parseFloat(b);
			}else if(a.equals("udeviations") || a.equals("ud")){
				uDeviations=Float.parseFloat(b);
			}else if(a.equals("edeviations") || a.equals("ed")){
				eDeviations=Float.parseFloat(b);
			}else if(a.equals("pgdeviations") || a.equals("pgd")){
				pgDeviations=Float.parseFloat(b);
			}
			else if(a.equals("qfraction") || a.equals("qf")){
				qualFraction=Float.parseFloat(b);
			}else if(a.equals("ufraction") || a.equals("uf")){
				uniqueFraction=Float.parseFloat(b);
			}else if(a.equals("efraction") || a.equals("ef")){
				errorFreeFraction=Float.parseFloat(b);
			}else if(a.equals("pgfraction") || a.equals("pgf")){
				polyGFraction=Float.parseFloat(b);
			}
			else if(a.equals("qabsolute") || a.equals("qa")){
				qualAbs=Float.parseFloat(b);
			}else if(a.equals("uabsolute") || a.equals("ua")){
				uniqueAbs=Float.parseFloat(b);
			}else if(a.equals("eabsolute") || a.equals("ea")){
				errorFreeAbs=Float.parseFloat(b);
			}else if(a.equals("pgabsolute") || a.equals("pga")){
				polyGAbs=Float.parseFloat(b);
			}
			
			else if(a.equals("lqo") || a.equals("lowqualityonly")){
				discardOnlyLowQuality=Parse.parseBoolean(b);
			}else if(a.equals("dmult")){
				dmult=Float.parseFloat(b);
			}
			
			else if(a.equals("parse_flag_goes_here")){
				//Set a variable here
			}else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
				//do nothing
			}else if(b==null && new File(arg).exists()){
				extra.add(b);
			}else{
				outstream.println("Unknown parameter "+args[i]);
				assert(false) : "Unknown parameter "+args[i];
				//				throw new RuntimeException("Unknown parameter "+args[i]);
			}
		}
		return parser;
	}
	
	private void checkFiles(){
		doPoundReplacement();
		adjustInterleaving();
		checkFileExistence();
		checkStatics();
	}
	
	private void doPoundReplacement(){
		//Do input file # replacement
		if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
			in2=in1.replace("#", "2");
			in1=in1.replace("#", "1");
		}

		//Do output file # replacement
		if(out1!=null && out2==null && out1.indexOf('#')>-1){
			out2=out1.replace("#", "2");
			out1=out1.replace("#", "1");
		}
		
		//Ensure there is an input file
		if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}

		//Ensure out2 is not set without out1
		if(out1==null && out2!=null){throw new RuntimeException("Error - cannot define out2 without defining out1.");}
	}
	
	private void checkFileExistence(){
		
		//Ensure output files can be written
		if(!Tools.testOutputFiles(overwrite, append, false, out1, out2, outbad, dumpOut)){
			outstream.println((out1==null)+", "+(out2==null)+", "+out1+", "+out2+", "+outbad);
			throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+", "+outbad+", "+dumpOut+"\n");
		}

		//Ensure input files can be read
		if(!Tools.testInputFiles(false, true, in1, in2, samInput, dumpIn)){
			throw new RuntimeException("\nCan't read some input files.\n");  
		}

		//Ensure that no file was specified multiple times
		if(!Tools.testForDuplicateFiles(true, in1, in2, out1, out2, outbad, samInput, dumpIn, dumpOut)){
			throw new RuntimeException("\nSome file names were specified multiple times.\n");
		}
	}
	
	private void adjustInterleaving(){
		//Adjust interleaved detection based on the number of input files
		if(in2!=null){
			if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
			FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
		}

		//Adjust interleaved settings based on number of output files
		if(!setInterleaved){
			assert(in1!=null && (out1!=null || out2==null)) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\nout2="+out2+"\n";
			if(in2!=null){ //If there are 2 input streams.
				FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
				outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
			}else{ //There is one input stream.
				if(out2!=null){
					FASTQ.FORCE_INTERLEAVED=true;
					FASTQ.TEST_INTERLEAVED=false;
					outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
				}
			}
		}
	}
	
	private static void checkStatics(){
		//Adjust the number of threads for input file reading
		if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
			ByteFile.FORCE_MODE_BF2=true;
		}
		
		assert(FastaReadInputStream.settingsOK());
	}
	
	/*--------------------------------------------------------------*/
	/*----------------         Outer Methods        ----------------*/
	/*--------------------------------------------------------------*/

	/** Create read streams and process all data */
	public void process(Timer t){
		
		//Reset counters
		readsProcessed=0;
		basesProcessed=0;
		
		if(dumpIn==null){
			flowcell=new FlowCell(k);
			if(loadKmers){loadKmers();}
			fillTiles();
			
			bloomFilter=null;//Clearing before widen saves memory
			ArrayList<MicroTile> mtList;
			synchronized(flowcell) {
				mtList=flowcell.calcStats();
				if(flowcell.avgReads<targetAverageReads){
					flowcell=flowcell.widenToTargetReads(targetAverageReads);
					mtList=flowcell.toList();
				}
//				if(MicroTile.trackDepth) {flowcell.summarizeDepth();}
				loadSam(samInput);
			}

			long readsToDiscard=markTiles(mtList, flowcell.avgReads);

			if(dumpOut!=null){flowcell.dump(dumpOut, overwrite);}
		}else{
			flowcell=new FlowCell(dumpIn);
//			if(loadKmers){loadKmers();}
			if(flowcell.avgReads<targetAverageReads){
				flowcell=flowcell.widenToTargetReads(targetAverageReads);
			}
			long readsToDiscard=markTiles(flowcell.toList(), flowcell.avgReads);
		}
		System.err.println("Avg quality:     \t"+Tools.format("%.3f", flowcell.avgQuality));
		System.err.println("STDev quality:   \t"+Tools.format("%.3f", flowcell.stdQuality));
		System.err.println("Avg uniqueness:  \t"+Tools.format("%.3f", flowcell.avgUnique));
		System.err.println("STDev uniqueness:\t"+Tools.format("%.3f", flowcell.stdUnique));
		System.err.println("Avg poly-G:      \t"+Tools.format("%.3f", flowcell.avgPolyG));
		System.err.println("STDev poly-G:    \t"+Tools.format("%.3f", flowcell.stdPolyG));
		processReads(t);
	}

	/** Create read streams and process all data */
	void loadKmers(){
		Timer t2=new Timer();
		outstream.print("Loading kmers:  \t");
		
		loadThreads=Tools.min(loadThreads, Shared.threads());
		final int oldMCT=KmerCountAbstract.MAX_COUNT_THREADS;
		final float oldProb=KmerCountAbstract.minProb;
		KmerCountAbstract.KMERS_PER_READ=kmersPerRead;
		KmerCountAbstract.minProb=minProb;
		KmerCountAbstract.CANONICAL=true;
		
		if(loadThreads>1) {
			if(kmersPerRead>0 && kmersPerRead<4) {KmerCountAbstract.MAX_COUNT_THREADS=loadThreads;}
			bloomFilter=new BloomFilter(in1, in2, extra, k, k, cbits, hashes, 
					1, true, false, false, 0.6f);
			bloomFilter.filter.shutdown();
		}else {
			//Create a read input stream
			final ConcurrentReadInputStream cris;
			{
				cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2);
				cris.start(); //Start the stream
				if(verbose){outstream.println("Started cris");}
			}
			boolean paired=cris.paired();
			//Process the read stream
			loadKmersInner(cris);
			
//			if(verbose){outstream.println("Finished; closing streams.");}
			
			//Close the read streams
			errorState|=ReadWrite.closeStreams(cris);
			bloomFilter.filter.shutdown();
		}
		
		KmerCountAbstract.KMERS_PER_READ=0;
		KmerCountAbstract.MAX_COUNT_THREADS=oldMCT;
		KmerCountAbstract.minProb=oldProb;
		
		double used=bloomFilter.filter.usedFraction();
		long unique=(long)bloomFilter.filter.estimateUniqueKmersFromUsedFraction(hashes, used);
		System.err.println(String.format("Bloom Occupancy:\t%.2f%%", 100*used));
		System.err.println("Unique Kmers:   \t"+unique);
		
		t2.stop();
		outstream.println(t2);
	}

	/** Create read streams and process all data */
	void fillTiles(){
		
		//Create a read input stream
		final ConcurrentReadInputStream cris;
		{
			cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2);
			cris.start(); //Start the stream
			if(verbose){outstream.println("Started cris");}
		}
		boolean paired=cris.paired();
//		if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
		
		//Process the read stream
		fillTilesInner(cris);
		
		if(verbose){outstream.println("Finished; closing streams.");}
		
		//Close the read streams
		errorState|=ReadWrite.closeStreams(cris);
	}
	
	private void loadSam(String fname) {
		if(fname==null) {return;}
		Timer t=new Timer();
		outstream.println("Loading sam file.");
		final SamReadStreamer ss;
		FileFormat ff=FileFormat.testInput(fname, FileFormat.SAM, null, true, false);
		final int streamerThreads=Tools.min(4, Shared.threads());
		
		ss=new SamReadStreamer(ff, streamerThreads, false, maxReads);
		ss.start();

		ListNum<Read> ln=ss.nextList();
		ArrayList<Read> reads=(ln==null ? null : ln.list);
		final IlluminaHeaderParser2 ihp=new IlluminaHeaderParser2();

		while(ln!=null && reads!=null && reads.size()>0){

			for(int idx=0; idx<reads.size(); idx++){
				Read r=reads.get(idx);
				assert(r.mate==null);
				processSamLine(r, ihp);
			}
			ln=ss.nextList();
			reads=(ln==null ? null : ln.list);
		}
		t.stopAndPrint();
	}
	
	private void processSamLine(Read r, IlluminaHeaderParser2 ihp) {
		if(r==null){return;}
		final SamLine sl=r.samline;
//		if(!sl.mapped() && !sl.nextMapped()) {return;} //Probably not PhiX
		if(!sl.mapped()) {return;}//TODO: Track unmapped info; requires modifying dump format
		ihp.parse(r.id);
		final MicroTile mt=flowcell.getMicroTile(ihp);
		final Lane lane=flowcell.getLane(ihp.lane());
		if(sl.mapped()) {
			mt.alignedReadCount++;
			mt.alignedBaseCount+=r.countAlignedBases();
		}
		final int pairnum=sl.pairnum();
		assert(sl.strand()==r.strand());
		
		final byte[] quals=r.quality, bases=r.bases;
		if(quals==null || bases==null || r.match==null){return;}
//		final boolean needsFixing=(varMap!=null && Read.containsVars(r.match));
		
		if(r.shortmatch()){r.toLongMatchString(false);}
		final byte[] match=r.match;

		final AtomicLongArray matchCounts=lane.matchCounts[pairnum];
		final AtomicLongArray subCounts=lane.subCounts[pairnum];
		for(int mpos=0, qpos=0; mpos<match.length; mpos++){
			byte m=match[mpos];
			if(m=='m'){
				matchCounts.incrementAndGet(qpos);
				qpos++;
			}else if(m=='S' || m=='N'){
				subCounts.incrementAndGet(qpos);
				qpos++;
			}else if(m=='X' || m=='Y' || m=='C' || m=='I'){
				qpos++;
			}else if(m=='D'){
				//Do nothing
			}else{
				assert(false) : "Unhandled symbol "+m;
			}
		}
	}

	/** Create read streams and process all data */
	void processReads(Timer t){
		
		if(ffout1!=null || ffoutbad!=null || coordsOut!=null){
			Timer t2=new Timer();
			outstream.print("Filtering reads:\t");

			//Create a read input stream
			final ConcurrentReadInputStream cris;
			{
				cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2);
				cris.start(); //Start the stream
				if(verbose){outstream.println("Started cris");}
			}
			boolean paired=cris.paired();
			//		if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}

			//Optionally read output streams
			final ConcurrentReadOutputStream ros, rosb;
			final int buff=4;
			if(ffout1!=null){
				ros=ConcurrentReadOutputStream.getStream(ffout1, ffout2, buff, null, false);
				ros.start(); //Start the stream
			}else{ros=null;}
			
			if(ffoutbad!=null){
				rosb=ConcurrentReadOutputStream.getStream(ffoutbad, null, null, null, buff, null, false);
				rosb.start(); //Start the stream
			}else{rosb=null;}
			
			final ByteStreamWriter coords=(coordsOut==null ? null : 
				ByteStreamWriter.makeBSW(coordsOut, overwrite, append, true));
			
			//Process the read stream
			processInner(cris, ros, rosb, coords);

			if(verbose){outstream.println("Finished; closing streams.");}

			//Close the read streams
			errorState|=ReadWrite.closeStreams(cris, ros, rosb);
			
			if(coords!=null) {
				errorState=coords.poisonAndWait()|errorState;
			}

			t2.stop();
			outstream.println(t2);
		}
		
		//Report timing and results
		{
			t.stop();
			lastReadsOut=readsProcessed-readsDiscarded;
			outstream.println();
			outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
			
			if(ffout1!=null || ffoutbad!=null || coordsOut!=null){

				String rpstring=Tools.padKMB(readsDiscarded, 8);
				String bpstring=Tools.padKMB(basesDiscarded, 8);
				String gpstring=Tools.padKMB(gsTransformedToN, 8);
				outstream.println();
				outstream.println("Reads Discarded:    "+rpstring+" \t"+Tools.format("%.3f%%", readsDiscarded*100.0/readsProcessed));
				outstream.println("Bases Discarded:    "+bpstring+" \t"+Tools.format("%.3f%%", basesDiscarded*100.0/basesProcessed));
				if(gToN){outstream.println("Gs Masked By N:     "+gpstring+" \t"+Tools.format("%.3f%%", gsTransformedToN*100.0/basesProcessed));}
				outstream.println();
			}
		}
		
		//Throw an exception of there was an error in a thread
		if(errorState){
			throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
		}
	}
	
	/** Iterate through the reads */
	void processInner(final ConcurrentReadInputStream cris, final ConcurrentReadOutputStream ros, 
			final ConcurrentReadOutputStream rosb, final ByteStreamWriter coords){
		
		//Do anything necessary prior to processing
		readsProcessed=0;
		basesProcessed=0;
		final IlluminaHeaderParser2 ihp=new IlluminaHeaderParser2();
		final ByteBuilder bb=new ByteBuilder();
		{
			//Grab the first ListNum of reads
			ListNum<Read> ln=cris.nextList();
			//Grab the actual read list from the ListNum
			ArrayList<Read> reads=(ln!=null ? ln.list : null);
			
			//Check to ensure pairing is as expected
			if(reads!=null && !reads.isEmpty()){
				Read r=reads.get(0);
				assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired());
			}
			
			//As long as there is a nonempty read list...
			while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
				if(verbose){outstream.println("Fetched "+reads.size()+" reads.");}

				ArrayList<Read> keepList=new ArrayList<Read>(reads.size());
				ArrayList<Read> tossList=new ArrayList<Read>(4);
				
				//Loop through each read in the list
				for(int idx=0; idx<reads.size(); idx++){
					final Read r1=reads.get(idx);
					final Read r2=r1.mate;
					
					//Track the initial length for statistics
					final int initialLength1=r1.length();
					final int initialLength2=(r1.mateLength());
					
					//Increment counters
					readsProcessed+=r1.pairCount();
					basesProcessed+=initialLength1+initialLength2;
					
					boolean keep=processReadPair(r1, r2);
					if(keep){
						keepList.add(r1);
					}else{
						tossList.add(r1);
						readsDiscarded+=r1.pairCount();
						basesDiscarded+=initialLength1+initialLength2;
					}
				}
				
				//Output reads to the output stream
				if(ros!=null){ros.add(keepList, ln.id);}
				if(rosb!=null){rosb.add(tossList, ln.id);}
				if(coords!=null) {
					bb.clear();
					for(Read r : tossList) {
						ihp.parse(r);
						ihp.appendCoordinates(bb);
						bb.nl();
					}
					if(!bb.isEmpty()) {coords.print(bb);}
				}
				
				//Notify the input stream that the list was used
				cris.returnList(ln);
				if(verbose){outstream.println("Returned a list.");}
				
				//Fetch a new list
				ln=cris.nextList();
				reads=(ln!=null ? ln.list : null);
			}
			
			//Notify the input stream that the final list was used
			if(ln!=null){
				cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
			}
		}
		
		//Do anything necessary after processing
		
	}
	
	/** Iterate through the reads */
	public void loadKmersInner(final ConcurrentReadInputStream cris){
		
		bloomFilter=new BloomFilter(k, k, cbits, hashes, 1, true, false, true, 0.7f);
		
		{
			//Grab the first ListNum of reads
			ListNum<Read> ln=cris.nextList();
			//Grab the actual read list from the ListNum
			ArrayList<Read> reads=(ln!=null ? ln.list : null);
			
			//Check to ensure pairing is as expected
			if(reads!=null && !reads.isEmpty()){
				Read r=reads.get(0);
				assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired());
			}
			
			LongList kmers=new LongList(300);
			//As long as there is a nonempty read list...
			while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
				if(verbose){outstream.println("Fetched "+reads.size()+" reads.");}

				for(int idx=0; idx<reads.size(); idx++){
					final Read r1=reads.get(idx);
					final Read r2=r1.mate;

					loadKmers(r1, kmers);
					loadKmers(r2, kmers);
				}
				
				//Notify the input stream that the list was used
				cris.returnList(ln);
				if(verbose){outstream.println("Returned a list.");}
				
				//Fetch a new list
				ln=cris.nextList();
				reads=(ln!=null ? ln.list : null);
			}
			
			//Notify the input stream that the final list was used
			if(ln!=null){
				cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
			}
		}
	}
	
	private void loadKmers(Read r, LongList kmers) {
		if(r==null || r.length()<k) {return;}
//		if(!randy.nextBoolean()) {return;}//Speed optimization, I guess
		if(kmersPerRead<1) {
			kmers.clear();
			BloomFilter.toKmers(r, kmers, k, 0, 0, true);
			for(int i=0; i<kmers.size; i++) {
				long kmer=kmers.array[i];
				bloomFilter.filter.increment(kmer);
			}
		}else {
			for(int i=0; i<kmersPerRead; i++) {
				final int pos=deterministic ? (int)((r.numericID+i*k)%(r.length()-k2)) : 
					randy.nextInt(r.length()-k2);
				final long kmer=toKmer(r.bases, pos, k);
				if(kmer>=0){
					final long key=toKey(kmer);
					bloomFilter.filter.increment(key);
				}
			}
		}
	}
	
	/** Iterate through the reads */
	public void fillTilesInner(final ConcurrentReadInputStream cris){
		Timer t2=new Timer();
		outstream.print("Filling tiles:  \t");
		
		fillThreads=Tools.min(fillThreads, Shared.threads());
		if(fillThreads>1){
			spawnThreads(cris);
		}else{
			//Grab the first ListNum of reads
			ListNum<Read> ln=cris.nextList();
			//Grab the actual read list from the ListNum
			ArrayList<Read> reads=(ln!=null ? ln.list : null);
			
			//Check to ensure pairing is as expected
			if(reads!=null && !reads.isEmpty()){
				Read r=reads.get(0);
				assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired());
			}
			
			//As long as there is a nonempty read list...
			while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
				if(verbose){outstream.println("Fetched "+reads.size()+" reads.");}
				
				//Loop through each read in the list
				for(int idx=0; idx<reads.size(); idx++){
					final Read r1=reads.get(idx);
					final Read r2=r1.mate;
					
					//Track the initial length for statistics
					final int initialLength1=r1.length();
					final int initialLength2=(r1.mateLength());
					
					//Increment counters
					readsProcessed+=r1.pairCount();
					basesProcessed+=initialLength1+initialLength2;
					
					final MicroTile mt=flowcell.getMicroTile(r1.id);
					
					if(loadKmers){
						processTileKmers(r1, mt, samples);
						processTileKmers(r2, mt, samples);
					}
					
					mt.add(r1);
					mt.add(r2);
				}
				
				//Notify the input stream that the list was used
				cris.returnList(ln);
				if(verbose){outstream.println("Returned a list.");}
				
				//Fetch a new list
				ln=cris.nextList();
				reads=(ln!=null ? ln.list : null);
			}
			
			//Notify the input stream that the final list was used
			if(ln!=null){
				cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
			}
		}
		
		t2.stop();
		outstream.println(t2);
	}
	
	void processTileKmers(Read r, MicroTile mt, int samples) {
		if(r==null || r.length()<k) {return;}
		if(samples<1 || samples>=r.length()-k2) {processTileKmersFull(r, mt);}
		else{processTileKmersSampled(r, mt, samples);} 
	}
	
	//Samples all kmers
	private void processTileKmersFull(Read r, MicroTile mt) {
		final int cutoff=(kmersPerRead<1 ? 2 : 1);
		final byte[] bases=r.bases;
		final int shift=2*k;
		final int shift2=shift-2;
		final long mask=(-1L)>>>(64-shift);

		long kmer=0, rkmer=0;
		long depthSum=0;
		int kmers=0;

		final LongList depthSums=MicroTile.trackDepth ? (mt.depthSums[r.pairnum()]) : null;
		final LongList depthCounts=MicroTile.trackDepth ? (mt.depthCounts[r.pairnum()]) : null;
		
		//TODO: Debranch using 2 loops; one for 1st k-1 bases, and one for the rest.
		for(int i=0, len=0; i<bases.length; i++) {
			final byte b=bases[i];
			final long x=AminoAcid.baseToNumber[b];
			final long x2=AminoAcid.baseToComplementNumber[b];
			kmer=((kmer<<2)|x)&mask;
			rkmer=x<0 ? 0 : ((rkmer>>>2)|(x2<<shift2))&mask;
			
			len=(x<0 ? 0 : len+1);
			rkmer=(x<0 ? 0 : rkmer);//is this necessary? TODO: Check.
//			if(x<0){len=0; rkmer=0;}else{len++;}//old branchy version
			if(i>=k) {
				final long key=toKey(kmer, rkmer);
				final int value=(len>=k ? bloomFilter.getCount(key) : 0);
				depthSum+=value;
				final int hit=(value>=cutoff ? 1 : 0);
				mt.hits+=hit;
				mt.misses+=(hit^1);//This is clever.  No conditionals!
				kmers++;
//				System.err.println("Got "+value+" for kmer "+key);
				
				if(MicroTile.trackDepth) {
					depthSums.increment(i-k, value);
					depthCounts.increment(i-k);
				}
			}
		}
		mt.depthSum+=depthSum;
	}
	
	//Samples all kmers
	private void processTileKmersFull(Read r, LongList depths) {
//		final int cutoff=(kmersPerRead<1 ? 2 : 1);
		final byte[] bases=r.bases;
		final int shift=2*k;
		final int shift2=shift-2;
		final long mask=(-1L)>>>(64-shift);

		long kmer=0, rkmer=0;
		
		depths.clear();
		
		//TODO: Debranch using 2 loops; one for 1st k-1 bases, and one for the rest.
		for(int i=0, len=0; i<bases.length; i++) {
			final byte b=bases[i];
			final long x=AminoAcid.baseToNumber[b];
			final long x2=AminoAcid.baseToComplementNumber[b];
			kmer=((kmer<<2)|x)&mask;
			rkmer=x<0 ? 0 : ((rkmer>>>2)|(x2<<shift2))&mask;
			
			len=(x<0 ? 0 : len+1);
			rkmer=(x<0 ? 0 : rkmer);//is this necessary? TODO: Check.
//			if(x<0){len=0; rkmer=0;}else{len++;}//old branchy version
			if(i>=k) {
				final long key=toKey(kmer, rkmer);
				final int value=(len>=k ? bloomFilter.getCount(key) : 0);
				depths.add(value);
			}
		}
	}
	
	//Samples multiple kmers
	private void processTileKmersSampled(Read r, MicroTile mt, int samples) {
		if(r.length()<=3*k+1) {samples=1;}
		samples=Tools.min(samples, r.length()-k2);
		final int cutoff=(kmersPerRead<1 ? 2 : 1);
		
		long depthSum=0;
		for(int i=0; i<samples; i++) {
			int value=getKmerCount(r.bases, getPos(r.numericID+74+k3*i, r.length()));
			depthSum+=value;
			if(value>=cutoff) {mt.hits++;}
			else {mt.misses++;}
		}
		mt.depthSum+=depthSum;
	}
	
	private int getKmerCount(byte[] bases, int pos) {
		final int lim=bases.length-k2;
		pos=pos%(bases.length-k2);
		assert(pos>=0 && pos<=lim);
		final long kmer=toKmer(bases, pos, k);
		if(kmer<0) {return 0;}
		final long key=toKey(kmer);
		final int value=bloomFilter.getCount(key);
//		if(maxReads==1) {System.err.println("Got "+value+" for kmer "+key);}
		return value;
	}
	
	private int getPos(long id, int len) {
		return (deterministic ? (int)((id)%(len-k2)) : randy.nextInt(len-k2));
	}
	
	private final long toKey(long kmer) {
		return Tools.max(kmer, AminoAcid.reverseComplementBinaryFast(kmer, k));
//		return (kmersPerRead==1 || kmer==-1 ? kmer : 
//			Tools.max(kmer, AminoAcid.reverseComplementBinaryFast(kmer, k)));
	}
	
	private final long toKey(long kmer, long rkmer) {
		return Tools.max(kmer, rkmer);
	}
	
	/*--------------------------------------------------------------*/
	/*----------------         Inner Methods        ----------------*/
	/*--------------------------------------------------------------*/
	
	boolean processReadPair(final Read r1, final Read r2){
		boolean passes=processReadPair_inner(r1, r2);
		if(passes){return true;}
		if(trimq>0){
			TrimRead.trimFast(r1, trimLeft, trimRight, trimq, trimE, 0);
			if(r2!=null){TrimRead.trimFast(r2, trimLeft, trimRight, trimq, trimE, 0);}
			return r1.length()>=minlen && (r2==null || r2.length()>=minlen);
		}else{
			return false;
		}
	}
	
	/**
	 * Process a single read pair.
	 * @param r1 Read 1
	 * @param r2 Read 2 (may be null)
	 * @return True if the reads should be kept, false if they should be discarded.
	 */
	boolean processReadPair_inner(final Read r1, final Read r2){
		
		MicroTile mt=flowcell.getMicroTile(r1.id);
		if(mt==null){
			if(!warned){
				outstream.println("\nWarning - a read was found with no corresponding MicroTile:\n"+r1.id);
				warned=true;
			}
			return true;
		}
		if(mt.discard<discardLevel){return true;}
		if(!discardOnlyLowQuality){return false;}
		
		if(shouldDiscard(r1, mt)) {return false;}
		if(gToN){gsTransformedToN+=doGToN(r1, mt);}
		
		if(shouldDiscard(r2, mt)) {return false;}
		if(gToN){gsTransformedToN+=doGToN(r2, mt);}
		
		return true;
	}
	
	private boolean shouldDiscard(Read r, MicroTile mt) {
		if(r==null || r.length()<1) {return false;}
		final int len=r.length();
		double qual=r.avgQualityByProbabilityDouble(true, len);
		double prob=100*r.probabilityErrorFree(true, len);
		if(qual<=flowcell.avgQuality-(dmult*qDeviations*flowcell.stdQuality)){return true;}
		if(prob<=flowcell.avgErrorFree-(dmult*eDeviations*flowcell.stdErrorFree)){return true;}
		if(PolyFilter.polymerLen(r.bases, (byte)'G', 0.16f)>15) {return true;}
		if(discardG && shouldDiscardG(r, mt)){return true;}
		return false;
	}
	
	private boolean shouldDiscardG(Read r, MicroTile mt){
		final byte[] bases=r.bases;
		final float[] gArray=mt.tracker.cycleAverages[2];
		
		final float thresh=(float)(flowcell.avgG+Tools.max(gDeviations*flowcell.stdG, 
				flowcell.avgG*gFraction, gAbs));
		for(int i=0; i<bases.length; i++){
			byte b=bases[i];
			if(b=='G' && gArray[i]>thresh){
				return true;
			}
		}
		return false;
	}
	
	private int doGToN(Read r, MicroTile mt){
		if(r==null || r.length()<1) {return 0;}
		final byte[] bases=r.bases;
		final byte[] quals=r.quality;
		final float[] gArray=mt.tracker.cycleAverages[2];
		
		final float thresh=(float)(flowcell.avgG+Tools.max(gDeviations*flowcell.stdG, 
				flowcell.avgG*gFraction, gAbs));
		int changes=0;
		for(int i=0; i<bases.length; i++){
			byte b=bases[i];
			if(b=='G' && gArray[i]>thresh){
				bases[i]='N';
				changes++;
				if(quals!=null){quals[i]=0;}
			}
		}
		return changes;
	}
		
	/*--------------------------------------------------------------*/
	/*----------------        Helper Methods        ----------------*/
	/*--------------------------------------------------------------*/
	
	/**
	 * Generate a kmer from specified start location
	 * @param bases
	 * @param start
	 * @param klen kmer length
	 * @return kmer
	 */
	private static final long toKmer(final byte[] bases, final int start, final int klen){
		final int stop=start+klen;
		assert(stop<=bases.length) : klen+", "+bases.length;
		long kmer=0;
		
		for(int i=start; i<stop; i++){
			final byte b=bases[i];
			final long x=Dedupe.baseToNumber[b];
			kmer=((kmer<<2)|x);
		}
		return kmer;
	}
	
	private final long markTiles(ArrayList<MicroTile> mtList, double avgReads){
		for(MicroTile mt : mtList){
			mt.discard=0;
		}
		long readsToDiscard=0;
		
		cDiscards=qDiscards=eDiscards=uDiscards=mtDiscards=gDiscards=mtRetained=0;
		
		for(MicroTile mt : mtList){
			double q=mt.averageReadQualityByProb();
			double e=mt.percentErrorFree();
			double u=mt.uniquePercent();
			double pg=mt.polyGPercent();
			double g=mt.maxG();

			double dq=flowcell.avgQuality-q;
			double de=flowcell.avgErrorFree-e;
			double du=u-flowcell.avgUnique;
			double dpg=pg-flowcell.avgPolyG;
			double dg=g-flowcell.avgG;
			
			if(mt.readCount<10 && mt.readCount<0.02f*avgReads){
				mt.discard++;
				cDiscards++;
			}
			
			if(dq>qDeviations*flowcell.stdQuality && dq>flowcell.avgQuality*qualFraction && dq>qualAbs){
				mt.discard++;
				qDiscards++;
			}
			if(de>eDeviations*flowcell.stdErrorFree && 
					de>flowcell.avgErrorFree*errorFreeFraction && de>errorFreeAbs){
				mt.discard++;
				eDiscards++;
			}
			if(dpg>pgDeviations*flowcell.stdPolyG && 
					dpg>flowcell.avgPolyG*polyGFraction && dpg>polyGAbs){
				mt.discard++;
				gDiscards++;
//				assert(dpg<0) : "pg="+pg+", dpg="+dpg+", devs="+pgDeviations+", std="+flowcell.stdPolyG+"\n"
//				+ "avg="+flowcell.avgPolyG+", frac="+polyGFraction+", abs="+polyGAbs+
//				", t1="+ (pgDeviations*flowcell.stdPolyG)+", t2="+(flowcell.avgPolyG*polyGFraction);
			}
			if(flowcell.avgUnique>2 && flowcell.avgUnique<98){
				if(du>uDeviations*flowcell.stdUnique && du>flowcell.avgUnique*uniqueFraction && du>uniqueAbs){
					mt.discard++;
					uDiscards++;
				}
			}
			
			//Or mode
//			if(dq>qDeviations*stdQuality || dq>avgQuality*qualFraction || dq>qualAbs){
//				mt.discard++;
//				qDiscards++;
//			}
//			if(de>eDeviations*stdErrorFree || de>avgErrorFree*errorFreeFraction || de>errorFreeAbs){
//				mt.discard++;
//				eDiscards++;
//			}
//			if(avgUnique>2 && avgUnique<98){
//				if(du>uDeviations*stdUnique || du>avgUnique*uniqueFraction || du>uniqueAbs){
//					mt.discard++;
//					uDiscards++;
//				}
//			}
			
			if((discardG || gToN) && (dg>gDeviations*flowcell.stdG && dg>flowcell.avgG*gFraction && dg>gAbs)){
				mt.discard++;
				gDiscards++;
			}
			if(mt.discard>0){
				mtDiscards++;
				readsToDiscard+=mt.readCount;
			}
			else{mtRetained++;}
		}
		
		outstream.println();
		outstream.println("Flagged "+mtDiscards+" of "+(mtDiscards+mtRetained)+" micro-tiles, containing "+readsToDiscard+" reads:");
		outstream.println(uDiscards+" exceeded uniqueness thresholds.");
		outstream.println(qDiscards+" exceeded quality thresholds.");
		outstream.println(eDiscards+" exceeded error-free probability thresholds.");
		outstream.println(gDiscards+" contained G spikes.");
		outstream.println(cDiscards+" had too few reads to calculate statistics.");
		outstream.println();
		
		return readsToDiscard;
	}
	
	/*--------------------------------------------------------------*/
	/*----------------       Thread Management      ----------------*/
	/*--------------------------------------------------------------*/
	
	/** Spawn process threads */
	private void spawnThreads(final ConcurrentReadInputStream cris){
		
		//Do anything necessary prior to processing
		
		//Determine how many threads may be used
		final int threads=Tools.min(fillThreads, Shared.threads());
		
		//Fill a list with ProcessThreads
		ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
		for(int i=0; i<threads; i++){
			alpt.add(new ProcessThread(cris, i));
		}
		
		//Start the threads and wait for them to finish
		boolean success=ThreadWaiter.startAndWait(alpt, this);
		errorState&=!success;
		
		//Do anything necessary after processing
		
	}
	
	@Override
	public final void accumulate(ProcessThread pt){
		synchronized(pt) {
			readsProcessed+=pt.readsProcessedT;
			basesProcessed+=pt.basesProcessedT;
			errorState|=(!pt.success);
		}
	}
	
	@Override
	public final boolean success(){return !errorState;}	
	@Override
	public final ReadWriteLock rwlock() {return rwlock;}
	private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
	
	class ProcessThread extends Thread {
		
		//Constructor
		ProcessThread(final ConcurrentReadInputStream cris_, final int tid_){
			cris=cris_;
			tid=tid_;
		}
		
		//Called by start()
		@Override
		public void run(){
			//Do anything necessary prior to processing
			
			//Process the reads
			processInner();
			
			//Do anything necessary after processing
			
			//Indicate successful exit status
			success=true;
		}
		
		/** Iterate through the reads */
		void processInner(){
			dummy.clear();
			
			//Grab the first ListNum of reads
			ListNum<Read> ln=cris.nextList();

			//Check to ensure pairing is as expected
			if(ln!=null && !ln.isEmpty()){
				Read r=ln.get(0);
//				assert(ffin1.samOrBam() || (r.mate!=null)==cris.paired()); //Disabled due to non-static access
			}

			//As long as there is a nonempty read list...
			while(ln!=null && ln.size()>0){
//				if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
				
				processList(ln);
				
				//Notify the input stream that the list was used
				cris.returnList(ln);
//				if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
				
				//Fetch a new list
				ln=cris.nextList();
			}

			//Notify the input stream that the final list was used
			if(ln!=null){
				cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
			}
			if(currentTile!=null) {
				synchronized(currentTile) {currentTile.add(dummy);}
			}
		}
		
		void processList(ListNum<Read> ln){

			//Grab the actual read list from the ListNum
			final ArrayList<Read> reads=ln.list;
			
			//Loop through each read in the list
			for(int idx=0; idx<reads.size(); idx++){
				final Read r1=reads.get(idx);
				final Read r2=r1.mate;
				
				//Validate reads in worker threads
				if(!r1.validated()){r1.validate(true);}
				if(r2!=null && !r2.validated()){r2.validate(true);}

				//Track the initial length for statistics
				final int initialLength1=r1.length();
				final int initialLength2=r1.mateLength();

				//Increment counters
				readsProcessedT+=r1.pairCount();
				basesProcessedT+=initialLength1+initialLength2;
				
				processReadPair(r1, r2);
			}
		}
		
		/**
		 * Process a read or a read pair.
		 * @param r1 Read 1
		 * @param r2 Read 2 (may be null)
		 */
		void processReadPair(final Read r1, final Read r2){
			//Increment counters
			readsProcessedT+=r1.pairCount();
			basesProcessedT+=r1.pairLength();
			
			MicroTile mt=null;
			ihp.parse(r1.id);
			synchronized(flowcell) {
				mt=flowcell.getMicroTile(ihp);
			}
			synchronized(mt) {
				if(loadKmers){
					processTileKmers(r1, mt, samples);
					processTileKmers(r2, mt, samples);
				}
				
				mt.add(r1);
				mt.add(r2);
			}
		}
		
		//Seemed like it would be faster, but not really.
//		void processReadPair(final Read r1, final Read r2){
//			//Increment counters
//			readsProcessedT+=r1.pairCount();
//			basesProcessedT+=r1.pairLength();
//			
//			MicroTile mt=null;
//			ihp.parse(r1.id);
//			synchronized(flowcell) {
//				mt=flowcell.getMicroTile(ihp);
//			}
//			if(mt!=currentTile && currentTile!=null) {
//				synchronized(currentTile) {currentTile.add(dummy);}
//				dummy.clear();
//			}
//			currentTile=mt;
//			if(loadKmers){
//				processTileKmers(r1, dummy, samples);
//				processTileKmers(r2, dummy, samples);
//			}
//
//			dummy.add(r1);
//			dummy.add(r2);
//		}

		/** Number of reads processed by this thread */
		protected long readsProcessedT=0;
		/** Number of bases processed by this thread */
		protected long basesProcessedT=0;
		
		private final MicroTile dummy=new MicroTile();
		private MicroTile currentTile=null;
		private IlluminaHeaderParser2 ihp=new IlluminaHeaderParser2();
		
		/** True only if this thread has completed successfully */
		boolean success=false;
		
		/** Shared input stream */
		private final ConcurrentReadInputStream cris;
		/** Thread ID */
		final int tid;
	}
	
	/*--------------------------------------------------------------*/
	/*----------------            Fields            ----------------*/
	/*--------------------------------------------------------------*/

	/** Primary input file path */
	private String in1=null;
	/** Secondary input file path */
	private String in2=null;
	
	private ArrayList<String> extra=new ArrayList<String>();

	/** Primary output file path */
	private String out1=null;
	/** Secondary output file path */
	private String out2=null;

	/** Discard output file path */
	private String outbad=null;

	/** Optional aligned reads (e.g. PhiX) */
	private String samInput=null;
	
	/** Override input file extension */
	private String extin=null;
	/** Override output file extension */
	private String extout=null;
	
	private boolean pound=true;
	private String dumpOut=null;
	private String dumpIn=null;
	private String coordsOut=null;
	
	private String bloomOut=null;
	private String bloomIn=null;
	
	/*--------------------------------------------------------------*/

	/** Number of reads processed */
	public long readsProcessed=0;
	/** Number of bases processed */
	public long basesProcessed=0;

	/** Number of reads discarded */
	public long readsDiscarded=0;
	/** Number of bases discarded */
	public long basesDiscarded=0;

	protected long cDiscards=0;
	protected long uDiscards=0;
	protected long qDiscards=0;
	protected long eDiscards=0;
	protected long gDiscards=0;
	protected long mtDiscards=0;
	protected long mtRetained=0;
	
	protected long gsTransformedToN=0; 
	
	/** Quit after processing this many input reads; -1 means no limit */
	private long maxReads=-1;
	
	/** Whether interleaved was explicitly set. */
	private boolean setInterleaved=false;
	
	private int fillThreads=32;
	private int loadThreads=4;
	private BloomFilter bloomFilter;
	
	private boolean loadKmers=true;
	private int kmersPerRead=4;//for loading
	private int samples=4; //for reading
	private float minProb=0;
	private boolean deterministic=true;
	private int cbits=2;
	private int hashes=2;
	
	private int targetAverageReads=800;
	
	private static final int k=31;
	//K2 is the constant k-1
	private static final int k2=30;
	//K3!=K and K3 is prime modulo read length
	private static final int k3=29;
	private long seed=-1;
	
	private final Random randy=Shared.threadLocalRandom(seed);
	private FlowCell flowcell;
	
	private long minCountToUse=0;

	private float dmult=-0.2f;
	
	private float qDeviations=2.0f;
	private float uDeviations=1.5f;
	private float eDeviations=2.2f;
	private float pgDeviations=2.0f;
	private float gDeviations=2.0f;
	
	private float qualFraction=0.01f;
	private float uniqueFraction=0.01f;
	private float errorFreeFraction=0.01f;
	private float polyGFraction=0.3f;
	private float gFraction=0.1f;
	
	private float qualAbs=1f;
	private float uniqueAbs=1f;
	private float errorFreeAbs=1f;
	private float polyGAbs=0.6f;
	private float gAbs=0.05f;

	private boolean discardOnlyLowQuality=true;
	private int discardLevel=1;
	private boolean gToN=false;
	private boolean discardG=false;
	
	private int minlen=30;
	private float trimq=-1;
	private final float trimE;
	private boolean trimLeft=false;
	private boolean trimRight=true;
	
	private boolean warned=false;
	
	/*--------------------------------------------------------------*/
	/*----------------         Final Fields         ----------------*/
	/*--------------------------------------------------------------*/

	/** Primary input file */
	private final FileFormat ffin1;
	/** Secondary input file */
	private final FileFormat ffin2;
	
	/** Primary output file */
	private final FileFormat ffout1;
	/** Secondary output file */
	private final FileFormat ffout2;
	
	/** Output for discarded reads */
	private final FileFormat ffoutbad;
	
	/*--------------------------------------------------------------*/
	/*----------------        Common Fields         ----------------*/
	/*--------------------------------------------------------------*/
	
	/** Number of reads output in the last run */
	public static long lastReadsOut;
	/** Print status messages to this output stream */
	private PrintStream outstream=System.err;
	/** Print verbose messages */
	public static boolean verbose=false;
	/** True if an error was encountered */
	public boolean errorState=false;
	/** Overwrite existing output files */
	private boolean overwrite=true;
	/** Append to existing output files */
	private boolean append=false;
	/** This flag has no effect on singlethreaded programs */
	private final boolean ordered=false;
	
}
