import sys

QTLFILENAME = sys.argv[1]
PEAKLOCATIONFILENAME = sys.argv[2]
OUTPUTFILENAME = sys.argv[3]

def getPeakLocationInfo(peakLocationLine):
	# Get the peak ID and coordinates for a peak
	peakLocationLineElements = peakLocationLine.strip().split()
	peakID = int(peakLocationLineElements[0])
	peakLocation = ("chr" + peakLocationLineElements[1], int(peakLocationLineElements[2]), int(peakLocationLineElements[3]))
	return [peakID, peakLocation]

def getPeakLocationsForQTLs():
	# Gets the peak location corresponding to each QTL
	# ASSUMES THAT QTLFile AND peakLocationFile ARE SORTED BY PEAK ID
	# ASSUMES THAT EVERY QTL HAS AN ID THAT MATCHES A PEAK LOCATION ID
	QTLFile = open(QTLFILENAME)
	peakLocationFile = open(PEAKLOCATIONFILENAME)
	outputFile = open(OUTPUTFILENAME, 'w+')
	peakLocationFile.readline() # Remove the header
	[peakID, peakLocation] = getPeakLocationInfo(peakLocationFile.readline())
	for line in QTLFile:
		# Iterate through the QTLs and find the region corresponding to each
		lineElements = line.strip().split("\t")
		if lineElements[8] != "pass":
			# The current QTL does not make the p-value cutoff, so skip it
			continue
		peakIDForQTL = int(lineElements[1])
		while peakIDForQTL > peakID:
			# Iterate through the peaks until the one with the correct ID is reached
			[peakID, peakLocation] = getPeakLocationInfo(peakLocationFile.readline())
		if peakIDForQTL < peakID:
			print "Problem!"
			print line
			break
		outputFile.write(peakLocation[0] + "\t" + str(peakLocation[1]) + "\t" + str(peakLocation[2]) + "\n")
	QTLFile.close()
	peakLocationFile.close()
	outputFile.close()

if __name__=='__main__':
	getPeakLocationsForQTLs()