import matplotlib.pyplot as plt
import numpy as np
import math
from scipy.stats import norm
import matplotlib.mlab as mlab
import argparse
import sys
import ROOT
ROOT.gROOT.SetBatch()
from array import *

# parse arguments
parser = argparse.ArgumentParser()
parser.add_argument("--filename", help="input hex data file", default=0, nargs='*')

args = parser.parse_args()
filename = args.filename
T = [x[:-4] for x in filename]
T = map(float, T)
T = np.array(T)

dtmin = T - 100
dtmax = T + 100
dtbins = dtmax - dtmin + 1
dtbins = map(int, dtbins)

minb = dtmin - .5
maxb = dtmax + .5

if filename == 0:
	print "No filename specified, use the --filename parameter."
	sys.exit()

#global variables
c = 0
T_exp = []
dt = []

for x in filename:
	#initialize variables
	itseq = []
	before = 0
	dif_list = []
	tstamp_list = []
	dt_list = []

	with open(x,"r") as f:
		for line in f:
		#read in each line of hex data and convert it to timestamp
		    scale = 16 
		    count = 41
		    itstamp = 0

		    for hexd in line[0:10]:
		        count = count - 4
		        ihex = int(hexd, scale)
		        #print hexd, ihex
		        jhex = ihex << count
		        itstamp = itstamp + jhex
		        
		    hexd = line[10]
		    ihex = int(hexd, scale)
		    #print hexd, ihex
		    jhex = ihex >> 3
		    itstamp = itstamp + jhex

		    #print itstamp
		    itseq.append(itstamp)

	#read in dif to dif_list
	for tstamp in itseq:
		itstamp = int(tstamp) 
		dif = abs(itstamp - before)
	
		if(abs(dif) > 10 and before != 0): 
		    dif_list += [dif]
		    if(abs(dif) >= dtmin[c] and abs(dif) <= dtmax[c]):
		        dt_list += [dif]
		        tstamp_list += [itstamp]
		before = itstamp
	
	#scatter
	T_exp += [T[c]] * len(dt_list)
	dt.extend(dt_list)
	dt_array = array('d', dt_list)

	c += 1

dt_array = array('d', dt)
exp_array = array('d', T_exp)

g = ROOT.TGraph(len(exp_array),exp_array,dt_array)
g.SetMarkerStyle(1)
g.SetMarkerSize(1)
g.Draw("AP")
g.SetTitle("#Delta timestamp vs. expected T [ns]")
g.SetName("#Delta timestamp vs. expected T [ns]")
g.GetXaxis().SetTitle("expected T [ns]")
g.GetYaxis().SetTitle("#Delta timestamp [ns]")

#create root file
output = ROOT.TFile("plotqtc1.root", "recreate")
output.cd()
g.Write()
output.Close()

