#!/usr/bin/python

"""

Read a pair of fastq files and filter out reads which IDs not found in both files

"""

import sys

fq1 = open(sys.argv[1])
fq2 = open(sys.argv[2])
out1 = open(sys.argv[3], "w")
out2 = open(sys.argv[4], "w")

stack1 = dict()
stack2 = dict()

counter = 0
same = False

while True:
	read1 = fq1.readline()
	read2 = fq2.readline()
	if not read1 and not read2:
		break

	#TODO remove /1 and /2 from the end of the line

	if counter % 4 == 0:
		same = False
		if read1 == read2:
			same = True
		else:
			id1 = read1
			id2 = read2
		for k in stack1.keys():
			if k in stack1 and k in stack2:
				out1.write(k)
				out2.write(k)
				out1.write("".join(stack1[k]))
				out2.write("".join(stack2[k]))
				del stack1[k]
				del stack2[k]
	else:
		if not same:
			stack1[id1] = list()
			stack2[id2] = list()
			stack1[id1].append(read1)
			stack2[id2].append(read2)

	if same:
		out1.write(read1)
		out2.write(read2)
	counter += 1
	if counter % 1000000 == 0:
		print counter

if k in stack1 and k in stack2:
	out1.write(k)
	out2.write(k)
	out1.write("".join(stack1[k]))
	out2.write("".join(stack2[k]))
	del stack1[k]
	del stack2[k]

out1.close()
out2.close()
