#!/usr/bin/env python3
__author__ = 'LieuV'
__version__ = "1.0.14"

from classes import *
from helper import *
import os
from itertools import groupby
from jinja2 import Environment,FileSystemLoader
import shutil
import configparser
from collections import OrderedDict
import json

#dependencies
try:
	import argparse
except ImportError:
	print('The "argparse" module is not available. Use Python >3.2.')
	sys.exit(1)

#parameter = configparser.ConfigParser(strict=False, interpolation=None)
#parameter.read(join(dirname(__file__), "parameter.txt"))

#r1_pattern = parameter["Pattern"]["R1"]
#r2_pattern = parameter["Pattern"]["R2"]
#sep_pattern = parameter["Pattern"]["sep"]
#lane_pattern = parameter["Pattern"]["lane"]
global parameter
global r1_pattern
global r2_pattern
global sep_pattern
global lane_pattern

def get_illumina_reads(tmp):
	readsets = []
	if not all([re.search(lane_pattern, x) for x in arguments["r1"]]):
		readname = re.sub(r1_pattern + ".*", "", os.path.basename(arguments["r1"][0]))
		if len(arguments["r1"]) != 1:
			r1 = FastQFile(join_reads(arguments["r1"], tmp, readname + "R1"),
						   [toLatex(os.path.basename(x)) for x in arguments["r1"]])
		else:
			r1 = FastQFile(arguments["r1"][0])
		if arguments["r2"]:
			if len(arguments["r2"]) != 1:
				r2 = FastQFile(join_reads(arguments["r2"], tmp, readname + "R2"),
							   [toLatex(os.path.basename(x)) for x in arguments["r2"]])
			else:
				r2 = FastQFile(arguments["r2"][0])
			readsets.append(ReadSet(r1, r2))
		else:
			readsets.append(ReadSet(r1))

	else:
		# split by lanes
		for lane in sorted(set([re.search(lane_pattern, x).group() for x in arguments["r1"]])):
			# concat same lanes
			r1_reads = [x for x in arguments["r1"] if lane in x]
			readname = re.sub(r1_pattern + ".*", "", os.path.basename(r1_reads[0]))
			if len(arguments["r1"]) != 1:
				r1 = FastQFile(join_reads(r1_reads, tmp, readname + "R1"), [toLatex(os.path.basename(x)) for x in r1_reads]  )
			else:
				r1 = FastQFile(r1_reads[0])
			if arguments["r2"]:
				r2_reads = [x for x in arguments["r2"] if lane in x]

				if len(r2_reads) != 1:
					r2 = FastQFile(join_reads(r2_reads, tmp, readname + "R2"),[toLatex(os.path.basename(x)) for x in r2_reads] )
				else:
					r2 = FastQFile(r2_reads[0])
				readsets.append(ReadSet(r1,r2))
			else:
				readsets.append(ReadSet(r1))
	return readsets

def get_input():
	all_files = []
	bam_ext = [x.strip(" ") for x in parameter["Fileextension"]["bam"].split(",")]
	fastq_ext = [x.strip(" ") for x in parameter["Fileextension"]["fastq"].split(",")]

	if arguments["technology"]:
		if arguments["technology"]=="IonTorrent":
			fastq_ext = []
		else:
			bam_ext = []

	if arguments["r1"]:
		if not arguments["technology"]:
			if any([arguments["r1"].endswith(ext) for ext in bam_ext]):
				arguments["technology"] = "IonTorrent"
			else:
				arguments["technology"] = "Illumina"
		if arguments["r2"]:
			return [[[arguments["r1"]], [arguments["r2"]]]]
		else:
			return [[[arguments["r1"]]]]


	for root, dirs, files in os.walk(arguments["input"]):
		for file in files:
			if any([file.endswith(ext) for ext in fastq_ext + bam_ext ]):
				all_files.append(join(root,file))

	if not arguments["technology"]:
		if len([x for x in all_files if any([ext in x for ext in bam_ext])]) == len(all_files):
			arguments["technology"] = "IonTorrent"
		else:
			arguments["technology"] = "Illumina"
	#if arguments["technology"]:
	#	if arguments["technology"]=="Illumina":
	#		# fastq only
	#		all_files = [x for x in all_files if any([ext in x for ext in fastq_ext])]
	#	elif arguments["technology"]=="IonTorrent":
	#		# bam only
	#		all_files = [x for x in all_files if any([ext in x for ext in bam_ext])]

	if (len(all_files) == 0):
		sys.exit(arguments["input"] + " does not contain fastq or bam files.")

	# find read pairs
	all_files = sorted(list(all_files))
	paired_reads_pattern =sep_pattern.join([lane_pattern , "(" + r1_pattern + "|" + r2_pattern + ")","\d{3}"])
	if all([re.search(paired_reads_pattern, x) for x in all_files]):
		paired_reads = []
		for setname, files in groupby(all_files, key=lambda x: "_".join(x.split("_")[:-3])):
			temp = sorted(list(files))
			r1_reads = [x for x in temp if r1_pattern in x]
			r2_reads = [x for x in temp if r2_pattern in x]
			if len(r1_reads) != 0:
				if len(r2_reads) != 0:
					paired_reads.append([r1_reads, r2_reads])
				else:
					paired_reads.append([r1_reads])
		return paired_reads
	else: # treat each file as sample
		return [[[x]] for x in all_files ]


def getSetname():
	try:
		if arguments["rename"]:
			new_name = [arguments["rename"][x] for x in arguments["rename"].keys() if basename(arguments["r1"][0]).startswith(x)]

			if len(new_name)>1:
				print("Name mapping ambiguous. Found: ", new_name)
				return getFilenameWithoutExtension(arguments["r1"][0], True)
			elif len(new_name)==0:
				return getFilenameWithoutExtension(arguments["r1"][0], True)
			else:
				print("Renamed to " ,new_name)
				return new_name[0]
	except:
		print("Couldnt rename sample files.")
	try:
		paired_reads_pattern = sep_pattern.join([sep_pattern + lane_pattern, "(" + r1_pattern + "|" + r2_pattern + ")", "\d{3}.*"])
		if isinstance(arguments["r1"], list):
			return re.sub(paired_reads_pattern, "" ,basename(arguments["r1"][0]))
		else:
			return re.sub(paired_reads_pattern,"",basename(arguments["r1"]))
	except:
		print("Problems getting samplenames")
		return arguments["r1"]

def runAnalyses(temp_bowtie_path, tmp):
	try:
		output = getDir([arguments["output"], "QCResults"], True)
		sample = Sample(getSetname(), output, arguments["reference"],arguments["threads"], arguments["technology"])

		if arguments["technology"].startswith("Illumina"):
			readsets = get_illumina_reads(tmp)
		elif arguments["technology"] == "IonTorrent":
			print("IonTorrent", arguments["r1"])
			fastqfile = bam_to_fastq(arguments["r1"],tmp)
			readsets = [ReadSet( fastqfile)]

		for rs in readsets:
			print("Run FastQC...")
			rs.run_FastQC(join(output, "FastQC"))
			if not arguments["notrimming"]:
				if arguments["trimBetter"]:
					trimming_perc = arguments["trimBetter_threshold"]
				else:
					trimming_perc = ""
				rs.run_Trimmomatic(arguments["adapter"], arguments["palindrome"], arguments["minlen"],
										arguments["trimOption"], trimming_perc, arguments["gz"])
				rs.trimRes = rs.trimRes.run_FastQC(tmp)
			sample = sample.add_readSet(rs)
		if not arguments["nomapping"]:
			if arguments["save_mapping"]:
				sample.mappingRes = sample.run_Bowtie2(temp_bowtie_path, join(arguments["output"], "QCResults", sample.name +".sam"), not arguments["notrimming"])
			else:
				sample.mappingRes = sample.run_Bowtie2(temp_bowtie_path, "/dev/null", not arguments["notrimming"])
		if not arguments["nokraken"]:
			print("Run Kraken.")
			sample = sample.run_Kraken(arguments["db"], not arguments["notrimming"])

		sample.stop = datetime.datetime.strftime(datetime.datetime.now(),"%d.%m.%Y, %H:%M:%S")
	finally:
		shutil.rmtree(tmp)
	return sample

def writeReport(sample):
	report_name = os.path.join(sample.mainResultsPath, "Report",
		 "summary_" + sample.name + "_" + datetime.datetime.strftime(datetime.datetime.now(), "%d-%m-%y_%H-%M"))
	print("Writing latex " ,report_name)
	env = Environment()
	env.loader = FileSystemLoader(os.path.dirname(__file__))

	template = env.get_template("report.tex")
	try:
		trim_param= sample.readSets[0].trimRes.print_param(arguments["palindrome"], arguments["minlen"], arguments["trimOption"])
	except:
		trim_param = "None"
	pdf_latex = template.render(sample=sample, pipeline=Pipeline(), trim_param = trim_param )

	latex = open(report_name + ".tex", "w")
	latex.write(pdf_latex)
	latex.close()

	process = subprocess.Popen(" ".join(["pdflatex", "-interaction=nonstopmode", "-output-directory=" + join(sample.mainResultsPath, "Report"), report_name + ".tex"]),shell=True, stdout = subprocess.DEVNULL, stderr = subprocess.PIPE)
	for line in iter(process.stderr.readline, b''):
		print(line)
	process.communicate()
	#os.system(" ".join(["pdflatex", "-interaction=nonstopmode", "-output-directory=" + join(sample.mainResultsPath, "Report"), report_name + ".tex > " + join(sample.mainResultsPath, "Report", "latex.log 2&")]))

	for ext in (".tex",".aux", ".log", ".toc", ".lof", ".lot", ".synctex.gz"):
		try:
			os.remove(report_name + ext)
		except OSError:
			pass
def check_input_validity():
	#
	# Check options for Trimmomatic
	#pattern = re.match("(?P<option>\w+):(?P<value1>\d+):(?P<value2>\d+)", arguments["trimOption"])
	#if (arguments["trimOption"] != ""):
	#	if not ((pattern.group("option") == "SLIDINGWINDOW") or (pattern.group("option") == "MAXINFO")):
	#		sys.exit("Check trimOption. Only 'SLIDINGWINDOW' or 'MAXINFO' allowed")
	#	try:
	#		int(pattern.group("value1"))
	#		int(pattern.group("value2"))
	#	except:
	#		sys.exit("Check trimOptions.")

	#
	# Check if adapter is required
	if  not (arguments['notrimming'] or arguments['adapter'] or arguments["technology"] == "IonTorrent") :
		sys.exit("Illumina projects requires an adapter file")

	#
	# Check if reference is required and valid
	if arguments["nomapping"]:
		arguments["reference"] = ""
	else:
		if not arguments["reference"]:
			sys.exit("Mapping needs a reference.")
		else:
			if not os.path.exists(arguments["reference"]):
				sys.exit("Reference does not exist.")
			try:
				from Bio import SeqIO
				seq_record = SeqIO.parse(arguments["reference"], "fasta")
			except:
				print("Couldnt check if reference input is a valid fasta due to missing python library Bio.")
			try:
				for seq in seq_record:
					break  # break after first sequence
			except FileNotFoundError as err:
				sys.exit("File %s does not exist" % arguments["reference"])
			try:
				str(seq)  # we somehow need to touch the sequence element to trigger an error or not
			except:
				sys.exit('File %s does not contain valid fasta data' % arguments["reference"])

	#
	#Check validity of Kraken DB
	if not arguments["nokraken"]:
		if not os.path.exists(arguments["db"]):
			sys.exit(arguments["db"] + " does not exist. Enter a valid database for kraken")
		else:
			if "database.kdb" not in os.listdir(arguments["db"]):
				sys.exit("database " + arguments["db"] + " does not contain necessary file database.kdb")
	#
	# Check input
	if arguments["input"]:
		if not os.path.exists(arguments["input"]):
			sys.exit(arguments["input"] + " does not exist.")
	else:
		if not os.path.isfile(arguments["r1"]):
			sys.exit(arguments["r1"] + " does not exist. Input file required. Use option -input or -1 / -2.")

		if arguments["r2"]:
			if not os.path.isfile(arguments["r2"]):
				sys.exit(arguments["r2"] + " does not exist.")

def get_defaults():
	if arguments["forAssembly"]:
		if not arguments["trimBetter_threshold"]:
			arguments["trimBetter_threshold"] = parameter["forAssembly." + arguments['technology']][
				"trimBetter_threshold"]
		if not arguments["trimOption"]:
			arguments["trimOption"] = parameter["forAssembly." + arguments['technology']]["trimOption"]

	elif arguments["forMapping"]:
		if not arguments["trimBetter_threshold"]:
			arguments["trimBetter_threshold"] = parameter["forMapping." + arguments['technology']][
				"trimBetter_threshold"]
		if not arguments["trimOption"]:
			arguments["trimOption"] = parameter["forMapping." + arguments['technology']]["trimOption"]

	if not arguments["trimOption"]:
		arguments["trimOption"] = parameter["Trimmomatic"]["trimOption"]
	if not arguments["trimBetter_threshold"]:
		arguments["trimBetter_threshold"] = parameter["Trimmomatic"]["trimBetter_threshold"]


def plot():
	try:
		#
		# Plot BOXPLOTS
		boxplots = [{"file": "Per_sequence_quality_scores.csv",
					 "output": join(arguments["output"], "QCResults/Report/src/img", "Per_sequence_quality_scores.png"),
					 "title": "Per sequence quality scores",
					 "ylab": "Mean Sequence Quality (Phred Score)",
					 "xlab": "Sample"},
					{"file": "Sequence_Length_Distribution.csv",
					 "output": join(arguments["output"], "QCResults/Report/src/img", "Sequence_Length_Distribution.png"),
					 "title": "Sequence Length Distribution",
					 "ylab": "Sequence Length (bp)",
					 "xlab": "Sample"},
					{"file": "Per_sequence_GC_content.csv",
					 "output": join(arguments["output"], "QCResults/Report/src/img", "Per_sequence_GC_content.png"),
					 "title": "Per sequence GC content",
					 "ylab": "Mean GC content (%)",
					 "xlab": "Sample"}]
		for plot in boxplots:
			process = subprocess.Popen(" ".join(["Rscript --vanilla ", join(os.path.dirname(__file__), "boxplot.R"),
												 join(arguments["output"], "QCResults", "Report", "src", plot["file"]),
												 plot["output"], '"' + plot["title"] + '"', '"' + plot["xlab"] + '"',
												 '"' + plot["ylab"] + '"']),
									   stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
			#for line in iter(process.stderr.readline, b''):
			#	print(line)
			process.communicate()

		#
		# Plot BARPLOTS
		process = subprocess.Popen(
			" ".join(["Rscript --vanilla ", join(os.path.dirname(__file__), "barplot.R"), join(arguments["output"], "QCResults/Report/src", "summary.json"),
					  join(arguments["output"], "QCResults/Report/src/img")]), stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
		process.communicate()
	except:
		print("Couldnt plot summary")


def writeSummaryTex(batch_json):
	try:
		summary_latex_name = join(arguments["output"], "QCResults", "Report", "summary.tex")
		with open(summary_latex_name, "w") as summary_latex:
			summary_latex.write("\\rowcolors{2}{gray!10}{}\n\\begin{table}[H]\\begin{tabular}{lcc}\n")
			summary_latex.write(
				"\\rowcolor{tableBlue} \\textbf{Sample} &  \\textbf{Reads after trimming [\#]} & \\textbf{Reads after trimming [\%]} &\\textbf{Map to reference [\#]} & \\textbf{Map to reference[\%]} & \\textbf{Classified (Kraken)} & \\textbf{Shorter fragments [\%]} \\ \n")

			for i in range(0, len(batch_json["summary"])):
				summary_latex.write(
					str(batch_json["summary"][i]["setname"]) + " & " +
					str(batch_json["summary"][i]["Reads after trimming [#]"]) + " & " +
					str(batch_json["summary"][i]["Reads after trimming [%]"]) + " & " +
					str(batch_json["summary"][i]["Map to reference [#]"]) + " & " +
					str(batch_json["summary"][i]["Map to reference [%]"]) + " & " +
					str(batch_json["summary"][i]["Classified (Kraken)"]) + " & " +
					str(batch_json["summary"][i]["Shorter fragments"]) + "\\\\\n"
				)
			summary_latex.write("\\end{tabular}\n")
			summary_latex.write("\\caption{Statistics on reads after trimming. }")
			summary_latex.close()
	except:

		print("Couldnt write summary.tex file.")

def main(arguments):

	tmp = join(arguments["output"],"QCResults" ,"qc_tmp")
	makedirs(tmp, exist_ok=True)
	makedirs(join(arguments["output"], "QCResults"), exist_ok=True)
	makedirs(join(arguments["output"], "QCResults", "FastQC"), exist_ok=True)
	makedirs(join(arguments["output"], "QCResults", "Trimmed"), exist_ok=True)
	makedirs(join(arguments["output"], "QCResults", "Trimmed", "FastQC"), exist_ok=True)
	makedirs(join(arguments["output"], "QCResults", "Report"), exist_ok=True)
	makedirs(join(arguments["output"], "QCResults", "Report", "src"), exist_ok=True)
	makedirs(join(arguments["output"], "QCResults", "Report", "src", "img"), exist_ok=True)

	if not os.path.exists(join(arguments["output"], "QCResults", "Report", "lib" )):
		shutil.copytree(join(os.path.dirname(__file__),"lib"),join(arguments["output"], "QCResults", "Report", "lib" ))

	####
	# rename sample names
	####
	if arguments["rename"]:
		rename_dict = {}
		with open(arguments["rename"], "r") as csvfile:
			for line in csvfile:
				row = line.split("\t")
				rename_dict[row[0]] = row[1].strip()
		arguments["rename"] = rename_dict

	###
	# create new boxplot csv files
	###
	for csv in ["Per_sequence_quality_scores.csv", "Per_sequence_GC_content.csv", "Sequence_Length_Distribution.csv"]:
		new_csv = open(join(arguments["output"], "QCResults", "Report", "src", csv), "w")
		new_csv.write("Sample,Read,Lane,Trimmed,Value,Count\n")
		new_csv.close()

	###
	# Write SAV
	###
	try:
		if arguments["sav"]:
			write_SAV(arguments["sav"], join(arguments["output"], "QCResults", "Report", "src"))
	except:
		print("Couldnt write SAV.")


	#
	# Check input validity
	check_input_validity()

	if arguments["index"]:
		mapping_index_path = arguments["index"]
	else:
		mapping_index_path = join(tmp, "bowtie2_index")
		os.makedirs(mapping_index_path, exist_ok=True)

	myFiles = get_input()
	print("Found " + str(len(myFiles)) + " sample(s).")

	#
	# Get parameter defaults
	get_defaults()

	batch_json = json.dump({
			"commandline": arguments,
			"summary": [],
			"kraken": {},
			"versions": Pipeline().__dict__},
		open(join(arguments["output"], "QCResults/Report/src", "summary.json"), "w"))

	output = join(arguments["output"], "QCResults")  # getDir([arguments["output"], "QCResults"], True)

	i = 1
	#######
	# Run for each sample
	#######
	try:
		for subset in myFiles:
			print("Analyse " + str(i) + "/" + str(len(myFiles)))
			sample_tmp = join(tmp, "Sample_" + str(i))
			os.makedirs(sample_tmp, exist_ok=True)

			if isinstance(subset, str):
				arguments["r1"] = subset
			else:
				arguments["r1"] = subset[0]
				if len(subset)>1:
					arguments["r2"] = subset[1]

			####
			# Run Analyses
			####
			sample = runAnalyses( mapping_index_path, sample_tmp )

			####
			# Write output
			####
			if sample is not None:
				try:
					writeReport(sample)
				except:
					print("Couldnt write pdf.")
				try:
					batch_json = json.load(open(join(arguments["output"], "QCResults/Report/src", "summary.json"), "r"), object_pairs_hook=OrderedDict)
					if sample.mappingRes is None:
						pMapping = 0
						nMapping = 0
					else:
						pMapping = sample.mappingRes.percentAlignedReads
						nMapping = sample.mappingRes.numberOfAlignedReads
					if sample.krakenRes is None:
						kraken = 0
						kraken_reports ={}
					else:
						kraken = sample.krakenRes.pClassified
						batch_json["kraken"][sample.name] = json.loads(str_to_json(sample.krakenRes.report))
					#tmp_overview.write(",".join([sample.name, str(sample.nTrimmed()), str(nMapping), str(kraken)]) +"\n")
					try:
						trim_param = sample.readSets[0].trimRes.print_param(arguments["palindrome"], arguments["minlen"],
															   arguments["trimOption"])
					except:
						trim_param="None"
					batch_json["summary"].append(
							OrderedDict([("setname", sample.name),
										 ("Total reads [#]", sample.total_reads()),
										 ("Reads after trimming [#]", sample.nTrimmed()),
										 ("Reads after trimming [%]", sample.pTrimmed()),
										 ("Map to reference [#]", nMapping),
										 ("Map to reference [%]", pMapping),
										 ("Classified (Kraken)", kraken),
										 ("Shorter fragments", sample.get_mean_trimRes()),
										 ("Trim Parameter",trim_param),
										 ("images", [x.get_all_qc_dict() for x in sample.readSets])]))

					json.dump(batch_json, open(join(arguments["output"], "QCResults/Report/src", "summary.json"), "w"))
				except:
					print("Couldnt produce HTML report.")

			sample = None
			arguments["r1"]=None
			arguments["r2"]=None
			i+=1
		# plot boxplots and barplots
		plot()
		writeSummaryTex(batch_json)
		shutil.copy(join(os.path.dirname(__file__), "batch_report.html"), join(arguments["output"], "QCResults", "Report", "batch_report.html"))

	finally:

		shutil.rmtree(tmp)
		delete_files(join(arguments["output"],"QCResults"), "FastQC", "_fastqc.html")
		delete_files(join(arguments["output"],"QCResults"), "Trimmed/FastQC", "_fastqc.html")
 
if __name__ == "__main__":
	config = configparser.ConfigParser()
	config.read(join(dirname(__file__), "config.txt"))
	kraken_db = ""
	if "DEFAULT" in config:
		if "kraken_db" in config["DEFAULT"].keys():
			kraken_db = config["DEFAULT"]["kraken_db"]

	parser = argparse.ArgumentParser()
	parser.add_argument( '-input', dest='input', help = "input sample folder. Illumina filenames should end with _<lane>_<R1|R2>_number, e.g. Sample_12_345_R1_001.fastq, to find the right paired set.", required=False)
	parser.add_argument('-1' , dest='r1', help = "input file", required=False)
	parser.add_argument( '-2', dest='r2', help = "input file", required=False)

	parser.add_argument('-output', dest='output', default="")
	parser.add_argument('-technology', dest='technology',choices=['Illumina',"IonTorrent"] ,required=False , help = "If not set, automatically determine technology and search for fastq and bam files. Set technology to IonTorrent if all files are bam-files, else set technology to Illumina.")
	parser.add_argument('-threads', dest='threads', default = 4, type = int, help= "Number of threads. Default:  %(default)s")
	parser.add_argument('-adapter', dest = 'adapter', choices = ['TruSeq2-PE', 'TruSeq2-SE' , 'TruSeq3-PE' , 'TruSeq3-SE' , 'TruSeq3-PE-2', 'NexteraPE-PE' ])
	parser.add_argument('-reference', dest='reference', required = False, help = "Map reads against reference")
	parser.add_argument('-index', dest='index', required = False, help = "Bowtie2 index if available.")
	parser.add_argument('-sav', dest='sav', required=False,help="Illumina folder for SAV. Requires RunInfo.xml, RunParamter.xml and Interop folder.")

	parser.add_argument('-save_mapping', action = "store_true")
	parser.add_argument('-db', dest='db', help='Kraken database', required = False, default= kraken_db)
	parser.add_argument('-palindrome', dest='palindrome', default=30, help= 'Use palindrome parameter 30 or 1000 for further analysis. Default: %(default)s', type = int)
	parser.add_argument('-minlen', default=50,dest='minlen',help='Minlen parameter for Trimmomatic. Default: %(default)s',  type=int)
	parser.add_argument('-trimOption', dest="trimOption", help='Use maxinfo or slidinginfo for Trimmomatic.MAXINFO:<target length>:<strictness> | SLIDINGWINDOW:<window size>:<required quality>.', type= str)
	parser.add_argument('-version', action='version', version='%(prog)s v' + __version__)
	parser.add_argument('-nokraken', action = "store_true")
	parser.add_argument('-nomapping', action = "store_true")
	parser.add_argument('-notrimming', action = "store_true")
	parser.add_argument('-gz', action = "store_true")
	parser.add_argument('-trimBetter', action = "store_true", help= "Optimize trimming parameter using 'Per sequence base content' from fastqc. Not recommended for amplicons.")
	parser.add_argument('-trimBetter_threshold', dest='trimBetter_threshold', help = "Set -trimBetter to use this option.Default setting for Illumina: 0.15 and for IonTorrent: 0.25.", required=False, type=float)
	parser.add_argument('-forAssembly', action = "store_true", help = "Set -trimBetter to use this option.Trim parameter are optimized for assemblies (trim more aggressive).")
	parser.add_argument('-forMapping', action = "store_true", help = "Set -trimBetter to use this option.Trim parameter are optimized for mapping (allow more errors).")
	parser.add_argument('-rename', dest="rename", required=False, help="TSV File with two columns: <old sample name> <new sample name>")
	parser.add_argument('-parameters', dest = 'parameters', default = join(dirname(__file__), "parameter.txt"))

	arguments = vars(parser.parse_args())
	parameter = configparser.ConfigParser(strict=False, interpolation=None)
	parameter.read(arguments['parameters'])

	r1_pattern = parameter["Pattern"]["R1"]
	r2_pattern = parameter["Pattern"]["R2"]
	sep_pattern = parameter["Pattern"]["sep"]
	lane_pattern = parameter["Pattern"]["lane"]
	main(arguments)
