#!/bin/env python 
from __future__ import division
from __future__ import print_function
import sys
import numpy as np
import matplotlib.pyplot as plt
import math

if len(sys.argv) != 6:
  print("Usage: {0} array1 array2 WIN bin_size flag".format(sys.argv[0])) 
  print("Set flag to hist, for histogram; otherwise type 0 for it")
  sys.exit()

yVar1 = np.load(sys.argv[1]) #the in-phase or out-of-phase numpy array
yVar2 = np.load(sys.argv[2]) #the seqEvntCnt numpy array
winSz = int(sys.argv[3]) #Use the same window with which array was created
#bin size is upto the user. For a window of size 6 kbp, a bin size of 200 or 250 is advisable. 
binSz = int(sys.argv[4]) 
#See above for comment on flag. 
flg = sys.argv[5]

#f for flank
nfBins = int(math.ceil(winSz/binSz))
print("nfBins: {0}".format(nfBins))

#This numpy array will contain either raw counts or normalized density. 
snpBinSum = np.zeros(2*nfBins)
 
#builds the right bins
for j,i in zip(range(nfBins, 2*nfBins), range(winSz, 2*winSz, binSz)):
  if j < 2*nfBins-1:
    if flg == "hist":
      snpBinSum[j] = sum(yVar1[i:i+binSz]) #just count the counts
    else:
      snpBinSum[j] = sum(yVar1[i:i+binSz])/sum(yVar2[i:i+binSz])
  else:
    if flg == "hist":
      snpBinSum[j] = sum(yVar1[i:]) #just count the counts
    else:
      snpBinSum[j] = sum(yVar1[i:])/sum(yVar2[i:])
    
#builds the left bins
for j, i in zip(range(nfBins-1, -1, -1), range(winSz-1, -1, -binSz)):
  if j > 0:
    if flg == "hist":
      snpBinSum[j] = sum(yVar1[i:i-binSz:-1])
    else:
      snpBinSum[j] = sum(yVar1[i:i-binSz:-1])/sum(yVar2[i:i-binSz:-1])
  else:
    if flg == "hist":
      snpBinSum[j] = sum(yVar1[i::-1])
    else:
      snpBinSum[j] = sum(yVar1[i::-1])/sum(yVar2[i::-1])

  
#This sets the x-values for the plot. Note that this is essentially
#follows the i index above (we choose every binSz). 
xVar = np.concatenate((np.arange(-winSz, 0, binSz), np.arange(0, winSz, binSz)))

#The code below can be commented out to draw histogram or a plot of density. Or one can
#plot in ipython window directly using matplotlib plot programs. 
#plt.figure()
#below, in-phase color choice
#plt.bar(xVar, snpBinSum, width=400,color='#920000')
#plt.plot(xVar, snpBinSum, color='#920000')
#below, out-of-phase color choice
#plt.plot(xVar, snpBinSum, color='#006ddb')
#plt.show()
