def makeFIMOPeakMotifScript(peakFileNameListFileName, genomeFileName, outputFileName, thresh):
	# Make a script that will run FIMO on the sequences in each peak with the motifs from each peak
	peakFileNameListFile = open(peakFileNameListFileName)
	outputFile = open(outputFileName, 'w+')
	for line in peakFileNameListFile:
		# Iterate through the fasta file names and add a line for each to the script
		peakFileName = line.strip()
		peakList = bt.BedTool(peakFileName)
		peakFileNameElements = peakFileName.split(".")
		peakFileNamePrefix = ".".join(peakFileNameElements[0:-2])
		PWMFileName = peakFileNamePrefix + ".HomerMotifsMEME.txt"
		fastaFileName = peakFileNamePrefix + ".fa"
		fastaList = peakList.sequence(fi = genomeFileName, fo = fastaFileName)
		FIMOOutputFileName = peakFileNamePrefix + ".PeakFIMOResults"
		outputFile.write(" ".join(["fimo --max-stored-scores 10000000 --o", FIMOOutputFileName, "--thresh", str(thresh), \
			PWMFileName, fastaFileName]) + "\n")
	peakFileNameListFile.close()
	outputFile.close()

if __name__=="__main__":
   import sys
   import pybedtools as bt
   peakFileNameListFileName = sys.argv[1]
   genomeFileName = sys.argv[2]
   outputFileName = sys.argv[3]
   thresh = 0.05
   if len(sys.argv) > 4:
	   # There is a q-value threshold argument
		thresh = float(sys.argv[4])
   makeFIMOPeakMotifScript(peakFileNameListFileName, genomeFileName, outputFileName, thresh)
