import sys
import numpy as np

MATRIXONEFILENAME = sys.argv[1]
MATRIXTWOFILENAME = sys.argv[2]
DETECTORLENGTHFILENAME = sys.argv[3]
OUTPUTFILENAME = sys.argv[4]
SEQUENCELENGTH = int(sys.argv[5])
MAXPOOLSIZE = int(sys.argv[6])

def getIntList():
	# Gets a list of ints from the detector file
	intFile = open(DETECTORLENGTHFILENAME)
	intList = []
	for line in intFile:
		# Iterate through the ints and add each to the list
		intList.append(int(line.strip()))
	intFile.close()
	return np.array(intList)

def getNumEntriesPerDetector(detectorLengthList):
	# Get the number of entries for each detector
	numTotalEntriesPerDetector = SEQUENCELENGTH - detectorLengthList + 1
	numEntriesPerDetector = np.ceil(numTotalEntriesPerDetector.astype('float')/float(MAXPOOLSIZE))
	return [numTotalEntriesPerDetector, numEntriesPerDetector.astype('int')]

def getMatrixDifferencesMaxPos(detectorLengthList):
	matrixOne = np.loadtxt(MATRIXONEFILENAME, dtype = np.float16)
	[numTotalEntriesPerDetector, numEntriesPerDetector] = getNumEntriesPerDetector(detectorLengthList)
	matrixOneMaxPool = np.zeros((matrixOne.shape[0], np.sum(numEntriesPerDetector)))
	maxDistPos = np.zeros((matrixOne.shape[0], 2*len(detectorLengthList)))
	matrixTwoFile = open(MATRIXTWOFILENAME)
	lineNum = 0
	for line in matrixTwoFile:
		# For each row in the second matrix, get the maximum difference and the distance of that difference from the center
		lineVals = np.fromstring(line.strip(), dtype = np.float16, sep = "\t")
		diffs = np.absolute(np.subtract(matrixOne[lineNum], lineVals))
		for i in range(len(numEntriesPerDetector)):
			# Iterate through the detectors and get the maximum difference and all of the max-pools for each
			maxDistPos[lineNum][2*i] = np.amax(diffs[np.sum(numTotalEntriesPerDetector[0:i]):np.sum(numTotalEntriesPerDetector[0:i+1])])
			maxDistPos[lineNum][(2*i) + 1] = abs(np.floor(float(numTotalEntriesPerDetector[i])/2.0) - np.argmax(diffs[np.sum(numTotalEntriesPerDetector[0:i]):np.sum(numTotalEntriesPerDetector[0:i+1])]))
			for j in range(numEntriesPerDetector[i] - 1):
				# Iterate through the max-pool groups and take the maximum of each
				matrixOneMaxPool[lineNum][sum(numEntriesPerDetector[0:i]) + j] = np.amax(matrixOne[lineNum][np.sum(numTotalEntriesPerDetector[0:i]) + (j * MAXPOOLSIZE):np.sum(numTotalEntriesPerDetector[0:i]) + ((j + 1) * MAXPOOLSIZE)])
			matrixOneMaxPool[lineNum][sum(numEntriesPerDetector[0:i]) + numEntriesPerDetector[i] - 1] = np.amax(matrixOne[lineNum][np.sum(numTotalEntriesPerDetector[0:i]) + ((numEntriesPerDetector[i] - 1) * MAXPOOLSIZE):np.sum(numTotalEntriesPerDetector[0:i+1])])
		lineNum = lineNum + 1
	matrixTwoFile.close()
	matrixOut = np.concatenate((matrixOneMaxPool, maxDistPos), axis = 1)
	np.savetxt(OUTPUTFILENAME, matrixOut, '%4.3f', delimiter="\t")
	
if __name__=="__main__":
	detectorLengthList = getIntList()
	getMatrixDifferencesMaxPos(detectorLengthList)
	