#!/usr/bin/python3
# -*- coding: utf-8 -*-

from __future__ import print_function
import Manyo as mm
import makeHistogram as mH
import makeHistoExtend as mE
import utsusemi.vis.M2Plot as mp
#import numpy as np
#import math
#import os
import sys

from tofHist import * 

ver = float(sys.version_info[0])+float(sys.version_info[1])*0.1
if ver<2.5:
    from elementtree.ElementTree import ElementTree
else:
    from xml.etree.ElementTree import ElementTree

import getVNRConst #[inamura 180326]

# reserved words for return value in this.
DAT = None
ECA = None
#ecm = None

#########################################
def PickupCurpos(runnumber=124368, meas='A2TH'):
    """
    Pickup params.xml curPos log for VNR
    @param  runnumber    (int) Run Number
    @param  meas         (string) measurement device 
    @retval TH           (double)
    """

    #exID = os.path.join(os.sep,"data",XXX, "exIDrunNo.txt")
    exID = os.path.join(os.sep,getVNRConst.GetDataDir(True), "exIDrunNo.txt") #[inamura 180326]
    f = open( exID)
    lines = f.readlines()
    f.close()
    exno = 0
    curPos = '-9999.9'
    for line in lines:
	words = line.split(",")
	if ( len( words) > 2):
	    if ( int( words[2]) == runnumber):
		exno = int( words[1])
		print("exID: ", exno, " runNo.:", runnumber)
    if ( exno > 0):
	#exID = os.path.join(os.sep,"usr","local","mlf",XXX,"ana","xml","ex"+str(exno).zfill(8),"params.xml")
        exID = os.path.join(os.sep,getVNRConst.GetUserDir(),"ana","xml","ex"+str(exno).zfill(8),"params.xml") #[inamura 180326]
        if os.path.exists(exID):
	    ET = ElementTree()
            dom = ET.parse(exID)
	    exInfo_ele = dom.find("exInfo")
	    rsltlst_ele = exInfo_ele.find("measRsltLst")
	    runno = str(runnumber)
	    for rslt_ele in rsltlst_ele.findall("measRslt"):
	        runNo = rslt_ele.find("runNo").text
		if ( runNo == runno):
		    param_ele = rslt_ele.find("param")
		    loglst_ele = param_ele.find("logLst")
		    if ( isinstance( loglst_ele, type(None)) == False):
			for logs_ele in loglst_ele.findall("logs"):
			    devName = logs_ele.find("devName").text
			    if ( devName == meas):
				curPos = logs_ele.find( ".//curPos").text
				print("Device: ", devName, " Value: ", curPos)
	    if ( curPos == '-9999.9'):
		print("Not found log in params.xml:", exno)
	else:
	    print("Not found params.xml: ", exno) 
    else:
	print("Not found. runNo.:", runnumber)
    TH = float( curPos) 
    return TH

########################################
def GetHistMWPC0d(runStr='123927', initial_bin=10000.0,final_bin=38100.0,delta_bin=0.01, xmin=64, xmax=191, ymin=64, ymax=191):
    """
    Load EventData and convert to histogram for MWPC
    @param  runStr       (String) Run Number
    @param  initial_bin  (double) 
    @param  final_bin    (double) 
    @param  delta_bin    (double) 
    @param  xmin         (int)
    @param  xmax         (int)
    @param  ymin         (int)
    @param  ymax         (int)
    @retval EC           (ElementContainer)
    """

    dioFlag = -1
    pixels = (256,256)

    runArray=runStr.split('+')
    for j in range( len( runArray)):
	runNo = int(runArray[j])
	datalone, T0Coone = mH.getEventDataArray( runNo, "MWPC", pixels, dioFlag)
	t0c = len( T0Coone)
	if j == 0:
	    datalist = datalone
	    T0Count = T0Coone
	else:
	    for i in range( t0c):
		T0Count[i] += T0Coone[i]
		dataone = datalone[i]
		for y in range( len(dataone) ):
		    for x in range( len(dataone[y]) ):
			if ( dataone[y][x] != []):
			    if ( datalist[i][y][x] != []):
				datalist[i][y][x] = np.concatenate((datalist[i][y][x], dataone[y][x]))
			    else:
				datalist[i][y][x] = dataone[y][x]

    ## datalist, T0Count = mH.getEventDataArray( runNo, "MWPC", pixels, dioFlag)

    runNo = int(runArray[0])
    if ( initial_bin < 0.0):
	initial_bin = 0.0
    if ( final_bin <= 0.0):
	final_bin = 80000.0
    if ( initial_bin >= final_bin):
	initila_bin = 0.0
    bins = getTofBin_DT_T_Constant(initial_bin,final_bin,delta_bin)
    t0c = len( T0Count)
    for i in range( t0c):
	t0s = T0Count[i]
	event_c = 0
	dataone = datalist[i]
	for y in range( len(dataone) ):
	    if ( y >= ymin and y <= ymax):
		for x in range( len(dataone[y]) ):
		    if ( x >= xmin and x <= xmax):
			events = dataone[y][x]
			if ( len( events) > 0):  # 2016-10-17 ##[inamura 180330]
			#if ( events != []):
			    if ( event_c == 0):
				intensity_array = events
			    else:
				intensity_array = np.concatenate((intensity_array, events))
			    event_c += 1
	intensity_a, tof_array = np.histogram( intensity_array, bins=bins )
	err_array = np.sqrt( intensity_a ) / float( t0s)
	intensity_array = intensity_a / float( t0s)
	print("Cell:", event_c)
	hh = mm.HeaderBase()
	hh.Add("RUNNUMBER", str(runNo))
	hh.Add("XAxis", "TOF")
	hh.Add("XLABEL", "TOF")
	hh.Add("YLABEL", "Intensity")
	hh.Add("TotalCount", float(intensity_array.sum()))
	hh.Add("T0Count",t0s)
	if ( t0c > 1):
	    if ( i == 0):
		hh.Add("Label", "mp")
	    else:
		if ( i == 1): 
		    hh.Add("Label", "pp")
		else:
		    if ( i == 2):
			hh.Add("Label", "mm")
		    else:
			hh.Add("Label", "pm")
	a2th = PickupCurpos(runNo, 'A2TH')
	if ( a2th != -9999.9):
	    hh.Add("A2TH", a2th)
        EC  = mm.ElementContainer(hh)
	EC.Add("TOF",tof_array.tolist(), "microsec")
	EC.Add("Intensity", intensity_array.tolist(), "Counts")
	EC.Add("Error", err_array.tolist(), "Counts")
	EC.SetKeys("TOF","Intensity","Error")

    return EC

########################################
def GetHistMWPC0dx(runNo=123927, initial_bin=10000.0,final_bin=38100.0,delta_bin=0.01, xmin=64, xstep=4, ymin=64, ymax=191):
    """
    Load EventData and convert to histogram for MWPC
    @param  runNo       (int) Run Number
    @param  initial_bin (double) 
    @param  final_bin   (double) 
    @param  delta_bin   (double) or width_of_bin 
    @param  xmin        (int)
    @param  xstep       (int)
    @param  ymin        (int)
    @param  ymax        (int)
    """

    dioFlag = -1
    pixels = (256,256)
    datalist, T0Count = mH.getEventDataArray( runNo, "MWPC", pixels, dioFlag)

    if ( initial_bin < 0.0):
	initial_bin = 0.0
    if ( final_bin <= 0.0):
	final_bin = 80000.0
    if ( initial_bin >= final_bin):
	initila_bin = 0.0
    if ( ymin < 0 or ymin > 255):
	ymin = 0
    if ( ymax < 0 or ymax > 255):
	ymax = 255
    if ( xmin < 0 or xmin > 255):
	xmin = 0
    if ( xstep < 1 or xstep > 255):
	xstep = 4

    if ( delta_bin >= 1.0):
	bin = getTofBin_T_Constant(int(initial_bin),int(final_bin),int(delta_bin))
	bins = map(float, bin)
    else:
	bins = getTofBin_DT_T_Constant(initial_bin,final_bin,delta_bin)
    t0c = len( T0Count)
    #f = open("/usr/local/mlf/VNR/ana/xml/"+str(runNo).zfill(6)+"_x.dat", 'w')
    f = open( os.path.join( getVNRConst.GetUserDir(),"ana","xml",str(runNo).zfill(6)+"_x.dat"), 'w') #[inamura 180403]
    f.write("tof_%d\tref_%d\terr_%d\n" % ( runNo, runNo, runNo))
    for i in range( t0c):
	t0s = T0Count[i]
	dataone = datalist[i]
	hist_n = ( (255 - xmin) / xstep) + 1
	intens = [np.array([])] * hist_n
	for y in range( ymin, ymax + 1):
	    for x0 in range( hist_n):
		for xs in range( 0, xstep):
		    x = xmin + xstep * x0 + xs
		    events = dataone[y][x]
		    #if ( events != []):
                    if ( len( events) > 0):  #[inamura 180403]
			intens[x0] = np.concatenate((intens[x0], events))
	print("Histogram n:", hist_n)
	for x0 in range( hist_n):
	    if ( intens[x0] != []):
		intensity_a, tof_array = np.histogram( intens[x0], bins=bins )
		err_array = np.sqrt( intensity_a )
		tof_a = (tof_array[1:] + tof_array[:-1]) * 0.5
		f.write("\nposition:%d  x = (%d, %d)\n" % ( x0, xmin + xstep * x0, xmin + xstep * (x0 + 1) - 1))
		for j in range( len( tof_a)):
		    f.write("%.12g\t%.16g\t%.16g\n" % (tof_a[j], intensity_a[j], err_array[j]))

    f.close()

########################################
def GetHistMWPC0dTime(runNo=129117, dioFlag=-1, bin_range='10000,38100', delta_bin=0.01, xrange='64,191', yrange='64,191', timerange='0,-1', timestep=-1):
    """
    Load EventData and convert to histogram for MWPC
    @param  runNo       (int) Run Number
    @param  dioFlag	(int) 
    @param  bin_range   (string) min, max
    @param  delta_bin   (double) or width_of_bin 
    @param  xrange      (string) min, max
    @param  yrange      (string) min, max
    @param  timerange   (string)
    @param  timestep    (int)   or -1 (not use)
    @retval ECA         (ElementContainer)
    """

    pixels = (256,256)
    words= bin_range.split(",")
    initial_bin = int( words[0])
    if ( len( words) > 1):
	final_bin = int( words[1])
    else:
	final_bin = 80000
    if ( initial_bin > final_bin):
	final_bin = 80000
    words= xrange.split(",")
    xmin = int( words[0])
    if ( len ( words) > 1):
	xmax = int( words[1])
    else:
	xmax = 255
    words= yrange.split(",")
    ymin = int( words[0])
    if ( len ( words) > 1):
	ymax = int( words[1])
    else:
	ymax = 255
    words= timerange.split(",")
    nT0start = int( words[0])
    if ( len ( words) > 1):
	nT0end = int( words[1])
    else:
	nT0end = -1
    if timestep < 1:
	nT0step = -1
    else:
	nT0step = timestep

    datalist, T0Count = mE.getEventDataArrayMulti( runNo, "MWPC", pixels, dioFlag, nT0start, nT0end, nT0step, initial_bin, final_bin)

    if ( delta_bin >= 1.0):
	bin = getTofBin_T_Constant(int(initial_bin),int(final_bin),int(delta_bin))
	bins = map(float, bin)
    else:
	bins = getTofBin_DT_T_Constant(initial_bin,final_bin,delta_bin)

    a2th = PickupCurpos(runNo, 'A2TH')

    if ( dioFlag == -1 or dioFlag == 0):
	t0c = len( T0Count)
	ECA = []
	for i in range( t0c):
	    t0s = T0Count[i]
	    event_c = 0
	    dataone = datalist[i]
	    for y in range( len(dataone) ):
		if ( y >= ymin and y <= ymax):
		    for x in range( len(dataone[y]) ):
			if ( x >= xmin and x <= xmax):
			    events = dataone[y][x]
			    #if ( events != []):
                            if ( len( events )>0 ):
				if ( event_c == 0):
				    intensity_array = events
				else:
				    intensity_array = np.concatenate((intensity_array, events))
				event_c += 1
	    intensity_a, tof_array = np.histogram( intensity_array, bins=bins )
	    err_array = np.sqrt( intensity_a ) / float( t0s)
	    intensity_array = intensity_a / float( t0s)
	    print("Cell:", event_c)
	    hh = mm.HeaderBase()
	    hh.Add("RUNNUMBER", str(runNo))
	    hh.Add("XAxis", "TOF")
	    hh.Add("XLABEL", "TOF")
	    hh.Add("YLABEL", "Intensity")
	    hh.Add("TotalCount", float(intensity_array.sum()))
	    hh.Add("T0Count",t0s)
	    hh.Add("Label", str(i))
	    if ( a2th != -9999.9):
		hh.Add("A2TH", a2th)
	    EC  = mm.ElementContainer(hh)
	    EC.Add("TOF",tof_array.tolist(), "microsec")
	    EC.Add("Intensity", intensity_array.tolist(), "Counts")
	    EC.Add("Error", err_array.tolist(), "Counts")
	    EC.SetKeys("TOF","Intensity","Error")
	    ECA += [EC]
    else:
	t0l = len( T0Count)
	ECA = []
	for k in range( tol):
	    t0c = len( T0Count[k])
	    ECAA = []
	    for i in range( t0c):
		t0s = T0Count[k][i]
		event_c = 0
		dataone = datalist[k][i]
		for y in range( len(dataone) ):
		    if ( y >= ymin and y <= ymax):
			for x in range( len(dataone[y]) ):
			    if ( x >= xmin and x <= xmax):
				events = dataone[y][x]
				#if ( events != []):
                                if ( len( events) > 0):  #[inamura 180403]
				    if ( event_c == 0):
					intensity_array = events
				    else:
					intensity_array = np.concatenate((intensity_array, events))
				    event_c += 1
		intensity_a, tof_array = np.histogram( intensity_array, bins=bins )
		err_array = np.sqrt( intensity_a ) / float( t0s)
		intensity_array = intensity_a / float( t0s)
		# print "Cell:", event_c
		hh = mm.HeaderBase()
		hh.Add("RUNNUMBER", str(runNo))
		hh.Add("XAxis", "TOF")
		hh.Add("XLABEL", "TOF")
		hh.Add("YLABEL", "Intensity")
		hh.Add("TotalCount", float(intensity_array.sum()))
		hh.Add("T0Count",t0s)
		hh.Add("Label", str(i))
		if ( a2th != -9999.9):
		    hh.Add("A2TH", a2th)
		EC  = mm.ElementContainer(hh)
		EC.Add("TOF",tof_array.tolist(), "microsec")
		EC.Add("Intensity", intensity_array.tolist(), "Counts")
		EC.Add("Error", err_array.tolist(), "Counts")
		EC.SetKeys("TOF","Intensity","Error")
		ECAA += [EC]
	    ECA += [ECAA]
    return ECA

########################################
def GetHistMWPC0dDio(runStr='123924', initial_bin=10000.0,final_bin=38100.0,delta_bin=0.01, xmin=64, xmax=191, ymin=64, ymax=191):
    """
    Load EventData and convert to histogram for MWPC
    @param  runStr       (string) Run Number
    @param  initial_bin  (double) 
    @param  final_bin    (double) 
    @param  delta_bin    (double) 
    @param  xmin         (int)
    @param  xmax         (int)
    @param  ymin         (int)
    @param  ymax         (int)
    @retval ECA          (ElementContainer)
    """

    dioFlag = 2
    pixels = (256,256)

    runArray=runStr.split('+')
    for j in range( len( runArray)):
	runNo = int(runArray[j])
	datalone, T0Coone = mH.getEventDataArray( runNo, "MWPC", pixels, dioFlag)
	t0c = len( T0Coone)
	if j == 0:
	    datalist = datalone
	    T0Count = T0Coone
	else:
	    for i in range( t0c):
		T0Count[i] += T0Coone[i]
		dataone = datalone[i]
		for y in range( len(dataone) ):
		    for x in range( len(dataone[y]) ):
			if ( dataone[y][x] != []):
			    if ( datalist[i][y][x] != []):
				datalist[i][y][x] = np.concatenate((datalist[i][y][x], dataone[y][x]))
			    else:
				datalist[i][y][x] = dataone[y][x]

    runNo = int(runArray[0])
    if ( initial_bin < 0.0):
	initial_bin = 0.0
    if ( final_bin <= 0.0):
	final_bin = 80000.0
    if ( initial_bin >= final_bin):
	initila_bin = 0.0
    bins = getTofBin_DT_T_Constant(initial_bin,final_bin,delta_bin)
    t0c = len( T0Count)
    a2th = PickupCurpos(runNo, 'A2TH')
    ECA = []
    for i in range( t0c):
	t0s = T0Count[i]
	dataone = datalist[i]
	event_c = 0
	for y in range( len(dataone) ):
	    if ( y >= ymin and y <= ymax):
		for x in range( len(dataone[y]) ):
		    if ( x >= xmin and x <= xmax):
			events = dataone[y][x]
			if ( len( events) > 0):  # 2016-10-17 ##[inamura 180330]
			#if ( events != []):
			    if ( event_c == 0):
				intensity_array = events
			    else:
				intensity_array = np.concatenate((intensity_array, events))
			    event_c += 1
	intensity_a, tof_array = np.histogram( intensity_array, bins=bins )
	print("T0  :", t0s, " Cell:", event_c)
	err_array = np.sqrt( intensity_a ) / float( t0s)
	intensity_array = intensity_a / float( t0s)
	hh = mm.HeaderBase()
	hh.Add("RUNNUMBER", str(runNo))
	hh.Add("XAxis", "TOF")
	hh.Add("XLABEL", "TOF")
	hh.Add("YLABEL", "Intensity")
	hh.Add("TotalCount", float(intensity_array.sum()))
	hh.Add("T0Count",t0s)
	if ( t0c > 1):
	    if ( i == 0):
		hh.Add("Label", "mp")
	    else:
		if ( i == 1): 
		    hh.Add("Label", "pp")
		else:
		    if ( i == 2):
			hh.Add("Label", "mm")
		    else:
			hh.Add("Label", "pm")
	if ( a2th != -9999.9):
	    hh.Add("A2TH", a2th)
        EC  = mm.ElementContainer(hh)
	EC.Add("TOF",tof_array.tolist(), "microsec")
	EC.Add("Intensity", intensity_array.tolist(), "Counts")
	EC.Add("Error", err_array.tolist(), "Counts")
	EC.SetKeys("TOF","Intensity","Error")
	ECA += [EC]

    return ECA

########################################
def GetHistMWPC0dDiox(runNo=123901, initial_bin=10000.0,final_bin=38100.0,delta_bin=0.01, xmin=64, xstep=4, ymin=64, ymax=191):
    """
    Load EventData and convert to histogram for MWPC
    @param  runNo       (int) Run Number
    @param  initial_bin (double) 
    @param  final_bin   (double) 
    @param  delta_bin   (double) or width_of_bin 
    @param  xmin        (int)
    @param  xstep       (int)
    @param  ymin        (int)
    @param  ymax        (int)
    """

    dioFlag = 2
    pixels = (256,256)
    datalist, T0Count = mH.getEventDataArray( runNo, "MWPC", pixels, dioFlag)

    if ( initial_bin < 0.0):
	initial_bin = 0.0
    if ( final_bin <= 0.0):
	final_bin = 80000.0
    if ( initial_bin >= final_bin):
	initila_bin = 0.0
    if ( ymin < 0 or ymin > 255):
	ymin = 0
    if ( ymax < 0 or ymax > 255):
	ymax = 255
    if ( xmin < 0 or xmin > 255):
	xmin = 0
    if ( xstep < 1 or xstep > 255):
	xstep = 4

    if ( delta_bin >= 1.0):
	bin = getTofBin_T_Constant(int(initial_bin),int(final_bin),int(delta_bin))
	bins = map(float, bin)
    else:
	bins = getTofBin_DT_T_Constant(initial_bin,final_bin,delta_bin)
    t0c = len( T0Count)
    for i in range( t0c):
	if ( i == 0):
	    #f = open("/usr/local/mlf/VNR/ana/xml/"+str(runNo).zfill(6)+"_mp.dat", 'w')
            f = open( os.path.join( getVNRConst.GetUserDir(),"ana","xml",str(runNo).zfill(6)+"_mp.dat"), 'w') #[inamura 180403]
	else:
	    if ( i == 1):
		#f = open("/usr/local/mlf/VNR/ana/xml/"+str(runNo).zfill(6)+"_pp.dat", 'w')
                f = open( os.path.join( getVNRConst.GetUserDir(),"ana","xml",str(runNo).zfill(6)+"_pp.dat"), 'w') #[inamura 180403]
	    else:
		if ( i == 2):
		    #f = open("/usr/local/mlf/VNR/ana/xml/"+str(runNo).zfill(6)+"_mm.dat", 'w')
                    f = open( os.path.join( getVNRConst.GetUserDir(),"ana","xml",str(runNo).zfill(6)+"_mm.dat"), 'w') #[inamura 180403]
		else:
		    #f = open("/usr/local/mlf/VNR/ana/xml/"+str(runNo).zfill(6)+"_pm.dat", 'w')
                    f = open( os.path.join( getVNRConst.GetUserDir(),"ana","xml",str(runNo).zfill(6)+"_pm.dat"), 'w') #[inamura 180403]
	f.write("tof_%d\tref_%d\terr_%d\n" % ( runNo, runNo, runNo))
	t0s = T0Count[i]
	dataone = datalist[i]
	hist_n = ( (255 - xmin) / xstep) + 1
	intens = [np.array([])] * hist_n
	for y in range( ymin, ymax + 1):
	    for x0 in range( hist_n):
		for xs in range( 0, xstep):
		    x = xmin + xstep * x0 + xs
		    events = dataone[y][x]
		    #if ( events != []):
                    if ( len( events) > 0):  #[inamura 180403]
			intens[x0] = np.concatenate((intens[x0], events))
	print("Histogram n:", hist_n)
	for x0 in range( hist_n):
	    if ( intens[x0] != []):
		intensity_a, tof_array = np.histogram( intens[x0], bins=bins )
		err_array = np.sqrt( intensity_a )
		tof_a = (tof_array[1:] + tof_array[:-1]) * 0.5
		f.write("\nposition:%d  x = (%d, %d)\n" % ( x0, xmin + xstep * x0, xmin + xstep * (x0 + 1) - 1))
		for j in range( len( tof_a)):
		    f.write("%.12g\t%.16g\t%.16g\n" % (tof_a[j], intensity_a[j], err_array[j]))

	f.close()

########################################
def GetHistMWPCDetector(runNo=123260, initial_bin=100.0,final_bin=40000.0,delta_bin=100.0, binType=0, dioFlag=-1):
    """
    Load EventData and convert to histogram for MWPC
    @param  runNo    	(int) Run Number
    @param  initial_bin  (double) 
    @param  final_bin    (double) 
    @param  delta_bin    (double) 
    @param  binType      (int)
    @param  dioFlag      (int)  
    @retval DAT (ElementContainerMatrix)
    """

    pixels = (256,256)
    datalist, T0Count = mH.getEventDataArray( runNo, "MWPC", pixels, dioFlag)

    DAT = mm.ElementContainerMatrix()
    instrument = os.environ["UTSUSEMI_INST_CODE"]
    DAT.AddToHeader("INSTRUMENT", instrument )
    DAT.AddToHeader("RUNNUMBER", str(runNo))
    bank_v = mm.MakeInt4Vector()
    bank_l = mm.MakeInt4Vector()
    for i in range( len(T0Count)):
	bank_v.append( i ) 
	bank_l.append( 256 ) 
    DAT.AddToHeader("BANKIDLIST", bank_v )
    DAT.AddToHeader("BANKSIZELIST", bank_l )
    bank_n = mm.MakeStringVector()
    if i == 0:
	bank_n.append('Bank0')
    else:
	if i == 1:
	    bank_n.append('BankM')
	    bank_n.append('BankP')
	else:
	    bank_n.append('BankMP')
	    bank_n.append('BankPP')
	    bank_n.append('BankMM')
	    bank_n.append('BankPM')
    DAT.AddToHeader("BANKNAMELIST", bank_n )
    if ( initial_bin < 0.0):
	initial_bin = 0.0
    if ( final_bin <= 0.0):
	final_bin = 80000.0
    if ( initial_bin >= final_bin):
	initila_bin = 0.0
    if ( binType == 0):
	if ( delta_bin < 5.0):
	    delta_bin = 10.0
	bins = getTofBin_T_Constant( int(initial_bin),int(final_bin),int(delta_bin))
    else:
	if ( delta_bin < 0.002):
	    delta_bin = 0.01
	bins = getTofBin_DT_T_Constant(initial_bin,final_bin,delta_bin)

    print("Make ElementContainerMatrix")
    print("binType	>> ", binType)
    print("initial bin	>> ", initial_bin)
    print("final bin	>> ", final_bin)
    print("delta bin	>> ", delta_bin, "(", len(bins), "bins)")

    for i in range( len(T0Count)):

	dataone = datalist[i]

	for x in range( 256):
	    eca = mm.ElementContainerArray()
	    eca.AddToHeader("DETID", x + i*256)
	    eca.AddToHeader("BANKID",i)
	    eca.AddToHeader("INDEXINBANK",x)
	    eca.AddToHeader("MASKED",0 )

	    for y in range( len(dataone) ):
		# make histogarm use numpy function
		events = dataone[y][x]
		intensity_array, tof_array = np.histogram( events, bins=bins )
		# make error list from intensity
		err_array = np.sqrt( intensity_array )

		# make ElementContainer
		ec = mm.ElementContainer()
		ec.Add("TOF",tof_array.tolist(), "microsec")
		ec.Add("Intensity", intensity_array.tolist(), "Counts")
		ec.Add("Error", err_array.tolist(), "Counts")
		ec.SetKeys("TOF","Intensity","Error")

		# add ec to eca(ElementContainerArray)
		eca.Add(ec)

	    #if ( (y & 15) == 15):
	#	print '*%d' % (y),
	    # add eca to ecm(ElementContainerMatrix)
	    DAT.Add(eca)

	print("bank:(%d) end." % (i))
    print("runNo.(%d) end." % (runNo))

    return DAT

########################################
def GetHistRPMTDetector(runNo=130494, initial_bin=100.0,final_bin=40000.0,delta_bin=100.0, binType=0, dioFlag=-1):
    """
    Load EventData and convert to histogram for MWPC
    @param  runNo    	(int) Run Number
    @param  initial_bin  (double) 
    @param  final_bin    (double) 
    @param  delta_bin    (double) 
    @param  binType      (int)
    @param  dioFlag      (int)  
    @retval DAT (ElementContainerMatrix)
    """

    pixels = (256,256)
    datalist, T0Count = mH.getEventDataArray( runNo, "RPMT", pixels, dioFlag)

    DAT = mm.ElementContainerMatrix()
    instrument = os.environ["UTSUSEMI_INST_CODE"]
    DAT.AddToHeader("INSTRUMENT", instrument )
    DAT.AddToHeader("RUNNUMBER", str(runNo))
    bank_v = mm.MakeInt4Vector()
    bank_l = mm.MakeInt4Vector()
    for i in range( len(T0Count)):
	bank_v.append( i ) 
	bank_l.append( 256 ) 
    DAT.AddToHeader("BANKIDLIST", bank_v )
    DAT.AddToHeader("BANKSIZELIST", bank_l )
    bank_n = mm.MakeStringVector()
    if i == 0:
	bank_n.append('Bank0')
    else:
	if i == 1:
	    bank_n.append('BankM')
	    bank_n.append('BankP')
	else:
	    bank_n.append('BankMP')
	    bank_n.append('BankPP')
	    bank_n.append('BankMM')
	    bank_n.append('BankPM')
    DAT.AddToHeader("BANKNAMELIST", bank_n )
    if ( initial_bin < 0.0):
	initial_bin = 0.0
    if ( final_bin <= 0.0):
	final_bin = 80000.0
    if ( initial_bin >= final_bin):
	initila_bin = 0.0
    if ( binType == 0):
	if ( delta_bin < 5.0):
	    delta_bin = 10.0
	bins = getTofBin_T_Constant( int(initial_bin),int(final_bin),int(delta_bin))
    else:
	if ( delta_bin < 0.002):
	    delta_bin = 0.01
	bins = getTofBin_DT_T_Constant(initial_bin,final_bin,delta_bin)

    print("Make ElementContainerMatrix")
    print("binType	>> ", binType)
    print("initial bin	>> ", initial_bin)
    print("final bin	>> ", final_bin)
    print("delta bin	>> ", delta_bin, "(", len(bins), "bins)")

    for i in range( len(T0Count)):

	dataone = datalist[i]

	for x in range( 256):
	    eca = mm.ElementContainerArray()
	    eca.AddToHeader("DETID", x + i*512)
	    eca.AddToHeader("BANKID",i)
	    eca.AddToHeader("INDEXINBANK",x)
	    eca.AddToHeader("MASKED",0 )

	    for y in range( len(dataone) ):
		# make histogarm use numpy function
		events = dataone[y][x]
		intensity_array, tof_array = np.histogram( events, bins=bins )
		# make error list from intensity
		err_array = np.sqrt( intensity_array )

		# make ElementContainer
		ec = mm.ElementContainer()
		ec.Add("TOF",tof_array.tolist(), "microsec")
		ec.Add("Intensity", intensity_array.tolist(), "Counts")
		ec.Add("Error", err_array.tolist(), "Counts")
		ec.SetKeys("TOF","Intensity","Error")

		# add ec to eca(ElementContainerArray)
		eca.Add(ec)

	    #if ( (y & 15) == 15):
	#	print '*%d' % (y),
	    # add eca to ecm(ElementContainerMatrix)
	    DAT.Add(eca)

	print("bank:(%d) end." % (i))
    print("runNo.(%d) end." % (runNo))

    return DAT

########################################
def GetHistMWPCDetectorT(runNo=123260, initial_bin=100.0,final_bin=40000.0, dioFlag=-1, startsec=0, endsec=-1, secwidth=60):
    """
    Load EventData and convert to histogram for MWPC
    @param  runNo    	(int) Run Number
    @param  initial_bin  (double) 
    @param  final_bin    (double) 
    @param  dioFlag      (int)  
    @param  startsec     (int)  
    @param  endsec       (int)  
    @param  secwidth     (int)  
    @retval DAT (ElementContainerMatrix)
    """

    pixels = (256,256)
    if ( initial_bin < 0.0):
	initial_bin = 0.0
    if ( final_bin <= 0.0):
	final_bin = 80000.0
    if ( initial_bin >= final_bin):
	initila_bin = 0.0

    datalist, T0Count, neutime = mE.getEventDataArrayTime( runNo, "MWPC", pixels, dioFlag, startsec, endsec, initial_bin, final_bin)

    DAT = mm.ElementContainerMatrix()
    instrument = os.environ["UTSUSEMI_INST_CODE"]
    DAT.AddToHeader("INSTRUMENT", instrument )
    DAT.AddToHeader("RUNNUMBER", str(runNo))
    bank_v = mm.MakeInt4Vector()
    bank_l = mm.MakeInt4Vector()
    for i in range( len(T0Count)):
	bank_v.append( i ) 
	bank_l.append( 256 ) 
    DAT.AddToHeader("BANKIDLIST", bank_v )
    DAT.AddToHeader("BANKSIZELIST", bank_l )
    bank_n = mm.MakeStringVector()
    if i == 0:
	bank_n.append('Bank0')
    else:
	if i == 1:
	    bank_n.append('BankM')
	    bank_n.append('BankP')
	else:
	    bank_n.append('BankMP')
	    bank_n.append('BankPP')
	    bank_n.append('BankMM')
	    bank_n.append('BankPM')
    DAT.AddToHeader("BANKNAMELIST", bank_n )

    if ( endsec < 0):
	endsec = int( neutime)+ secwidth
    if ( startsec >= endsec):
	startsec = 0
    if ( secwidth < 1):
	secwidth = ( endsec - startsec) / 256 + 1

    print("Make ElementContainerMatrix")
    #print "binType	>> ", binType
    print("initial bin	>> ", initial_bin)
    print("final bin	>> ", final_bin)
    print("start sec.	>> ", startsec)
    print("end sec. 	>> ", endsec)
    print("sec.width	>> ", secwidth)
    #print "delta bin	>> ", delta_bin, "(", len(bins), "bins)"

    bins = getTofBin_T_Constant( startsec, endsec, secwidth)

    for i in range( len(T0Count)):

	dataone = datalist[i]

	for x in range( 256):
	    eca = mm.ElementContainerArray()
	    eca.AddToHeader("DETID", x + i*256)
	    eca.AddToHeader("BANKID",i)
	    eca.AddToHeader("INDEXINBANK",x)
	    eca.AddToHeader("MASKED",0 )

	    for y in range( len(dataone) ):
		# make histogarm use numpy function
		events = dataone[y][x]
		intensity_array, tof_array = np.histogram( events, bins=bins )
		# make error list from intensity
		err_array = np.sqrt( intensity_array )

		# make ElementContainer
		ec = mm.ElementContainer()
		#ec.Add("TOF",tof_array.tolist(), "second")
		ec.Add("SEC",tof_array.tolist(), "second")
		ec.Add("Intensity", intensity_array.tolist(), "Counts")
		ec.Add("Error", err_array.tolist(), "Counts")
		#ec.SetKeys("TOF","Intensity","Error")
		ec.SetKeys("SEC","Intensity","Error")

		# add ec to eca(ElementContainerArray)
		eca.Add(ec)

	    #if ( (y & 15) == 15):
	#	print '*%d' % (y),
	    # add eca to ecm(ElementContainerMatrix)
	    DAT.Add(eca)

	print("bank:(%d) end." % (i))
    print("runNo.(%d) end." % (runNo))

    return DAT

########################################
def GetHistMWPCTOF(runNo=125523, initial_bin=10000,final_bin=38100,xmin=32, xmax=224, ymin=32, ymax=224, bank=-1):
    """
    Load EventData and convert to histogram for MWPC
    @param  runNo        (int) Run Number
    @param  initial_bin  (int) 
    @param  final_bin    (int) 
    @param  xmin         (int)
    @param  xmax         (int)
    @param  ymin         (int)
    @param  ymax         (int)
    @param  bank         (int)
    @retval ECA          (ElementContainerArray)
    """

    pixels = (256,256)
    if ( bank < 0):
	dioFlag = -1
	bank = 0
    else:
	dioFlag = 1
 
    datalist, T0Count = mH.getEventDataArray( runNo, "MWPC", pixels, dioFlag)

    if ( initial_bin < 1.0):
	initial_bin = 1.0
    if ( final_bin <= 1.0):
	final_bin = 38100.0
    if ( initial_bin >= final_bin):
	initila_bin = 1.0

    #a2th = PickupCurpos(runNo, 'A2TH')
    #if ( a2th != -9999.9):
    #	angle = float( a2th) / 2.0
    #else:
    #	angle = 0.3

    print("Make ElementContainerMatrix")
    print("initial bin	>> ", initial_bin)
    print("final bin	>> ", final_bin)
    print("dioFlag  	>> ", dioFlag)
    # print "bank    	>> ", bank

    #pix_per = 0.5

    t0c = len( T0Count)
    tstep = 158
    bin_z = [ float( tstep * j) for j in range(257)]

    ECA = mm.ElementContainerArray()
    instrument = os.environ["UTSUSEMI_INST_CODE"]
    ECA.AddToHeader("INSTRUMENT", instrument )
    ECA.AddToHeader("RUNNUMBER", str(runNo))
    for i in range( t0c):
      if ( i == bank):
	t0s = T0Count[i]
	# event_c = 0
	dataone = datalist[i]
	data=[[[] for j in range(256)] for k in range(256)]
	for y in range( len(dataone) ):
	    if ( y >= ymin and y <= ymax):
		for x in range( len(dataone[y]) ):
		    if ( x >= xmin and x <= xmax):
			events = dataone[y][x]
			eventn = len( events)
			if ( eventn > 0):
			    for k in range( eventn):
				tof = events[k]
				if ( tof >= initial_bin and tof <= final_bin):
				    iz = int( tof / tstep)
				    data[iz][x].append( tof)
	bin_x = [ float( j) for j in range(257)] 
	for z in range(256):
            int_list = data[z]
	    int_list_at_px = [ float( len( x)) for x in int_list ]
	    err_list_at_px = [ math.sqrt(e) for e in int_list_at_px ]
	    ec = mm.ElementContainer()
	    ec.Add( "X", bin_x)
	    ec.Add( "Intensity", int_list_at_px )
	    ec.Add( "Error", err_list_at_px )
	    ec.SetKeys("X","Intensity","Error")
	    xr_v = mm.MakeDoubleVector()
	    xr_v.append( bin_z[z] )
	    xr_v.append( bin_z[z + 1] )
	    ec.AddToHeader( "XRANGE", xr_v )
	    ECA.Add(ec)

	p=mp.M2Plot(ECA)
	p.SetXLabel( 'TOF (microsec)')
	p.SetYLabel( 'Detector PositionX')
	p.SetXLog(True)

    # import Cmm
    # Cmm.SaveDataToDump( ECA, "/home/vnradmin/", "sampledata")
    return ECA

########################################
def GetHistMWPCX(runNo=125523, initial_bin=10000.0,final_bin=38100.0,angle=-1.0, xord=-1, yord=-1, dioFlag=-1, bank=0):
    """
    Load EventData and convert to histogram for MWPC
    @param  runNo        (int) Run Number
    @param  initial_bin  (double) 
    @param  final_bin    (double) 
    @param  angle        (double) 
    @param  xord         (int)
    @param  yord         (int)
    @param  dioFlag      (int)
    @param  bank         (int)
    @retval ECA          (ElementContainerArray)
    """

    pixels = (256,256)
    datalist, T0Count = mH.getEventDataArray( runNo, "MWPC", pixels, dioFlag)

    if ( initial_bin < 1.0):
	initial_bin = 1.0
    if ( final_bin <= 1.0):
	final_bin = 38100.0
    if ( initial_bin >= final_bin):
	initila_bin = 1.0

    a2th = PickupCurpos(runNo, 'A2TH')
    if ( angle < 0.0):
	if ( a2th != -9999.9):
	    angle = float( a2th) / 2.0
	else:
	    angle = 0.3
    if ( dioFlag == -1):
	bank = 0

    print("Make ElementContainerMatrix")
    print("initial bin	>> ", initial_bin)
    print("final bin	>> ", final_bin)
    print("angle    	>> ", angle)
    print("dioFlag  	>> ", dioFlag)
    print("bank    	>> ", bank)

    # xmin,max ymin,max constant
    xmin = 32
    xmax = 224
    ymin = 32
    ymax = 224
    pix_per = 0.5

    t0c = len( T0Count)
    if ( xord == -1 and yord == -1):
	nmax = 0
	for i in range( t0c):
	    if ( i == bank):
		dataone = datalist[i]
		for y in range( len(dataone) ):
		    if ( y >= ymin and y <= ymax):
			for x in range( len(dataone[y])):
			    if ( x >= xmin and x <= xmax):
				n = len(dataone[y][x])
				n += len(dataone[y-1][x-1])
				n += len(dataone[y-1][x])
				n += len(dataone[y][x-1])
				n += len(dataone[y+1][x])
				n += len(dataone[y][x+1])
				n += len(dataone[y+1][x+1])
				n += len(dataone[y+1][x-1])
				n += len(dataone[y-1][x+1])
				if ( n > nmax):
				    nmax = n
				    xord = x
				    yord = y
	print("Auto Origin set")
    print("x origin   	>> ", xord)
    print("y origin 	>> ", yord)

    QC = 2.0 * math.pi * (18.0e7/3955.6)

    qxmax = QC * ( math.cos(math.pi * angle/180.0 + math.atan(pix_per * float(xmax - xord)/2500.0)) - math.cos(math.pi * angle/180.0)) / initial_bin
    qxmin = qxmax
    xvar = [ xmin, xmax]
    yvar = [ ymin, ymax]
    bins = [initial_bin, final_bin]
    for x in xvar:
	for y in yvar:
	    for bin in bins:
		QxC = QC * ( math.cos(math.pi * angle/180.0 + math.atan(pix_per * float(x - xord)/2500.0))  - math.cos(math.pi * angle/180.0)) / bin
		if ( qxmax < QxC):
		    qxmax = QxC
		if ( qxmin > QxC):
		    qxmin = QxC
    if ( qxmax < 0.0):
	qxmax = 0.0

    qx_step = ( qxmax - qxmin) / 256.0
    bin_x = [ (qxmin + qx_step * float( j)) for j in range(257)] 

    qzmax = QC * (math.sin( math.pi * angle / 180.0) + math.sin( math.pi * angle/180.0 + math.atan(pix_per * float( xmax - xord)/2500.0))) / initial_bin
    qzmin = qzmax
    for x in xvar:
	for bin in bins:
	    QzC = QC * (math.sin( math.pi * angle / 180.0) + math.sin( math.pi * angle/180.0 + math.atan(pix_per * float( x - xord)/2500.0))) / bin
	    if ( qzmax < QzC):
		qzmax = QzC
	    if ( qzmin > QzC):
		qzmin = QzC
    if ( qzmin < 5e-2):
	qzmin = 5e-2
	if ( qzmax < qzmin):
	    qzmax = qzmin + 1
    qmin = math.log( qzmin)
    qmax = math.log( qzmax)
    qstep = ( qmax - qmin ) / 256.0
    bin_z = [ math.exp( qmin + qstep * float( j)) for j in range(257)]
    # qz_step = (qzmax - qzmin) / 256.0
    # bin_z = [ (qzmin + qz_step * float( j)) for j in range(257)]

    print("Qx min  	>> ", qxmin)
    print("Qx max  	>> ", qxmax)
    print("Qz min  	>> ", qzmin)
    print("Qz max  	>> ", qzmax)

    ECA = mm.ElementContainerArray()
    instrument = os.environ["UTSUSEMI_INST_CODE"]
    ECA.AddToHeader("INSTRUMENT", instrument )
    ECA.AddToHeader("RUNNUMBER", str(runNo))
    for i in range( t0c):
      if ( i == bank):
	t0s = T0Count[i]
	# event_c = 0
	dataone = datalist[i]
	data=[[[] for j in range(256)] for k in range(256)]
	for y in range( len(dataone) ):
	    if ( y >= ymin and y <= ymax):
		for x in range( len(dataone[y]) ):
		    if ( x >= xmin and x <= xmax):
			events = dataone[y][x]
			eventn = len( events)
			if ( eventn > 0):
			    # QxC = QC * ( math.cos(math.pi * angle/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) * math.cos(math.atan(pix_per * float(y - yord)/2500.0)) - math.cos(math.pi * angle/180.0))
			    QzC = QC * ( math.sin(math.pi * angle/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) + math.sin(math.pi * angle/180.0))
			    for k in range( eventn):
				tof = float( events[k])
				if ( tof >= initial_bin and tof <= final_bin):
				    iz = 0
				    Qz = QzC / tof
				    if ( Qz >= qzmin):
					while 1:
					    if ( Qz < bin_z[iz+1]): 
						break
					    iz += 1
					    if iz >= 256:
						break
					if ( iz < 256):
					    data[iz][x].append( tof)
	bin_x = [ float( j) for j in range(257)] 
	for z in range(256):
            int_list = data[z]
	    int_list_at_px = [ float( len( x)) for x in int_list ]
	    err_list_at_px = [ math.sqrt(e) for e in int_list_at_px ]
	    ec = mm.ElementContainer()
	    ec.Add( "X", bin_x)
	    ec.Add( "Intensity", int_list_at_px )
	    ec.Add( "Error", err_list_at_px )
	    ec.SetKeys("X","Intensity","Error")
	    xr_v = mm.MakeDoubleVector()
	    xr_v.append( bin_z[z] )
	    xr_v.append( bin_z[z + 1] )
	    ec.AddToHeader( "XRANGE", xr_v )
	    ECA.Add(ec)

	p=mp.M2Plot(ECA)
	p.SetXLabel( 'qz(nm^(-1))')
	p.SetYLabel( 'Detector Position')
	p.SetXLog(True)

    # import Cmm
    # Cmm.SaveDataToDump( ECA, "/home/vnradmin/", "sampledata")
    return ECA

########################################
def GetHistMWPCX2(runNo=125523, initial_bin=10000.0,final_bin=38100.0,angle=0.35, angle2=0.0, xord=95, yord=128):
    """
    Load EventData and convert to histogram for MWPC
    @param  runNo        (int) Run Number
    @param  initial_bin  (double) 
    @param  final_bin    (double) 
    @param  angle        (double) 
    @param  angle2       (double) 
    @param  xord         (int)
    @param  yord         (int)
    @retval ECA          (ElementContainerArray)
    """

    pixels = (256,256)
    dioFlag = -1
    bank = 0
    datalist, T0Count = mH.getEventDataArray( runNo, "MWPC", pixels, dioFlag)

    if ( initial_bin < 1.0):
	initial_bin = 1.0
    if ( final_bin <= 1.0):
	final_bin = 38100.0
    if ( initial_bin >= final_bin):
	initila_bin = 1.0

    #a2th = PickupCurpos(runNo, 'A2TH')
    #if ( angle < 0.0):
    #	if ( a2th != -9999.9):
    #	    angle = float( a2th) / 2.0
    #	else:
    #	    angle = 0.3
    #if ( dioFlag == -1):
    #	bank = 0

    print("Make ElementContainerMatrix")
    print("initial bin	>> ", initial_bin)
    print("final bin	>> ", final_bin)
    print("angle    	>> ", angle)
    print("angle2   	>> ", angle2)
    #print "dioFlag  	>> ", dioFlag
    #print "bank    	>> ", bank

    # xmin,max ymin,max constant
    xmin = 8
    xmax = 248
    ymin = 32
    ymax = 224
    pix_per = 0.5

    t0c = len( T0Count)
    if ( xord == -1 and yord == -1):
	nmax = 0
	for i in range( t0c):
	    if ( i == bank):
		dataone = datalist[i]
		for y in range( len(dataone) ):
		    if ( y >= ymin and y <= ymax):
			for x in range( len(dataone[y])):
			    if ( x >= xmin and x <= xmax):
				n = len(dataone[y][x])
				n += len(dataone[y-1][x-1])
				n += len(dataone[y-1][x])
				n += len(dataone[y][x-1])
				n += len(dataone[y+1][x])
				n += len(dataone[y][x+1])
				n += len(dataone[y+1][x+1])
				n += len(dataone[y+1][x-1])
				n += len(dataone[y-1][x+1])
				if ( n > nmax):
				    nmax = n
				    xord = x
				    yord = y
	print("Auto Origin set")
    print("x origin   	>> ", xord)
    print("y origin 	>> ", yord)

    QC = 2.0 * math.pi * (18.0e7/3955.6)

    qxmax = QC * ( math.cos(math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float(xmax - xord)/2500.0)) - math.cos(math.pi * angle/180.0)) / initial_bin
    qxmin = qxmax
    xvar = [ xmin, xmax]
    yvar = [ ymin, ymax]
    bins = [initial_bin, final_bin]
    for x in xvar:
	for y in yvar:
	    for bin in bins:
		QxC = QC * ( math.cos(math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float(x - xord)/2500.0))  - math.cos(math.pi * angle/180.0)) / bin
		if ( qxmax < QxC):
		    qxmax = QxC
		if ( qxmin > QxC):
		    qxmin = QxC
    if ( qxmax < 0.0):
	qxmax = 0.0

    qx_step = ( qxmax - qxmin) / 256.0
    bin_x = [ (qxmin + qx_step * float( j)) for j in range(257)] 

    qzmax = QC * (math.sin( math.pi * angle / 180.0) + math.sin( math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float( xmax - xord)/2500.0))) / initial_bin
    qzmin = qzmax
    for x in xvar:
	for bin in bins:
	    QzC = QC * (math.sin( math.pi * angle / 180.0) + math.sin( math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float( x - xord)/2500.0))) / bin
	    if ( qzmax < QzC):
		qzmax = QzC
	    if ( qzmin > QzC):
		qzmin = QzC
    if ( qzmin < 5e-2):
	qzmin = 5e-2
	if ( qzmax < qzmin):
	    qzmax = qzmin + 1
    qmin = math.log( qzmin)
    qmax = math.log( qzmax)
    qstep = ( qmax - qmin ) / 256.0
    bin_z = [ math.exp( qmin + qstep * float( j)) for j in range(257)]
    # qz_step = (qzmax - qzmin) / 256.0
    # bin_z = [ (qzmin + qz_step * float( j)) for j in range(257)]

    print("Qx min  	>> ", qxmin)
    print("Qx max  	>> ", qxmax)
    print("Qz min  	>> ", qzmin)
    print("Qz max  	>> ", qzmax)

    ECA = mm.ElementContainerArray()
    instrument = os.environ["UTSUSEMI_INST_CODE"]
    ECA.AddToHeader("INSTRUMENT", instrument )
    ECA.AddToHeader("RUNNUMBER", str(runNo))
    for i in range( t0c):
      if ( i == bank):
	t0s = T0Count[i]
	# event_c = 0
	dataone = datalist[i]
	data=[[[] for j in range(256)] for k in range(256)]
	for y in range( len(dataone) ):
	    if ( y >= ymin and y <= ymax):
		for x in range( len(dataone[y]) ):
		    if ( x >= xmin and x <= xmax):
			events = dataone[y][x]
			eventn = len( events)
			if ( eventn > 0):
			    # QxC = QC * ( math.cos(math.pi * angle/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) * math.cos(math.atan(pix_per * float(y - yord)/2500.0)) - math.cos(math.pi * angle/180.0))
			    QzC = QC * ( math.sin(math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) + math.sin(math.pi * angle/180.0))
			    for k in range( eventn):
				tof = float( events[k])
				if ( tof >= initial_bin and tof <= final_bin):
				    iz = 0
				    Qz = QzC / tof
				    if ( Qz >= qzmin):
					while 1:
					    if ( Qz < bin_z[iz+1]): 
						break
					    iz += 1
					    if iz >= 256:
						break
					if ( iz < 256):
					    data[iz][x].append( tof)
	bin_x = [ float( j) for j in range(257)] 
	for z in range(256):
            int_list = data[z]
	    int_list_at_px = [ float( len( x)) for x in int_list ]
	    err_list_at_px = [ math.sqrt(e) for e in int_list_at_px ]
	    ec = mm.ElementContainer()
	    ec.Add( "X", bin_x)
	    ec.Add( "Intensity", int_list_at_px )
	    ec.Add( "Error", err_list_at_px )
	    ec.SetKeys("X","Intensity","Error")
	    xr_v = mm.MakeDoubleVector()
	    xr_v.append( bin_z[z] )
	    xr_v.append( bin_z[z + 1] )
	    ec.AddToHeader( "XRANGE", xr_v )
	    ECA.Add(ec)

	p=mp.M2Plot(ECA)
	p.SetXLabel( 'qz(nm^(-1))')
	p.SetYLabel( 'Detector Position')
	p.SetXLog(True)

    # import Cmm
    # Cmm.SaveDataToDump( ECA, "/home/vnradmin/", "sampledata")
    return ECA

########################################
def GetHistMWPCQy(runNo=125523, initial_bin=10000.0,final_bin=38100.0,angle=-1.0, xord=-1, yord=-1, dioFlag=-1, bank=0):
    """
    Load EventData and convert to histogram for MWPC
    @param  runNo        (int) Run Number
    @param  initial_bin  (double) 
    @param  final_bin    (double) 
    @param  angle        (double) 
    @param  xord         (int)
    @param  yord         (int)
    @param  dioFlag      (int)
    @param  bank         (int)
    @retval ECA          (ElementContainerArray)
    """

    pixels = (256,256)
    datalist, T0Count = mH.getEventDataArray( runNo, "MWPC", pixels, dioFlag)

    if ( initial_bin < 1.0):
	initial_bin = 1.0
    if ( final_bin <= 1.0):
	final_bin = 38100.0
    if ( initial_bin >= final_bin):
	initila_bin = 1.0

    a2th = PickupCurpos(runNo, 'A2TH')
    if ( angle < 0.0):
	if ( a2th != -9999.9):
	    angle = float( a2th) / 2.0
	else:
	    angle = 0.3
    if ( dioFlag == -1):
	bank = 0

    print("Make ElementContainerMatrix")
    print("initial bin	>> ", initial_bin)
    print("final bin	>> ", final_bin)
    print("angle    	>> ", angle)
    print("dioFlag  	>> ", dioFlag)
    print("bank    	>> ", bank)

    # xmin,max ymin,max constant
    xmin = 32
    xmax = 224
    ymin = 32
    ymax = 224
    pix_per = 0.5

    t0c = len( T0Count)
    if ( xord == -1 and yord == -1):
	nmax = 0
	for i in range( t0c):
	    if ( i == bank):
		dataone = datalist[i]
		for y in range( len(dataone) ):
		    if ( y >= ymin and y <= ymax):
			for x in range( len(dataone[y])):
			    if ( x >= xmin and x <= xmax):
				n = len(dataone[y][x])
				n += len(dataone[y-1][x-1])
				n += len(dataone[y-1][x])
				n += len(dataone[y][x-1])
				n += len(dataone[y+1][x])
				n += len(dataone[y][x+1])
				n += len(dataone[y+1][x+1])
				n += len(dataone[y+1][x-1])
				n += len(dataone[y-1][x+1])
				if ( n > nmax):
				    nmax = n
				    xord = x
				    yord = y
	print("Auto Origin set")
    print("x origin   	>> ", xord)
    print("y origin 	>> ", yord)

    QC = 2.0 * math.pi * (18.0e7/3955.6)

    qxmax = QC * ( math.cos(math.pi * angle/180.0 + math.atan(pix_per * float(xmax - xord)/2500.0)) * math.cos(math.atan(pix_per * float(ymax - yord)/2500.0)) - math.cos(math.pi * angle/180.0)) / initial_bin
    qxmin = qxmax
    xvar = [ xmin, xmax]
    yvar = [ ymin, ymax]
    bins = [initial_bin, final_bin]
    for x in xvar:
	for y in yvar:
	    for bin in bins:
		QxC = QC * ( math.cos(math.pi * angle/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) * math.cos(math.atan(pix_per * float(y - yord)/2500.0)) - math.cos(math.pi * angle/180.0)) / bin
		if ( qxmax < QxC):
		    qxmax = QxC
		if ( qxmin > QxC):
		    qxmin = QxC
    if ( qxmax < 0.0):
	qxmax = 0.0

    qx_step = ( qxmax - qxmin) / 256.0
    bin_x = [ (qxmin + qx_step * float( j)) for j in range(257)] 

    qymax = QC *  math.cos(math.pi * angle/180.0 + math.atan(pix_per * float(xmin - xord)/2500.0)) * math.sin(math.atan(pix_per * float(ymin - yord)/2500.0)) / initial_bin
    qymin = qymax
    for x in xvar:
	for y in yvar:
	    for bin in bins:
		QyC = QC *  math.cos(math.pi * angle/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) * math.sin(math.atan(pix_per * float(y - yord)/2500.0)) / bin
		if ( qymax < QyC):
		    qymax = QyC
		if ( qymin > QyC):
		    qymin = QyC
    qy_step = (qymax - qymin) / 256.0
    bin_y = [ (qymin + qy_step * float( j)) for j in range(257)]

    qzmax = QC * (math.sin( math.pi * angle / 180.0) + math.sin( math.pi * angle/180.0 + math.atan(pix_per * float( xmax - xord)/2500.0))) / initial_bin
    qzmin = qzmax
    for x in xvar:
	for bin in bins:
	    QzC = QC * (math.sin( math.pi * angle / 180.0) + math.sin( math.pi * angle/180.0 + math.atan(pix_per * float( x - xord)/2500.0))) / bin
	    if ( qzmax < QzC):
		qzmax = QzC
	    if ( qzmin > QzC):
		qzmin = QzC
    qz_step = (qzmax - qzmin) / 256.0
    bin_z = [ (qzmin + qz_step * float( j)) for j in range(257)]

    print("Qx min  	>> ", qxmin)
    print("Qx max  	>> ", qxmax)
    print("Qy min  	>> ", qymin)
    print("Qy max  	>> ", qymax)
    print("Qz min  	>> ", qzmin)
    print("Qz max  	>> ", qzmax)

    ECA = mm.ElementContainerArray()
    instrument = os.environ["UTSUSEMI_INST_CODE"]
    ECA.AddToHeader("INSTRUMENT", instrument )
    ECA.AddToHeader("RUNNUMBER", str(runNo))
    for i in range( t0c):
      if ( i == bank):
	t0s = T0Count[i]
	# event_c = 0
	dataone = datalist[i]
	data=[[[] for j in range(256)] for k in range(256)]
	for y in range( len(dataone) ):
	    if ( y >= ymin and y <= ymax):
		for x in range( len(dataone[y]) ):
		    if ( x >= xmin and x <= xmax):
			events = dataone[y][x]
			eventn = len( events)
			if ( eventn > 0):
			    QxC = QC * ( math.cos(math.pi * angle/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) * math.cos(math.atan(pix_per * float(y - yord)/2500.0)) - math.cos(math.pi * angle/180.0))
			    QyC = QC *  math.cos(math.pi * angle/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) * math.sin(math.atan(pix_per * float(y - yord)/2500.0))
			    QzC = QC * ( math.sin(math.pi * angle/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) + math.sin(math.pi * angle/180.0))
			    for k in range( eventn):
				tof = float( events[k])
				if ( tof >= initial_bin and tof <= final_bin):
				    ix = 0
				    Qx = QxC / tof
				    while 1:
					if ( Qx < bin_x[ix+1]): 
					    break
					ix += 1
					if ix >= 256:
					     break
				    if ( ix < 256):
					iz = 0
					Qz = QzC / tof
					while 1:
					    if ( Qz < bin_z[iz+1]): 
						break
					    iz += 1
					    if iz >= 256:
						break
					if ( iz < 256):
					    data[ix][iz].append( QyC / tof)
	for x in range(256):
            int_list = data[x]
	    int_list_at_py = [ float( len( y)) for y in int_list ]
	    err_list_at_py = [ math.sqrt(e) for e in int_list_at_py ]
	    ec = mm.ElementContainer()
	    ec.Add( "Z", bin_z)
	    ec.Add( "Intensity", int_list_at_py )
	    ec.Add( "Error", err_list_at_py )
	    ec.SetKeys("Z","Intensity","Error")
	    xr_v = mm.MakeDoubleVector()
	    xr_v.append( bin_x[x] )
	    xr_v.append( bin_x[x + 1] )
	    ec.AddToHeader( "XRANGE", xr_v )
	    ECA.Add(ec)

	p=mp.M2Plot(ECA)
	p.SetXLabel( 'qx(nm^(-1))')
	p.SetYLabel( 'qz(nm^(-1))')

    return ECA

########################################
def GetHistMWPCQy2(runNo=125523, initial_bin=10000.0,final_bin=38100.0,angle=0.35, angle2=0.0, xord=95, yord=128):
    """
    Load EventData and convert to histogram for MWPC
    @param  runNo        (int) Run Number
    @param  initial_bin  (double) 
    @param  final_bin    (double) 
    @param  angle        (double) 
    @param  angle2        (double) 
    @param  xord         (int)
    @param  yord         (int)
    @retval ECA          (ElementContainerArray)
    """

    pixels = (256,256)
    dioFlag = -1
    bank = 0
    datalist, T0Count = mH.getEventDataArray( runNo, "MWPC", pixels, dioFlag)

    if ( initial_bin < 1.0):
	initial_bin = 1.0
    if ( final_bin <= 1.0):
	final_bin = 38100.0
    if ( initial_bin >= final_bin):
	initila_bin = 1.0

    #if ( dioFlag == -1):
    #	bank = 0

    print("Make ElementContainerMatrix")
    print("initial bin	>> ", initial_bin)
    print("final bin	>> ", final_bin)
    print("angle    	>> ", angle)
    print("angle2    	>> ", angle2)
    #print "dioFlag  	>> ", dioFlag
    #print "bank    	>> ", bank

    # xmin,max ymin,max constant
    xmin = 8
    xmax = 248
    ymin = 32
    ymax = 224
    pix_per = 0.5

    t0c = len( T0Count)
    if ( xord == -1 and yord == -1):
	nmax = 0
	for i in range( t0c):
	    if ( i == bank):
		dataone = datalist[i]
		for y in range( len(dataone) ):
		    if ( y >= ymin and y <= ymax):
			for x in range( len(dataone[y])):
			    if ( x >= xmin and x <= xmax):
				n = len(dataone[y][x])
				n += len(dataone[y-1][x-1])
				n += len(dataone[y-1][x])
				n += len(dataone[y][x-1])
				n += len(dataone[y+1][x])
				n += len(dataone[y][x+1])
				n += len(dataone[y+1][x+1])
				n += len(dataone[y+1][x-1])
				n += len(dataone[y-1][x+1])
				if ( n > nmax):
				    nmax = n
				    xord = x
				    yord = y
	print("Auto Origin set")
    print("x origin   	>> ", xord)
    print("y origin 	>> ", yord)

    QC = 2.0 * math.pi * (18.0e7/3955.6)

    qxmax = QC * ( math.cos(math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float(xmax - xord)/2500.0)) * math.cos(math.atan(pix_per * float(ymax - yord)/2500.0)) - math.cos(math.pi * angle/180.0)) / initial_bin
    qxmin = qxmax
    xvar = [ xmin, xmax]
    yvar = [ ymin, ymax]
    bins = [initial_bin, final_bin]
    for x in xvar:
	for y in yvar:
	    for bin in bins:
		QxC = QC * ( math.cos(math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) * math.cos(math.atan(pix_per * float(y - yord)/2500.0)) - math.cos(math.pi * angle/180.0)) / bin
		if ( qxmax < QxC):
		    qxmax = QxC
		if ( qxmin > QxC):
		    qxmin = QxC
    if ( qxmax < 0.0):
	qxmax = 0.0

    qx_step = ( qxmax - qxmin) / 256.0
    bin_x = [ (qxmin + qx_step * float( j)) for j in range(257)] 

    qymax = QC *  math.cos(math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float(xmin - xord)/2500.0)) * math.sin(math.atan(pix_per * float(ymin - yord)/2500.0)) / initial_bin
    qymin = qymax
    for x in xvar:
	for y in yvar:
	    for bin in bins:
		QyC = QC *  math.cos(math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) * math.sin(math.atan(pix_per * float(y - yord)/2500.0)) / bin
		if ( qymax < QyC):
		    qymax = QyC
		if ( qymin > QyC):
		    qymin = QyC
    qy_step = (qymax - qymin) / 256.0
    bin_y = [ (qymin + qy_step * float( j)) for j in range(257)]

    qzmax = QC * (math.sin( math.pi * angle / 180.0) + math.sin( math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float( xmax - xord)/2500.0))) / initial_bin
    qzmin = qzmax
    for x in xvar:
	for bin in bins:
	    QzC = QC * (math.sin( math.pi * angle / 180.0) + math.sin( math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float( x - xord)/2500.0))) / bin
	    if ( qzmax < QzC):
		qzmax = QzC
	    if ( qzmin > QzC):
		qzmin = QzC
    qz_step = (qzmax - qzmin) / 256.0
    bin_z = [ (qzmin + qz_step * float( j)) for j in range(257)]

    print("Qx min  	>> ", qxmin)
    print("Qx max  	>> ", qxmax)
    print("Qy min  	>> ", qymin)
    print("Qy max  	>> ", qymax)
    print("Qz min  	>> ", qzmin)
    print("Qz max  	>> ", qzmax)

    ECA = mm.ElementContainerArray()
    instrument = os.environ["UTSUSEMI_INST_CODE"]
    ECA.AddToHeader("INSTRUMENT", instrument )
    ECA.AddToHeader("RUNNUMBER", str(runNo))
    for i in range( t0c):
      if ( i == bank):
	t0s = T0Count[i]
	# event_c = 0
	dataone = datalist[i]
	data=[[[] for j in range(256)] for k in range(256)]
	for y in range( len(dataone) ):
	    if ( y >= ymin and y <= ymax):
		for x in range( len(dataone[y]) ):
		    if ( x >= xmin and x <= xmax):
			events = dataone[y][x]
			eventn = len( events)
			if ( eventn > 0):
			    QxC = QC * ( math.cos(math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) * math.cos(math.atan(pix_per * float(y - yord)/2500.0)) - math.cos(math.pi * angle/180.0))
			    QyC = QC *  math.cos(math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) * math.sin(math.atan(pix_per * float(y - yord)/2500.0))
			    QzC = QC * ( math.sin(math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) + math.sin(math.pi * angle/180.0))
			    for k in range( eventn):
				tof = float( events[k])
				if ( tof >= initial_bin and tof <= final_bin):
				    ix = 0
				    Qx = QxC / tof
				    while 1:
					if ( Qx < bin_x[ix+1]): 
					    break
					ix += 1
					if ix >= 256:
					     break
				    if ( ix < 256):
					iz = 0
					Qz = QzC / tof
					while 1:
					    if ( Qz < bin_z[iz+1]): 
						break
					    iz += 1
					    if iz >= 256:
						break
					if ( iz < 256):
					    data[ix][iz].append( QyC / tof)
	for x in range(256):
            int_list = data[x]
	    int_list_at_py = [ float( len( y)) for y in int_list ]
	    err_list_at_py = [ math.sqrt(e) for e in int_list_at_py ]
	    ec = mm.ElementContainer()
	    ec.Add( "Z", bin_z)
	    ec.Add( "Intensity", int_list_at_py )
	    ec.Add( "Error", err_list_at_py )
	    ec.SetKeys("Z","Intensity","Error")
	    xr_v = mm.MakeDoubleVector()
	    xr_v.append( bin_x[x] )
	    xr_v.append( bin_x[x + 1] )
	    ec.AddToHeader( "XRANGE", xr_v )
	    ECA.Add(ec)

	p=mp.M2Plot(ECA)
	p.SetXLabel( 'qx(nm^(-1))')
	p.SetYLabel( 'qz(nm^(-1))')

    return ECA

########################################
def GetHistMWPCQyoff(runNo=128215, initial_bin=10000.0,final_bin=38100.0,angle=2.0, angle2=0.0, xord=79, yord=128):
    """
    Load EventData and convert to histogram for MWPC
    @param  runNo        (int) Run Number
    @param  initial_bin  (double) 
    @param  final_bin    (double) 
    @param  angle        (double) 
    @param  angle2        (double) 
    @param  xord         (int)
    @param  yord         (int)
    @retval ECA          (ElementContainerArray)
    """

    pixels = (256,256)
    dioFlag = -1
    bank = 0
    datalist, T0Count = mH.getEventDataArray( runNo, "MWPC", pixels, dioFlag)

    if ( initial_bin < 1.0):
	initial_bin = 1.0
    if ( final_bin <= 1.0):
	final_bin = 38100.0
    if ( initial_bin >= final_bin):
	initila_bin = 1.0

    #if ( dioFlag == -1):
    #	bank = 0

    print("Make ElementContainerMatrix")
    print("initial bin	>> ", initial_bin)
    print("final bin	>> ", final_bin)
    print("angle    	>> ", angle)
    print("angle2    	>> ", angle2)
    #print "dioFlag  	>> ", dioFlag
    #print "bank    	>> ", bank

    # xmin,max ymin,max constant
    xmin = 8
    xmax = 248
    ymin = 32
    ymax = 224
    pix_per = 0.5

    t0c = len( T0Count)
    if ( xord == -1 and yord == -1):
	nmax = 0
	for i in range( t0c):
	    if ( i == bank):
		dataone = datalist[i]
		for y in range( len(dataone) ):
		    if ( y >= ymin and y <= ymax):
			for x in range( len(dataone[y])):
			    if ( x >= xmin and x <= xmax):
				n = len(dataone[y][x])
				n += len(dataone[y-1][x-1])
				n += len(dataone[y-1][x])
				n += len(dataone[y][x-1])
				n += len(dataone[y+1][x])
				n += len(dataone[y][x+1])
				n += len(dataone[y+1][x+1])
				n += len(dataone[y+1][x-1])
				n += len(dataone[y-1][x+1])
				if ( n > nmax):
				    nmax = n
				    xord = x
				    yord = y
	print("Auto Origin set")
    print("x origin   	>> ", xord)
    print("y origin 	>> ", yord)

    QC = 2.0 * math.pi * (18.0e7/3955.6)

    qxmax = QC * ( math.cos(math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float(xmax - xord)/2500.0)) - math.cos(math.pi * angle/180.0)) / initial_bin
    qxmin = qxmax
    xvar = [ xmin, xmax]
    yvar = [ ymin, ymax]
    bins = [initial_bin, final_bin]
    for x in xvar:
#	for y in yvar:
	    for bin in bins:
		QxC = QC * ( math.cos(math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float(x - xord)/2500.0))  - math.cos(math.pi * angle/180.0)) / bin
		if ( qxmax < QxC):
		    qxmax = QxC
		if ( qxmin > QxC):
		    qxmin = QxC
#    if ( qxmax < 0.0):
#	qxmax = 0.0

#    qxmin = -0.01074
#    qxmax = -0.0005

    qx_step = ( qxmax - qxmin) / 512.0
    bin_x = [ (qxmin + qx_step * float( j)) for j in range(513)] 

    qzmax = QC * (math.sin( math.pi * angle / 180.0) + math.sin( math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float( xmax - xord)/2500.0))) / initial_bin
    qzmin = qzmax
    for x in xvar:
	for bin in bins:
	    QzC = QC * (math.sin( math.pi * angle / 180.0) + math.sin( math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float( x - xord)/2500.0))) / bin
	    if ( qzmax < QzC):
		qzmax = QzC
	    if ( qzmin > QzC):
		qzmin = QzC
#    qzmin = 0.50
#    qzmax = 1.012

    qz_step = (qzmax - qzmin) / 512.0
    bin_z = [ (qzmin + qz_step * float( j)) for j in range(513)]

    print("Qx min  	>> ", qxmin)
    print("Qx max  	>> ", qxmax)
    # print "Qy min  	>> ", qymin
    # print "Qy max  	>> ", qymax
    print("Qz min  	>> ", qzmin)
    print("Qz max  	>> ", qzmax)

    ECA = mm.ElementContainerArray()
    instrument = os.environ["UTSUSEMI_INST_CODE"]
    ECA.AddToHeader("INSTRUMENT", instrument )
    ECA.AddToHeader("RUNNUMBER", str(runNo))
    for i in range( t0c):
      if ( i == bank):
	t0s = T0Count[i]
	# event_c = 0
	dataone = datalist[i]
	data=[[[] for j in range(512)] for k in range(512)]
	for y in range( len(dataone) ):
	    if ( y >= ymin and y <= ymax):
		for x in range( len(dataone[y]) ):
		    if ( x >= xmin and x <= xmax):
			events = dataone[y][x]
			eventn = len( events)
			if ( eventn > 0):
			    QxC = QC * ( math.cos(math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) - math.cos(math.pi * angle/180.0))
			    QyC = QC *  math.cos(math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) * math.sin(math.atan(pix_per * float(y - yord)/2500.0))
			    QzC = QC * ( math.sin(math.pi * (angle+angle2)/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) + math.sin(math.pi * angle/180.0))
			    for k in range( eventn):
				tof = float( events[k])
				if ( tof >= initial_bin and tof <= final_bin):
				    ix = 0
				    Qx = QxC / tof
				    while 1:
					if ( Qx < bin_x[ix+1]): 
					    break
					ix += 1
					if ix >= 512:
					     break
				    if ( ix < 512):
					iz = 0
					Qz = QzC / tof
					while 1:
					    if ( Qz < bin_z[iz+1]): 
						break
					    iz += 1
					    if iz >= 512:
						break
					if ( iz < 512):
					    data[ix][iz].append( QyC / tof)
	for x in range(512):
            int_list = data[x]
	    int_list_at_py = [ float( len( y)) for y in int_list ]
	    err_list_at_py = [ math.sqrt(e) for e in int_list_at_py ]
	    ec = mm.ElementContainer()
	    ec.Add( "Z", bin_z)
	    ec.Add( "Intensity", int_list_at_py )
	    ec.Add( "Error", err_list_at_py )
	    ec.SetKeys("Z","Intensity","Error")
	    xr_v = mm.MakeDoubleVector()
	    xr_v.append( bin_x[x] )
	    xr_v.append( bin_x[x + 1] )
	    ec.AddToHeader( "XRANGE", xr_v )
	    ECA.Add(ec)

	p=mp.M2Plot(ECA)
	p.SetXLabel( 'qx(nm^(-1))')
	p.SetYLabel( 'qz(nm^(-1))')

    return ECA

########################################
def GetHistMWPCQz(runNo=125523, initial_bin=10000.0,final_bin=38100.0,angle=-1.0, xord=-1, yord=-1, dioFlag=-1, bank=0):
    """
    Load EventData and convert to histogram for MWPC
    @param  runNo        (int) Run Number
    @param  initial_bin  (double) 
    @param  final_bin    (double) 
    @param  angle        (double) 
    @param  xord         (int)
    @param  yord         (int)
    @param  dioFlag      (int)
    @param  bank         (int)
    @retval ECA          (ElementContainerArray)
    """

    pixels = (256,256)
    datalist, T0Count = mH.getEventDataArray( runNo, "MWPC", pixels, dioFlag)

    if ( initial_bin < 1.0):
	initial_bin = 1.0
    if ( final_bin <= 1.0):
	final_bin = 38100.0
    if ( initial_bin >= final_bin):
	initila_bin = 1.0

    a2th = PickupCurpos(runNo, 'A2TH')
    if ( angle < 0.0):
	if ( a2th != -9999.9):
	    angle = float( a2th) / 2.0
	else:
	    angle = 0.3
    if ( dioFlag == -1):
	bank = 0

    print("Make ElementContainerMatrix")
    print("initial bin	>> ", initial_bin)
    print("final bin	>> ", final_bin)
    print("angle    	>> ", angle)
    print("dioFlag  	>> ", dioFlag)
    print("bank    	>> ", bank)

    # xmin,max ymin,max constant
    xmin = 32
    xmax = 224
    ymin = 32
    ymax = 224
    pix_per = 0.5

    t0c = len( T0Count)
    if ( xord == -1 and yord == -1):
	nmax = 0
	for i in range( t0c):
	    if ( i == bank):
		dataone = datalist[i]
		for y in range( len(dataone) ):
		    if ( y >= ymin and y <= ymax):
			for x in range( len(dataone[y])):
			    if ( x >= xmin and x <= xmax):
				n = len(dataone[y][x])
				n += len(dataone[y-1][x-1])
				n += len(dataone[y-1][x])
				n += len(dataone[y][x-1])
				n += len(dataone[y+1][x])
				n += len(dataone[y][x+1])
				n += len(dataone[y+1][x+1])
				n += len(dataone[y+1][x-1])
				n += len(dataone[y-1][x+1])
				if ( n > nmax):
				    nmax = n
				    xord = x
				    yord = y
	print("Auto Origin set")
    print("x origin   	>> ", xord)
    print("y origin 	>> ", yord)

    QC = 2.0 * math.pi * (18.0e7/3955.6)

    qxmax = QC * ( math.cos(math.pi * angle/180.0 + math.atan(pix_per * float(xmax - xord)/2500.0)) * math.cos(math.atan(pix_per * float(ymax - yord)/2500.0)) - math.cos(math.pi * angle/180.0)) / initial_bin
    qxmin = qxmax
    xvar = [ xmin, xmax]
    yvar = [ ymin, ymax]
    bins = [initial_bin, final_bin]
    for x in xvar:
	for y in yvar:
	    for bin in bins:
		QxC = QC * ( math.cos(math.pi * angle/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) * math.cos(math.atan(pix_per * float(y - yord)/2500.0)) - math.cos(math.pi * angle/180.0)) / bin
		if ( qxmax < QxC):
		    qxmax = QxC
		if ( qxmin > QxC):
		    qxmin = QxC
    if ( qxmax < 0.0):
	qxmax = 0.0

    qx_step = ( qxmax - qxmin) / 256.0
    bin_x = [ (qxmin + qx_step * float( j)) for j in range(257)] 

    qymax = QC *  math.cos(math.pi * angle/180.0 + math.atan(pix_per * float(xmin - xord)/2500.0)) * math.sin(math.atan(pix_per * float(ymin - yord)/2500.0)) / initial_bin
    qymin = qymax
    for x in xvar:
	for y in yvar:
	    for bin in bins:
		QyC = QC *  math.cos(math.pi * angle/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) * math.sin(math.atan(pix_per * float(y - yord)/2500.0)) / bin
		if ( qymax < QyC):
		    qymax = QyC
		if ( qymin > QyC):
		    qymin = QyC
    qy_step = (qymax - qymin) / 256.0
    bin_y = [ (qymin + qy_step * float( j)) for j in range(257)]

    qzmax = QC * (math.sin( math.pi * angle / 180.0) + math.sin( math.pi * angle/180.0 + math.atan(pix_per * float( xmax - xord)/2500.0))) / initial_bin
    qzmin = qzmax
    for x in xvar:
	for bin in bins:
	    QzC = QC * (math.sin( math.pi * angle / 180.0) + math.sin( math.pi * angle/180.0 + math.atan(pix_per * float( x - xord)/2500.0))) / bin
	    if ( qzmax < QzC):
		qzmax = QzC
	    if ( qzmin > QzC):
		qzmin = QzC
    qz_step = (qzmax - qzmin) / 256.0
    bin_z = [ (qzmin + qz_step * float( j)) for j in range(257)]

    print("Qx min  	>> ", qxmin)
    print("Qx max  	>> ", qxmax)
    print("Qy min  	>> ", qymin)
    print("Qy max  	>> ", qymax)
    print("Qz min  	>> ", qzmin)
    print("Qz max  	>> ", qzmax)

    ECA = mm.ElementContainerArray()
    instrument = os.environ["UTSUSEMI_INST_CODE"]
    ECA.AddToHeader("INSTRUMENT", instrument )
    ECA.AddToHeader("RUNNUMBER", str(runNo))
    for i in range( t0c):
      if ( i == bank):
	t0s = T0Count[i]
	# event_c = 0
	dataone = datalist[i]
	data=[[[] for j in range(256)] for k in range(256)]
	for y in range( len(dataone) ):
	    if ( y >= ymin and y <= ymax):
		for x in range( len(dataone[y]) ):
		    if ( x >= xmin and x <= xmax):
			events = dataone[y][x]
			eventn = len( events)
			if ( eventn > 0):
			    QxC = QC * ( math.cos(math.pi * angle/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) * math.cos(math.atan(pix_per * float(y - yord)/2500.0)) - math.cos(math.pi * angle/180.0))
			    QyC = QC *  math.cos(math.pi * angle/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) * math.sin(math.atan(pix_per * float(y - yord)/2500.0))
			    QzC = QC * ( math.sin(math.pi * angle/180.0 + math.atan(pix_per * float(x - xord)/2500.0)) + math.sin(math.pi * angle/180.0))
			    for k in range( eventn):
				tof = float( events[k])
				if ( tof >= initial_bin and tof <= final_bin):
				    ix = 0
				    Qx = QxC / tof
				    while 1:
					if ( Qx < bin_x[ix+1]): 
					    break
					ix += 1
					if ix >= 256:
					     break
				    if ( ix < 256):
					iy = 0
					Qy = QyC / tof
					while 1:
					    if ( Qy < bin_y[iy+1]): 
						break
					    iy += 1
					    if iy >= 256:
						break
					if ( iy < 256):
					    data[ix][iy].append( QzC / tof)
	for x in range(256):
            int_list = data[x]
	    int_list_at_py = [ float( len( y)) for y in int_list ]
	    err_list_at_py = [ math.sqrt(e) for e in int_list_at_py ]
	    ec = mm.ElementContainer()
	    ec.Add( "Y", bin_z)
	    ec.Add( "Intensity", int_list_at_py )
	    ec.Add( "Error", err_list_at_py )
	    ec.SetKeys("Y","Intensity","Error")
	    xr_v = mm.MakeDoubleVector()
	    xr_v.append( bin_x[x] )
	    xr_v.append( bin_x[x + 1] )
	    ec.AddToHeader( "XRANGE", xr_v )
	    ECA.Add(ec)

	p=mp.M2Plot(ECA)
	p.SetXLabel( 'qx(nm^(-1))')
	p.SetYLabel( 'qy(nm^(-1))')

    return ECA

def GetM2PlotMWPC( runNo=0, dio = -1 ):
    """
    Load EventData to produce histogram
    GetM2PlotMWPC( runNo=0, dio = -1)
    
    @param runNo     (int)     Run Number
    @param dio (int) dio mode -1, or 0, or 1
    @retval ECA (ElementContainerArray)
    """

    px_list=[ -0.5+float(i) for i in range(257) ]
    pixels = (256,256)

    datalist, T0Count = mH.getEventDataArray( runNo, "MWPC", pixels, -1)
    ECA = mm.ElementContainerArray()
    instrument = os.environ["UTSUSEMI_INST_CODE"]
    ECA.AddToHeader("INSTRUMENT", instrument )
    ECA.AddToHeader("RUNNUMBER", str(runNo))
    dataone = datalist[0]

    correct = np.loadtxt('calib_mwpc_161106.txt')

    for i_px in range(157,171):
	for i_py in range(64,76):
	    correct[i_py, i_px] = correct[i_py + 24, i_px]
    for i_px in range(230,242):
	for i_py in range(216,230):
	    correct[i_py, i_px] = correct[i_py - 24, i_px]

    #f = open("/usr/local/mlf/VNR/ana/xml/"+str(runNo).zfill(6)+".dat", 'w')
    f = open( os.path.join( getVNRConst.GetUserDir(),"ana","xml",str(runNo).zfill(6)+".dat"), 'w') #[inamura 180403]
    for i_px in range(256):
	int_list_at_py = [ float( len( dataone[i_py][i_px])) * float(correct[i_py,255 - i_px]) for i_py in range(256) ]
	err_list_at_py = [ math.sqrt(y) for y in int_list_at_py ]
    
        ec = mm.ElementContainer()
        ec.Add( "X", px_list )
        ec.Add( "Intensity", int_list_at_py )
        ec.Add( "Error", err_list_at_py )
        ec.SetKeys("X","Intensity","Error")
        xr_v = mm.MakeDoubleVector()
        xr_v.append( px_list[i_px] )
        xr_v.append( px_list[i_px+1] )
        ec.AddToHeader( "XRANGE", xr_v )
        ECA.Add(ec)
	for i_py in range(len(int_list_at_py)):
	    f.write("%d\t%d\t%f\t%f\n" % (i_px, i_py, int_list_at_py[i_py], err_list_at_py[i_py]))

    f.close()
#   import utsusemi.vis.M2Plot as mp
#   p=mp.M2Plot(dat)

    return ECA

########################################
# Dictionary for entry the name of functions
_functions = {
            "GetHistMWPCDetector":GetHistMWPCDetector,
            "GetHistRPMTDetector":GetHistRPMTDetector,
            "GetHistMWPCDetectorT":GetHistMWPCDetectorT,
            "GetHistMWPC0d":GetHistMWPC0d,
            "GetHistMWPC0dx":GetHistMWPC0dx,
            "GetHistMWPC0dTime":GetHistMWPC0dTime,
            "GetHistMWPC0dDio":GetHistMWPC0dDio,
            "GetHistMWPC0dDiox":GetHistMWPC0dDiox,
            "GetHistMWPCTOF":GetHistMWPCTOF,
            "GetHistMWPCX":GetHistMWPCX,
            "GetHistMWPCX2":GetHistMWPCX2,
            "GetHistMWPCQy":GetHistMWPCQy,
            "GetHistMWPCQy2":GetHistMWPCQy2,
            "GetHistMWPCQyoff":GetHistMWPCQyoff,
            "GetHistMWPCQz":GetHistMWPCQz,
            "GetM2PlotMWPC":GetM2PlotMWPC
            }
_functionsOrder = [
    "GetHistMWPCDetector",
    "GetHistRPMTDetector",
    "GetHistMWPCDetectorT",
    "GetHistMWPC0d",
    "GetHistMWPC0dx",
    "GetHistMWPC0dTime",
    "GetHistMWPC0dDio",
    "GetHistMWPC0dDiox",
    "GetHistMWPCTOF",
    "GetHistMWPCX",
    "GetHistMWPCX2",
    "GetHistMWPCQy",
    "GetHistMWPCQy2",
    "GetHistMWPCQyoff",
    "GetHistMWPCQz",
    "GetM2PlotMWPC"
    ]
    
