#!/usr/bin/python
import os,sys,inspect
import numpy as np

currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir) 
import common
import config as cfg





#def getNormalCN(chrom, gender):
#	normalCN = 2.
#	if chrom in ['chrX', 'chrY'] and gender == 'M':
#		normalCN = 1.
#	elif chrom == 'chrY' and gender == 'F':
#		normalCN = 0.
#	return normalCN





def mergeSegCN(seg1, seg2, intD=False):
	currentWeight = seg1['end'] - seg1['start']
	nextWeight = seg2['end'] - seg2['start']
	weightedAverageCN = np.average([seg1['CN'], seg2['CN']], weights = [currentWeight, nextWeight])
	
	if intD:
		currentIntdist = abs(np.round(seg1['CN']) - seg1['CN'])
		nextIntdist = abs(np.round(seg2['CN']) - seg2['CN'])
		weightedAverageIntdist = np.average([currentIntdist, nextIntdist], weights = [currentWeight, nextWeight])
		mergeIntdist = abs(np.round(weightedAverageCN) - weightedAverageCN)
		
		return weightedAverageCN, weightedAverageIntdist, mergeIntdist

	else:
		return weightedAverageCN
	
	
	
	

def mergeCNinitial(dataDict, gender):
	newData = [dataDict[0]]

	for i in dataDict[1:]:
		addData = i

		if newData[-1]['chrom'] == i['chrom'] and np.round(newData[-1]['CN']) == np.round(i['CN']):
			weightedAverageCN, weightedAverageIntdist, mergeIntdist = mergeSegCN(newData[-1], i, intD=True)

			#previously was <= but that's stupid b/c it can really only improve
			if mergeIntdist < weightedAverageIntdist or np.round(i['CN']) == common.getNormalCN(i['chrom'], gender):
			#	print 'passed', weightedAverageIntdist, mergeIntdist
				prevMerge = newData.pop()
				addData =	{
					'chrom': i['chrom'], 
					'start': prevMerge['start'], 
					'end': i['end'], 
					'CN': weightedAverageCN
					}