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

from __future__ import print_function
import sys
#import os
import Manyo as mm
import utsusemi.vis.M2Plot as mp
from tofHist2 import *
#import math

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]

# special reserved word for commands history
HISTORY = None

# reserved words for return value in this.
ec = None
ec0 = None
ec1 = None
ec2 = None
EC = None
XXX = 'VNR'
########################################

def modeDio(sfmode='sf3'):
    if ( sfmode == 'sf2'):
	dioFlag1=[True,False,True,False,True,None,None,None]
	dioFlag2=[False,True,True,False,True,None,None,None]
	dioFlag3=[True,False,False,True,True,None,None,None]
	dioFlag4=[False,True,False,True,True,None,None,None]
    elif ( sfmode == 'sf3'):
	dioFlag1=[True,False,None,None,True,True,False,None]
	dioFlag2=[False,True,None,None,True,True,False,None]
	dioFlag3=[True,False,None,None,True,False,True,None]
	dioFlag4=[False,True,None,None,True,False,True,None]
    else:
	dioFlag1=[True,False,None,None,True,False,True,None]
	dioFlag2=[False,True,None,None,True,False,True,None]
	dioFlag3=[True,False,None,None,True,True,False,None]
	dioFlag4=[False,True,None,None,True,True,False,None]
    return [dioFlag1, dioFlag2, dioFlag3, dioFlag4]

def modeDioSwing(sfmode='sf3'):
    if ( sfmode == 'sf2'):
	dioFlag1=[True,False,True,False,False,None,None,None]
	dioFlag2=[False,True,True,False,False,None,None,None]
	dioFlag3=[True,False,False,True,False,None,None,None]
	dioFlag4=[False,True,False,True,False,None,None,None]
    elif ( sfmode == 'sf3'):
	dioFlag1=[True,False,None,None,False,True,False,None]
	dioFlag2=[False,True,None,None,False,True,False,None]
	dioFlag3=[True,False,None,None,False,False,True,None]
	dioFlag4=[False,True,None,None,False,False,True,None]
    else:
	dioFlag1=[True,False,None,None,False,False,True,None]
	dioFlag2=[False,True,None,None,False,False,True,None]
	dioFlag3=[True,False,None,None,False,True,False,None]
	dioFlag4=[False,True,None,None,False,True,False,None]
    return [dioFlag1, dioFlag2, dioFlag3, dioFlag4]

def modeDio12(sfmode='sf3'):
    dioFlag1=[True,False,None,None,True,None,None,None]
    dioFlag2=[False,True,None,None,True,None,None,None]
    return [dioFlag1, dioFlag2]

def modeDio12Swing(sfmode='sf3'):
    dioFlag1=[True,False,None,None,False,None,None,None]
    dioFlag2=[False,True,None,None,False,None,None,None]
    return [dioFlag1, dioFlag2]

#########################################
def cal_factor( q1, y1, q2, y2):

	qu1 = 0
	qu2 = 0
	i = len( q1) - 2
	while (i > 0):
	    if (q1[i] > q2[1]):
		i -= 1
		qu1 += (y1[i] * (q1[i+1] - q1[i]))
	    else:
		i = 0
	if ( qu1 > 0.0):
	    i = 1
	    while ( i < len(q2)-1):
		if (q2[i] < q1[-2]):
		    qu2 += (y2[i] * (q2[i+1] - q2[i]))
		    i += 1
		else:
		    i = len(q2)
	    if ( qu2 > 0.0):
		qu1 /= qu2
	    else:
		qu1 = 0.0
	return qu1

def merge_wave( q1, y1, e1, q2, y2, e2):
	i = 0
	while ( q2[1] > q1[i]):
	    i += 1
	q1ptr = i - 1
	q2ptr = 0
	while ( q2[q2ptr] < q1[-2]):
	    q2ptr += 1
	n1 = len( q1) - q1ptr - 1
	n2 = q2ptr
	if ( n1 == n2):
	    # smooth mode
	    print("Smooth Mode: ", n1)
	    new_q = q1[:q1ptr]
	    new_y = y1[:q1ptr]
	    new_e = e1[:q1ptr]
	    i = 1
	    while ( i < q2ptr):
		new_q.append( (q1[q1ptr] + q2[i]) / 2.0)
		new_y.append((y1[q1ptr] + y2[i]) / 2.0)
		new_e.append( math.sqrt(e1[q1ptr]*e1[q1ptr] + e2[i]*e2[i]) / 2.0)
		i += 1
		q1ptr += 1
	    new_q.append( (q1[q1ptr] + q2[q2ptr]) / 2.0)
	    #new_y.extend( y)
	    new_y[len(new_y):] = y2[i:]
	    #new_e.extend( e2[i:])
	    new_e[len(new_e):] = e2[i:]
	    #new_q.extend(q2[i+1:])
	    new_q[len(new_q):] = q2[i+1:]
	    print("len: ", len(new_q), len(new_y))
	else:
		# ookiihouni awaseru
	    print("Convert Mode: ", n1," : ", n2)
	    if ( n1 < n2):
		new_q = q1[:-2]
		new_y = y1[:-1]
		new_e = e1[:-1]
		new_q.append( (q1[-2] + q2[q2ptr]) / 2.0)
		new_q[len(new_q):] = q2[q2ptr+1:]
		new_y[len(new_y):] = y2[q2ptr:]
		new_e[len(new_e):] = e2[q2ptr:]
		#new_q.extend( q2[q2ptr+1:]) 
		#new_y.extend( y2[q2ptr:]) 
		#new_e.extend( e2[q2ptr:]) 
		i = q1ptr
		while ( i < len(q1)-1):
		    low = new_q[i]
		    high = new_q[i+1]
		    y = new_y[i]
		    e = new_e[i] * new_e[i]
		    d = 1.0
		    for j in range(1, q2ptr):
			mid = (q2[j] + q2[j+1]) / 2.0
			if ( mid >= low and mid < high):
			    y += y2[j]
			    e += e2[j] * e2[j]
			    d += 1.0
		    if ( d > 1.0):
			new_y[i] = y / d
			new_e[i] = math.sqrt(e) / d
		    i += 1
	    else:
		new_q = q1[:q1ptr]
		new_y = y1[:q1ptr]
		new_e = e1[:q1ptr]
		new_q.append( (q1[q1ptr] + q2[1]) / 2.0)
		new_q[len(new_q):] = q2[2:]
		new_y[len(new_y):] = y2[1:]
		new_e[len(new_e):] = e2[1:]
		#new_q.extend( q2[2:]) 
		#new_y.extend( y2[1:]) 
		#new_e.extend( e2[1:]) 
		i = q1ptr
		while ( i < len(q1)-1):
		    low = new_q[i]
		    high = new_q[i+1]
		    y = new_y[i]
		    e = new_e[i] * new_e[i]
		    d = 1.0
		    for j in range(q1ptr, len(q1)-2):
			mid = (q1[j] + q1[j+1]) / 2.0
			if ( mid >= low and mid < high):
			    y += y1[j]
			    e += e1[j] * e1[j]
			    d += 1.0
		    if ( d > 1.0):
			new_y[i] = y / d
			new_e[i] = math.sqrt(e) / d
		    i += 1
	return [new_q, new_y, new_e]

#########################################
def ConcatenateUnp(ec1, ec2, norm=False):
	"""
	ConcatenateUnp(ec1,ec2, norm)
	@param   ec1  (ElementContainer)
	@param   ec2  (ElementContainer)
	@param   norm  (boolen) if True normarize
	@retval  EC   (ElementContainer)
	"""
	hh = ec1.PutHeader()
	q1 = ec1.PutX()
	int1 = ec1.PutY()
	err1 = ec1.PutE()
	q2 = ec2.PutX()
	int2 = ec2.PutY()
	err2 = ec2.PutE()
	EC  = mm.ElementContainer(hh)
	if ( q1[0] <= q2[0]):
	    du = cal_factor( q1, int1, q2, int2)
	    if ( du > 0.0):
		new_int = [i * du for i in int2]    
		new_err = [i * du for i in err2]
		ec = merge_wave( q1, int1, err1, q2, new_int, new_err)
	else:
	    du = cal_factor( q2, int2, q1, int1)
	    if ( du > 0.0):
		new_int = [i * du for i in int1]    
		new_err = [i * du for i in err1]
		ec = merge_wave( q2, int2, err2, q1, new_int, new_err)
	if ( du > 0.0):
	    EC.Add("Q", ec[0], "nm-1")
	    if ( norm == True):
		du = 1.0 / np.max( np.array(ec[1]))
		new_int = np.array( ec[1]) * du
		new_err = np.array( ec[2]) * du
		EC.Add("Intensity", new_int.tolist(), "Counts")
		EC.Add("Error", new_err.tolist(), "Counts")
	    else:
		EC.Add("Intensity", ec[1], "Counts")
		EC.Add("Error", ec[2], "Counts")
	    del new_int 
	    del new_err 
	    EC.SetKeys("Q","Intensity","Error")
	del int2 
	del err2 
	del int1 
	del err1 
	del q1 
	del q2 
	del hh 
	return EC

#########################################
def ConcatenateNorm(ec1=ec1, ec2=ec2, filename="/dev/shm/con.exp", norm=True):
	"""
	Concatenate(ec1,ec2, filename, Nornalize)
	@param   ec1  (ElementContainer)
	@param   ec2  (ElementContainer)
	@param   filename (string)
	@param   norm (Boolean) if normalize set 'True'
	@retval  EC   (ElementContainer)
	"""
	if ( isinstance( ec1, list)):
	    hh = ec1[0].PutHeader()
	    EC = []
	    if ( len( ec1) == 2):
		q1 = ec1[0].PutX()
		q2 = ec2[0].PutX()
		if ( q1[0] <= q2[0]):
		    int1 = ec1[0].PutY()
		    int2 = ec2[0].PutY()
		    int3 = ec1[1].PutY()
		    int4 = ec2[1].PutY()
		    err1 = ec1[0].PutE()
		    err2 = ec2[0].PutE()
		    err3 = ec1[1].PutE()
		    err4 = ec2[1].PutE()
		    q3  = ec1[1].PutX()
		    q4  = ec2[1].PutX()
		else:
		    q2 = q1
		    q1 = ec2[0].PutX()
		    int1 = ec2[0].PutY()
		    int2 = ec1[0].PutY()
		    int3 = ec2[1].PutY()
		    int4 = ec1[1].PutY()
		    err1 = ec2[0].PutE()
		    err2 = ec1[0].PutE()
		    err3 = ec2[1].PutE()
		    err4 = ec1[1].PutE()
		    q3  = ec2[1].PutX()
		    q4  = ec1[1].PutX()
		du1 = cal_factor( q1, int1, q2, int2)
		du2 = cal_factor( q3, int3, q4, int4)
		if ( du1 > 0 and du2 > 0):
		    du = ( du1 + du2) / 2.0
		    new_int = [i * du for i in int2]    
		    new_err = [i * du for i in err2]
		    ecm = merge_wave( q1, int1, err1, q2, new_int, new_err)
		    new_int = [i * du for i in int4]    
		    new_err = [i * du for i in err4]
		    ecp = merge_wave( q3, int3, err3, q4, new_int, new_err)
		    if ( norm == True):
			du = 1.0 / np.max( np.concatenate((np.array(ecm[1]),np.array(ecp[1]))))
			print("Normalize scale:", du)
			new_int = np.array( ecm[1]) * du
			new_err = np.array( ecm[2]) * du
			ecm[1] = new_int.tolist()
			ecm[2] = new_err.tolist()
			new_int = np.array( ecp[1]) * du
			new_err = np.array( ecp[2]) * du
			ecp[1] = new_int.tolist()
			ecp[2] = new_err.tolist()
		    ec0 = mm.ElementContainer(hh)
		    ec0.Add("Q", ecm[0], "nm-1")
		    ec0.Add("Intensity", ecm[1], "Counts")
		    ec0.Add("Error", ecm[2], "Counts")
		    ec0.SetKeys("Q","Intensity","Error")
		    EC = [ec0]
		    hh = ec1[1].PutHeader()
		    ec0 = mm.ElementContainer(hh)
		    ec0.Add("Q", ecp[0], "nm-1")
		    ec0.Add("Intensity", ecp[1], "Counts")
		    ec0.Add("Error", ecp[2], "Counts")
		    ec0.SetKeys("Q","Intensity","Error")
		    EC.append( ec0)
		    del ecm
		    del ecp
		    del new_int 
		    del new_err
		    del ec0

		if ( len( EC) == 2 and len( filename)> 0):
		    f = open( filename, 'w')
		    f.write("q_"+"\tref_p_"+"\terr_p_"+"\tref_m_"+"\terr_m_"+"\n")
	
		    q1 = EC[0].ReduceColumn( EC[0].PutXKey())
		    int1 = EC[0].PutY()
		    err1 = EC[0].PutE()
		    int2 = EC[1].PutY()
		    err2 = EC[1].PutE()

		    for i in range(len(int1)):
			q1[i] /= 10.0
			f.write("%16.12g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (q1[i], int2[i], err2[i], int1[i], err1[i]))
		    f.close()
	    else:
		q1 = ec1[1].PutX()
		q2 = ec2[1].PutX()
		if ( q1[0] <= q2[0]):
		    int1 = ec1[1].PutY()
		    int2 = ec2[1].PutY()
		    int3 = ec1[2].PutY()
		    int4 = ec2[2].PutY()
		    err1 = ec1[1].PutE()
		    err2 = ec2[1].PutE()
		    err3 = ec1[2].PutE()
		    err4 = ec2[2].PutE()
		    q3  = ec1[2].PutX()
		    q4  = ec2[2].PutX()
		    int5 = ec1[0].PutY()
		    int6 = ec2[0].PutY()
		    int7 = ec1[3].PutY()
		    int8 = ec2[3].PutY()
		    err5 = ec1[0].PutE()
		    err6 = ec2[0].PutE()
		    err7 = ec1[3].PutE()
		    err8 = ec2[3].PutE()
		    q5  = ec1[0].PutX()
		    q6  = ec2[0].PutX()
		    q7  = ec1[3].PutX()
		    q8  = ec2[3].PutX()
		else:
		    q2 = q1
		    q1 = ec2[1].PutX()
		    int1 = ec2[1].PutY()
		    int2 = ec1[1].PutY()
		    int3 = ec2[2].PutY()
		    int4 = ec1[2].PutY()
		    err1 = ec2[1].PutE()
		    err2 = ec1[1].PutE()
		    err3 = ec2[2].PutE()
		    err4 = ec1[2].PutE()
		    q3  = ec2[2].PutX()
		    q4  = ec1[2].PutX()
		    int5 = ec2[0].PutY()
		    int6 = ec1[0].PutY()
		    int7 = ec2[3].PutY()
		    int8 = ec1[3].PutY()
		    err5 = ec2[0].PutE()
		    err6 = ec1[0].PutE()
		    err7 = ec2[3].PutE()
		    err8 = ec1[3].PutE()
		    q5  = ec2[0].PutX()
		    q6  = ec1[0].PutX()
		    q7  = ec2[3].PutX()
		    q8  = ec1[3].PutX()
		du1 = cal_factor( q1, int1, q2, int2)
		du2 = cal_factor( q3, int3, q4, int4)
		if ( du1 > 0 and du2 > 0):
		    du = ( du1 + du2) / 2.0
		    new_int = [i * du for i in int6]    
		    new_err = [i * du for i in err6]
		    ecmp = merge_wave( q5, int5, err5, q6, new_int, new_err)
		    new_int = [i * du for i in int2]    
		    new_err = [i * du for i in err2]
		    ecpp = merge_wave( q1, int1, err1, q2, new_int, new_err)
		    new_int = [i * du for i in int4]    
		    new_err = [i * du for i in err4]
		    ecmm = merge_wave( q3, int3, err3, q4, new_int, new_err)
		    new_int = [i * du for i in int8]    
		    new_err = [i * du for i in err8]
		    ecpm = merge_wave( q7, int7, err7, q8, new_int, new_err)
		    if ( norm == True):
			du = 1.0 / np.max( np.concatenate((np.array(ecmm[1]),np.array(ecpp[1]))))
			print("Normalize scale:", du)
			new_int = np.array( ecmp[1]) * du
			new_err = np.array( ecmp[2]) * du
			ecmp[1] = new_int.tolist()
			ecmp[2] = new_err.tolist()
			new_int = np.array( ecpp[1]) * du
			new_err = np.array( ecpp[2]) * du
			ecpp[1] = new_int.tolist()
			ecpp[2] = new_err.tolist()
			new_int = np.array( ecmm[1]) * du
			new_err = np.array( ecmm[2]) * du
			ecmm[1] = new_int.tolist()
			ecmm[2] = new_err.tolist()
			new_int = np.array( ecpm[1]) * du
			new_err = np.array( ecpm[2]) * du
			ecpm[1] = new_int.tolist()
			ecpm[2] = new_err.tolist()
		    ec0 = mm.ElementContainer(hh)
		    ec0.Add("Q", ecmp[0], "nm-1")
		    ec0.Add("Intensity", ecmp[1], "Counts")
		    ec0.Add("Error", ecmp[2], "Counts")
		    ec0.SetKeys("Q","Intensity","Error")
		    EC = [ec0]
		    hh = ec1[1].PutHeader()
		    ec0 = mm.ElementContainer(hh)
		    ec0.Add("Q", ecpp[0], "nm-1")
		    ec0.Add("Intensity", ecpp[1], "Counts")
		    ec0.Add("Error", ecpp[2], "Counts")
		    ec0.SetKeys("Q","Intensity","Error")
		    EC.append( ec0)
		    hh = ec1[2].PutHeader()
		    ec0 = mm.ElementContainer(hh)
		    ec0.Add("Q", ecmm[0], "nm-1")
		    ec0.Add("Intensity", ecmm[1], "Counts")
		    ec0.Add("Error", ecmm[2], "Counts")
		    ec0.SetKeys("Q","Intensity","Error")
		    EC.append( ec0)
		    hh = ec1[3].PutHeader()
		    ec0 = mm.ElementContainer(hh)
		    ec0.Add("Q", ecpm[0], "nm-1")
		    ec0.Add("Intensity", ecpm[1], "Counts")
		    ec0.Add("Error", ecpm[2], "Counts")
		    ec0.SetKeys("Q","Intensity","Error")
		    EC.append( ec0)
		    del ecmp 
		    del ecpp 
		    del ecmm 
		    del ecpm 
		    del new_int 
		    del new_err
		    del ec0

		if ( len( EC) == 4 and len( filename)> 0):
		    f = open( filename, 'w')
		    f.write("q_"+"\tref_p_"+"\terr_p_"+"\tref_m_"+"\terr_m_"+"\tref_pm_"+"\terr_pm_"+"\n")
	
		    q1 = EC[0].ReduceColumn( EC[0].PutXKey())
		    int1 = EC[0].PutY()
		    err1 = EC[0].PutE()
		    int2 = EC[1].PutY()
		    err2 = EC[1].PutE()
		    int3 = EC[2].PutY()
		    err3 = EC[2].PutE()
		    int4 = EC[3].PutY()
		    err4 = EC[3].PutE()

		    for i in range(len(int1)):
			q1[i] /= 10.0
			f.write("%16.12g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (q1[i], int2[i], err2[i], int3[i], err3[i], (int1[i]+int4[i])/2.0, math.sqrt(err1[i]*err1[i] + err4[i]*err4[i])))
		    f.close()

		del err8	    
		del err7	    
		del err6	    
		del err5	    
		del int8	    
		del int7	    
		del int6	    
		del int5	    
		del q8	    
		del q7	    
		del q6	    
		del q5	    
	    del err4	    
	    del err3	    
	    del err2	    
	    del err1	    
	    del int4	    
	    del int3	    
	    del int2	    
	    del int1	    
	    del q4	    
	    del q3	    
	    del q2	    
	    del q1	    
	else:
	    EC = ConcatenateUnp( ec1, ec2, norm)
	    if ( len( filename)> 0):
		f = open( filename, 'w')
		f.write("q_"+"\tref_"+"\terr_ref_"+"\n")
	
		q1 = EC.ReduceColumn( EC.PutXKey())
		int1 = EC.PutY()
		err1 = EC.PutE()

		for i in range(len(int1)):
		    q1[i] /= 10.0
		    f.write("%16.12g\t%20.16g\t%20.16g\n" % (q1[i], int1[i], err1[i]))
		del q1
		del int1
		del err1
		f.close()
	return EC

#########################################
def ConcatenateNorm2(ec1=ec1, ec2=ec2, filename="/dev/shm/con.exp", norm=True):
	"""
	Concatenate(ec1,ec2, filename, Nornalize)
	@param   ec1  (ElementContainer)
	@param   ec2  (ElementContainer)
	@param   filename (string)
	@param   norm (Boolean) if normalize set 'True'
	@retval  EC   (ElementContainer)
	"""
	if ( isinstance( ec1, list)):
	    hh = ec1[0].PutHeader()
	    EC = []
	    if ( len( ec1) == 2):
		q1 = ec1[0].PutX()
		q2 = ec2[0].PutX()
		if ( q1[0] <= q2[0]):
		    int1 = ec1[0].PutY()
		    int2 = ec2[0].PutY()
		    int3 = ec1[1].PutY()
		    int4 = ec2[1].PutY()
		    err1 = ec1[0].PutE()
		    err2 = ec2[0].PutE()
		    err3 = ec1[1].PutE()
		    err4 = ec2[1].PutE()
		    q3  = ec1[1].PutX()
		    q4  = ec2[1].PutX()
		else:
		    q2 = q1
		    q1 = ec2[0].PutX()
		    int1 = ec2[0].PutY()
		    int2 = ec1[0].PutY()
		    int3 = ec2[1].PutY()
		    int4 = ec1[1].PutY()
		    err1 = ec2[0].PutE()
		    err2 = ec1[0].PutE()
		    err3 = ec2[1].PutE()
		    err4 = ec1[1].PutE()
		    q3  = ec2[1].PutX()
		    q4  = ec1[1].PutX()
		du1 = cal_factor( q1, int1, q2, int2)
		du2 = cal_factor( q3, int3, q4, int4)
		if ( du1 > 0 and du2 > 0):
		    du = ( du1 + du2) / 2.0
		    new_int = [i * du for i in int2]    
		    new_err = [i * du for i in err2]
		    ecm = merge_wave( q1, int1, err1, q2, new_int, new_err)
		    new_int = [i * du for i in int4]    
		    new_err = [i * du for i in err4]
		    ecp = merge_wave( q3, int3, err3, q4, new_int, new_err)
		    if ( norm == True):
			du = 1.0 / np.max( np.concatenate((np.array(ecm[1]),np.array(ecp[1]))))
			print("Normalize scale:", du)
			new_int = np.array( ecm[1]) * du
			new_err = np.array( ecm[2]) * du
			ecm[1] = new_int.tolist()
			ecm[2] = new_err.tolist()
			new_int = np.array( ecp[1]) * du
			new_err = np.array( ecp[2]) * du
			ecp[1] = new_int.tolist()
			ecp[2] = new_err.tolist()
		    ec0 = mm.ElementContainer(hh)
		    ec0.Add("Q", ecm[0], "nm-1")
		    ec0.Add("Intensity", ecm[1], "Counts")
		    ec0.Add("Error", ecm[2], "Counts")
		    ec0.SetKeys("Q","Intensity","Error")
		    EC = [ec0]
		    hh = ec1[1].PutHeader()
		    ec0 = mm.ElementContainer(hh)
		    ec0.Add("Q", ecp[0], "nm-1")
		    ec0.Add("Intensity", ecp[1], "Counts")
		    ec0.Add("Error", ecp[2], "Counts")
		    ec0.SetKeys("Q","Intensity","Error")
		    EC.append( ec0)
		    del ecm
		    del ecp
		    del new_int 
		    del new_err
		    del ec0

		if ( len( EC) == 2 and len( filename)> 0):
		    f = open( filename, 'w')
		    f.write("q_"+"\tref_p_"+"\terr_p_"+"\tref_m_"+"\terr_m_"+"\n")
	
		    q1 = EC[0].ReduceColumn( EC[0].PutXKey())
		    int1 = EC[0].PutY()
		    err1 = EC[0].PutE()
		    int2 = EC[1].PutY()
		    err2 = EC[1].PutE()

		    for i in range(len(int1)):
			q1[i] /= 10.0
			f.write("%16.12g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (q1[i], int2[i], err2[i], int1[i], err1[i]))
		    f.close()
	    else:
		q1 = ec1[1].PutX()
		q2 = ec2[1].PutX()
		if ( q1[0] <= q2[0]):
		    int1 = ec1[1].PutY()
		    int2 = ec2[1].PutY()
		    int3 = ec1[2].PutY()
		    int4 = ec2[2].PutY()
		    err1 = ec1[1].PutE()
		    err2 = ec2[1].PutE()
		    err3 = ec1[2].PutE()
		    err4 = ec2[2].PutE()
		    q3  = ec1[2].PutX()
		    q4  = ec2[2].PutX()
		    int5 = ec1[0].PutY()
		    int6 = ec2[0].PutY()
		    int7 = ec1[3].PutY()
		    int8 = ec2[3].PutY()
		    err5 = ec1[0].PutE()
		    err6 = ec2[0].PutE()
		    err7 = ec1[3].PutE()
		    err8 = ec2[3].PutE()
		    q5  = ec1[0].PutX()
		    q6  = ec2[0].PutX()
		    q7  = ec1[3].PutX()
		    q8  = ec2[3].PutX()
		else:
		    q2 = q1
		    q1 = ec2[1].PutX()
		    int1 = ec2[1].PutY()
		    int2 = ec1[1].PutY()
		    int3 = ec2[2].PutY()
		    int4 = ec1[2].PutY()
		    err1 = ec2[1].PutE()
		    err2 = ec1[1].PutE()
		    err3 = ec2[2].PutE()
		    err4 = ec1[2].PutE()
		    q3  = ec2[2].PutX()
		    q4  = ec1[2].PutX()
		    int5 = ec2[0].PutY()
		    int6 = ec1[0].PutY()
		    int7 = ec2[3].PutY()
		    int8 = ec1[3].PutY()
		    err5 = ec2[0].PutE()
		    err6 = ec1[0].PutE()
		    err7 = ec2[3].PutE()
		    err8 = ec1[3].PutE()
		    q5  = ec2[0].PutX()
		    q6  = ec1[0].PutX()
		    q7  = ec2[3].PutX()
		    q8  = ec1[3].PutX()
		du1 = cal_factor( q1, int1, q2, int2)
		du2 = cal_factor( q3, int3, q4, int4)
		if ( du1 > 0 and du2 > 0):
		    du = ( du1 + du2) / 2.0
		    new_int = [i * du for i in int6]    
		    new_err = [i * du for i in err6]
		    ecmp = merge_wave( q5, int5, err5, q6, new_int, new_err)
		    new_int = [i * du for i in int2]    
		    new_err = [i * du for i in err2]
		    ecpp = merge_wave( q1, int1, err1, q2, new_int, new_err)
		    new_int = [i * du for i in int4]    
		    new_err = [i * du for i in err4]
		    ecmm = merge_wave( q3, int3, err3, q4, new_int, new_err)
		    new_int = [i * du for i in int8]    
		    new_err = [i * du for i in err8]
		    ecpm = merge_wave( q7, int7, err7, q8, new_int, new_err)
		    if ( norm == True):
			du = 1.0 / np.max( np.concatenate((np.array(ecmm[1]),np.array(ecpp[1]))))
			print("Normalize scale:", du)
			new_int = np.array( ecmp[1]) * du
			new_err = np.array( ecmp[2]) * du
			ecmp[1] = new_int.tolist()
			ecmp[2] = new_err.tolist()
			new_int = np.array( ecpp[1]) * du
			new_err = np.array( ecpp[2]) * du
			ecpp[1] = new_int.tolist()
			ecpp[2] = new_err.tolist()
			new_int = np.array( ecmm[1]) * du
			new_err = np.array( ecmm[2]) * du
			ecmm[1] = new_int.tolist()
			ecmm[2] = new_err.tolist()
			new_int = np.array( ecpm[1]) * du
			new_err = np.array( ecpm[2]) * du
			ecpm[1] = new_int.tolist()
			ecpm[2] = new_err.tolist()
		    ec0 = mm.ElementContainer(hh)
		    ec0.Add("Q", ecmp[0], "nm-1")
		    ec0.Add("Intensity", ecmp[1], "Counts")
		    ec0.Add("Error", ecmp[2], "Counts")
		    ec0.SetKeys("Q","Intensity","Error")
		    EC = [ec0]
		    hh = ec1[1].PutHeader()
		    ec0 = mm.ElementContainer(hh)
		    ec0.Add("Q", ecpp[0], "nm-1")
		    ec0.Add("Intensity", ecpp[1], "Counts")
		    ec0.Add("Error", ecpp[2], "Counts")
		    ec0.SetKeys("Q","Intensity","Error")
		    EC.append( ec0)
		    hh = ec1[2].PutHeader()
		    ec0 = mm.ElementContainer(hh)
		    ec0.Add("Q", ecmm[0], "nm-1")
		    ec0.Add("Intensity", ecmm[1], "Counts")
		    ec0.Add("Error", ecmm[2], "Counts")
		    ec0.SetKeys("Q","Intensity","Error")
		    EC.append( ec0)
		    hh = ec1[3].PutHeader()
		    ec0 = mm.ElementContainer(hh)
		    ec0.Add("Q", ecpm[0], "nm-1")
		    ec0.Add("Intensity", ecpm[1], "Counts")
		    ec0.Add("Error", ecpm[2], "Counts")
		    ec0.SetKeys("Q","Intensity","Error")
		    EC.append( ec0)
		    del ecmp 
		    del ecpp 
		    del ecmm 
		    del ecpm 
		    del new_int 
		    del new_err
		    del ec0

		if ( len( EC) == 4 and len( filename)> 0):
		    f = open( filename, 'w')
		    f.write("q_"+"\tref_pp_"+"\terr_pp_"+"\tref_mm_"+"\terr_mm_"+"\tref_pm_"+"\terr_pm_"+"\tref_mp_"+"\terr_mp_"+"\n")
	
		    q1 = EC[0].ReduceColumn( EC[0].PutXKey())
		    int1 = EC[0].PutY()
		    err1 = EC[0].PutE()
		    int2 = EC[1].PutY()
		    err2 = EC[1].PutE()
		    int3 = EC[2].PutY()
		    err3 = EC[2].PutE()
		    int4 = EC[3].PutY()
		    err4 = EC[3].PutE()

		    for i in range(len(int1)):
			q1[i] /= 10.0
			f.write("%16.12g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (q1[i], int2[i], err2[i], int3[i], err3[i], int4[i], err4[i], int1[i], err1[i]))
		    f.close()

		del err8	    
		del err7	    
		del err6	    
		del err5	    
		del int8	    
		del int7	    
		del int6	    
		del int5	    
		del q8	    
		del q7	    
		del q6	    
		del q5	    
	    del err4	    
	    del err3	    
	    del err2	    
	    del err1	    
	    del int4	    
	    del int3	    
	    del int2	    
	    del int1	    
	    del q4	    
	    del q3	    
	    del q2	    
	    del q1	    
	else:
	    EC = ConcatenateUnp( ec1, ec2, norm)
	    if ( len( filename)> 0):
		f = open( filename, 'w')
		f.write("q_"+"\tref_"+"\terr_ref_"+"\n")
	
		q1 = EC.ReduceColumn( EC.PutXKey())
		int1 = EC.PutY()
		err1 = EC.PutE()

		for i in range(len(int1)):
		    q1[i] /= 10.0
		    f.write("%16.12g\t%20.16g\t%20.16g\n" % (q1[i], int1[i], err1[i]))
		del q1
		del int1
		del err1
		f.close()
	return EC

#########################################
def Concatenate(ec1=ec1, ec2=ec2, filename="/dev/shm/con.exp"):
	"""
	Concatenate(ec1,ec2)
	@param   ec1  (ElementContainer)
	@param   ec2  (ElementContainer)
	@param   filename (string)
	@retval  EC   (ElementContainer)
	"""
	if ( isinstance( ec1, list)):
	    hh = ec1[0].PutHeader()
	    EC = []
	    if ( len( ec1) == 2):
		q1 = ec1[0].PutX()
		q2 = ec2[0].PutX()
		if ( q1[0] <= q2[0]):
		    int1 = ec1[0].PutY()
		    int2 = ec2[0].PutY()
		    int3 = ec1[1].PutY()
		    int4 = ec2[1].PutY()
		    err1 = ec1[0].PutE()
		    err2 = ec2[0].PutE()
		    err3 = ec1[1].PutE()
		    err4 = ec2[1].PutE()
		    q3  = ec1[1].PutX()
		    q4  = ec2[1].PutX()
		else:
		    q2 = q1
		    q1 = ec2[0].PutX()
		    int1 = ec2[0].PutY()
		    int2 = ec1[0].PutY()
		    int3 = ec2[1].PutY()
		    int4 = ec1[1].PutY()
		    err1 = ec2[0].PutE()
		    err2 = ec1[0].PutE()
		    err3 = ec2[1].PutE()
		    err4 = ec1[1].PutE()
		    q3  = ec2[1].PutX()
		    q4  = ec1[1].PutX()
		du1 = cal_factor( q1, int1, q2, int2)
		du2 = cal_factor( q3, int3, q4, int4)
		if ( du1 > 0 and du2 > 0):
		    du = ( du1 + du2) / 2.0
		    new_int = [i * du for i in int2]    
		    new_err = [i * du for i in err2]
		    ec = merge_wave( q1, int1, err1, q2, new_int, new_err)
		    ec0 = mm.ElementContainer(hh)
		    ec0.Add("Q", ec[0], "nm-1")
		    ec0.Add("Intensity", ec[1], "Counts")
		    ec0.Add("Error", ec[2], "Counts")
		    ec0.SetKeys("Q","Intensity","Error")
		    EC = [ec0]
		    new_int = [i * du for i in int4]    
		    new_err = [i * du for i in err4]
		    ec = merge_wave( q3, int3, err3, q4, new_int, new_err)
		    hh = ec1[1].PutHeader()
		    ec0 = mm.ElementContainer(hh)
		    ec0.Add("Q", ec[0], "nm-1")
		    ec0.Add("Intensity", ec[1], "Counts")
		    ec0.Add("Error", ec[2], "Counts")
		    ec0.SetKeys("Q","Intensity","Error")
		    EC.append( ec0)
		    del new_int 
		    del new_err
		    del ec0

		if ( len( EC) == 2 and len( filename)> 0):
		    f = open( filename, 'w')
		    f.write("q_"+"\tref_p_"+"\terr_p_"+"\tref_m_"+"\terr_m_"+"\n")
	
		    q1 = EC[0].ReduceColumn( EC[0].PutXKey())
		    int1 = EC[0].PutY()
		    err1 = EC[0].PutE()
		    int2 = EC[1].PutY()
		    err2 = EC[1].PutE()

		    for i in range(len(int1)):
			q1[i] /= 10.0
			f.write("%16.12g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (q1[i], int2[i], err2[i], int1[i], err1[i]))
		    f.close()
	    else:
		q1 = ec1[1].PutX()
		q2 = ec2[1].PutX()
		if ( q1[0] <= q2[0]):
		    int1 = ec1[1].PutY()
		    int2 = ec2[1].PutY()
		    int3 = ec1[2].PutY()
		    int4 = ec2[2].PutY()
		    err1 = ec1[1].PutE()
		    err2 = ec2[1].PutE()
		    err3 = ec1[2].PutE()
		    err4 = ec2[2].PutE()
		    q3  = ec1[2].PutX()
		    q4  = ec2[2].PutX()
		    int5 = ec1[0].PutY()
		    int6 = ec2[0].PutY()
		    int7 = ec1[3].PutY()
		    int8 = ec2[3].PutY()
		    err5 = ec1[0].PutE()
		    err6 = ec2[0].PutE()
		    err7 = ec1[3].PutE()
		    err8 = ec2[3].PutE()
		    q5  = ec1[0].PutX()
		    q6  = ec2[0].PutX()
		    q7  = ec1[3].PutX()
		    q8  = ec2[3].PutX()
		else:
		    q2 = q1
		    q1 = ec2[1].PutX()
		    int1 = ec2[1].PutY()
		    int2 = ec1[1].PutY()
		    int3 = ec2[2].PutY()
		    int4 = ec1[2].PutY()
		    err1 = ec2[1].PutE()
		    err2 = ec1[1].PutE()
		    err3 = ec2[2].PutE()
		    err4 = ec1[2].PutE()
		    q3  = ec2[2].PutX()
		    q4  = ec1[2].PutX()
		    int5 = ec2[0].PutY()
		    int6 = ec1[0].PutY()
		    int7 = ec2[3].PutY()
		    int8 = ec1[3].PutY()
		    err5 = ec2[0].PutE()
		    err6 = ec1[0].PutE()
		    err7 = ec2[3].PutE()
		    err8 = ec1[3].PutE()
		    q5  = ec2[0].PutX()
		    q6  = ec1[0].PutX()
		    q7  = ec2[3].PutX()
		    q8  = ec1[3].PutX()
		du1 = cal_factor( q1, int1, q2, int2)
		du2 = cal_factor( q3, int3, q4, int4)
		if ( du1 > 0 and du2 > 0):
		    du = ( du1 + du2) / 2.0
		    new_int = [i * du for i in int6]    
		    new_err = [i * du for i in err6]
		    ec = merge_wave( q5, int5, err5, q6, new_int, new_err)
		    ec0 = mm.ElementContainer(hh)
		    ec0.Add("Q", ec[0], "nm-1")
		    ec0.Add("Intensity", ec[1], "Counts")
		    ec0.Add("Error", ec[2], "Counts")
		    ec0.SetKeys("Q","Intensity","Error")
		    EC = [ec0]
		    new_int = [i * du for i in int2]    
		    new_err = [i * du for i in err2]
		    ec = merge_wave( q1, int1, err1, q2, new_int, new_err)
		    hh = ec1[1].PutHeader()
		    ec0 = mm.ElementContainer(hh)
		    ec0.Add("Q", ec[0], "nm-1")
		    ec0.Add("Intensity", ec[1], "Counts")
		    ec0.Add("Error", ec[2], "Counts")
		    ec0.SetKeys("Q","Intensity","Error")
		    EC.append( ec0)
		    new_int = [i * du for i in int4]    
		    new_err = [i * du for i in err4]
		    ec = merge_wave( q3, int3, err3, q4, new_int, new_err)
		    hh = ec1[2].PutHeader()
		    ec0 = mm.ElementContainer(hh)
		    ec0.Add("Q", ec[0], "nm-1")
		    ec0.Add("Intensity", ec[1], "Counts")
		    ec0.Add("Error", ec[2], "Counts")
		    ec0.SetKeys("Q","Intensity","Error")
		    EC.append( ec0)
		    new_int = [i * du for i in int8]    
		    new_err = [i * du for i in err8]
		    ec = merge_wave( q7, int7, err7, q8, new_int, new_err)
		    hh = ec1[3].PutHeader()
		    ec0 = mm.ElementContainer(hh)
		    ec0.Add("Q", ec[0], "nm-1")
		    ec0.Add("Intensity", ec[1], "Counts")
		    ec0.Add("Error", ec[2], "Counts")
		    ec0.SetKeys("Q","Intensity","Error")
		    EC.append( ec0)
		    del new_int 
		    del new_err
		    del ec0

		if ( len( EC) == 4 and len( filename)> 0):
		    f = open( filename, 'w')
		    f.write("q_"+"\tref_p_"+"\terr_p_"+"\tref_m_"+"\terr_m_"+"\tref_pm_"+"\terr_pm_"+"\n")
	
		    q1 = EC[0].ReduceColumn( EC[0].PutXKey())
		    int1 = EC[0].PutY()
		    err1 = EC[0].PutE()
		    int2 = EC[1].PutY()
		    err2 = EC[1].PutE()
		    int3 = EC[2].PutY()
		    err3 = EC[2].PutE()
		    int4 = EC[3].PutY()
		    err4 = EC[3].PutE()

		    for i in range(len(int1)):
			q1[i] /= 10.0
			f.write("%16.12g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (q1[i], int2[i], err2[i], int3[i], err3[i], (int1[i]+int4[i])/2.0, math.sqrt(err1[i]*err1[i] + err4[i]*err4[i])))
		    f.close()

		del err8	    
		del err7	    
		del err6	    
		del err5	    
		del int8	    
		del int7	    
		del int6	    
		del int5	    
		del q8	    
		del q7	    
		del q6	    
		del q5	    
	    del err4	    
	    del err3	    
	    del err2	    
	    del err1	    
	    del int4	    
	    del int3	    
	    del int2	    
	    del int1	    
	    del q4	    
	    del q3	    
	    del q2	    
	    del q1	    
	else:
	    EC = ConcatenateUnp( ec1, ec2, False)
	    if ( len( filename)> 0):
		f = open( filename, 'w')
		f.write("q_"+"\tref_"+"\terr_ref_"+"\n")
	
		q1 = EC.ReduceColumn( EC.PutXKey())
		int1 = EC.PutY()
		err1 = EC.PutE()

		for i in range(len(int1)):
		    q1[i] /= 10.0
		    f.write("%16.12g\t%20.16g\t%20.16g\n" % (q1[i], int1[i], err1[i]))
		del q1
		del int1
		del err1
		f.close()
	return EC

#########################################
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])
    if ( exno > 0):
	print("exID: ", exno, " runNo.:", runnumber)
	#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 PickupAxisCurpos(runnumber=125467, meas='S', axis='Omg'):
    """
    Pickup params.xml curPos log for VNR
    @param  runnumber    (int) Run Number
    @param  meas         (string) measurement device 
    @param  axis         (string) measurement axis 
    @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])
    if ( exno > 0):
	print("exID: ", exno, " runNo.:", runnumber)
	#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):
				axisinfo = logs_ele.find(".//axisInfo")
				if ( isinstance( axisinfo, type(None)) == False):
				    for axisrec in axisinfo.findall("axisRec"):
					if ( axis == axisrec.find("axisName").text):
					    curPos = axisrec.find("curPos").text
					    print(" start: ", rslt_ele.find("startDate").text)
					    print(" end:   ", rslt_ele.find("endDate").text)
					    print(" Device:", devName, " Axis:", axis, " Value:", curPos)
				else:
				    print(" Not found axisinfo:", axis)
	    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 GetHist0dDetectorAdd(runnumber=123016, runStr='-1', initial_bin=10000.0,final_bin=38100.0,delta_bin=100.0, binType=0, t0Normalize=True):
        """
        Load EventData and convert to histogram for VNR
        @param  runnumber    (int) Run Number
        @param  runStr       (string) Run Number 2 or more
        @param  initial_bin  (double) 
        @param  final_bin    (double) 
        @param  delta_bin    (double) 
        @param  binType      (int) 
        @param  t0Normalize  (boolen)  
        @retval EC           (ElementContainer)
        """
	filterCondition = None
	positionCondition = None
	filePosition = None
	#binType=0
	#binInfo=( int(initial_bin), int(final_bin), int(delta_bin))
	binInfo=( initial_bin, final_bin, delta_bin)
	detector='0D'
	dioFlag=-1
	if 'MLF_DATA_DIR' in os.environ:
	    datadir = os.environ['MLF_DATA_DIR']
	else:
	    #datadir = os.path.join(os.sep,"data",XXX)
            datadir = getVNRConst.GetDataDir(True) #[inamura 180326]
	#trignetData = getTrignetData( runnumber, datadir)
	trignetData = None
	#t0Normalize = False
	t0Norm = False

	histDatas = getNeutronData( runnumber,datadir, detector, binInfo, binType,
			t0Norm, trignetData,
			filterCondition,
                        positionCondition,filePosition)

	EC  = mm.ElementContainer()
	if ( histDatas[3] > 0):
	    intensity_array = histDatas[0]
	    t0s = histDatas[3]
	    if ( runStr != '-1'):
		runArray=runStr.split('+')
		for j in range( len( runArray)):
		    runnum2 = int(runArray[j])
		    histData2 = getNeutronData( runnum2,datadir, detector, binInfo, binType,
			t0Norm, trignetData,
			filterCondition,
                        positionCondition,filePosition)
		    if ( histData2[3] > 0):
			intensity_array = intensity_array + histData2[0]
			t0s += histData2[3]
	    err_array = np.sqrt( intensity_array)
	    if t0Normalize:
		intensity_array = intensity_array / float( t0s)
		err_array = err_array / float( t0s)

	    print(">>  T0", t0s)

	    hh = mm.HeaderBase()
	    hh.Add("RUNNUMBER", str(runnumber))
	    hh.Add("XAxis", "TOF")
	    hh.Add("XLABEL", "TOF")
	    if ( t0Normalize == True):
		hh.Add("YLABEL", "Intensity")
	    else:
		hh.Add("YLABEL", "Counts")
	    intensity_list = intensity_array.tolist()
	    hh.Add("TotalCount",sum(intensity_list))
	    hh.Add("T0Count", t0s)
	    a2th = PickupCurpos(runnumber, 'A2TH')
	    if ( a2th != -9999.9):
		hh.Add("A2TH", a2th)
	    EC  = mm.ElementContainer(hh)
	    EC.Add("TOF", histDatas[2].tolist(), "microsec")
	    EC.Add("Intensity", intensity_list, "Counts")
	    EC.Add("Error", err_array.tolist(), "Counts")
	    EC.SetKeys("TOF","Intensity","Error")

	    tof1 = EC.ReduceColumn( EC.PutXKey())
	    int1 = EC.PutY()
	    err1 = EC.PutE()

	    #f = open("/usr/local/mlf/VNR/ana/xml/"+str(runnumber).zfill(6)+".tof", 'w')
            f = open(os.path.join(os.sep,getVNRConst.GetUserDir(),"ana","xml",str(runnumber).zfill(6)+".tof"), 'w') #[inamura 180404]
	    #f.write("t_"+str(runnumber)+"\tmp_"+str(runnumber)+"\temp_"+str(runnumber)+"\tpp_"+str(runnumber)+"\tepp_"+str(runnumber)+"\tmm_"+str(runnumber)+"\temm_"+str(runnumber)+"\tpm_"+str(runnumber)+"\tepm_"+str(runnumber)+"\n")
	    for i in range(len(int1)):
##      	f.write("%5.1f\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i], int2[i], err2[i], int3[i], err3[i], int4[i], err4[i]))
		f.write("%5.1f\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i]))
	    f.close()
	return EC
 
#########################################
def GetHist0dDetectorAddTOF(runnumber=123016, runStr='-1', initial_bin=10000.0,final_bin=38100.0,delta_bin=100.0, binType=0, t0Normalize=True, SecndF_upto=-1):
        """
        Load EventData and convert to histogram for VNR
        @param  runnumber    (int) Run Number
        @param  runStr       (string) Run Number 2 or more
        @param  initial_bin  (double) 
        @param  final_bin    (double) 
        @param  delta_bin    (double) 
        @param  binType      (int) 
        @param  t0Normalize  (boolen)  
        @param  SecndF_upto    (int)  
        @retval EC           (ElementContainer)
        """
	filterCondition = None
	positionCondition = None
	filePosition = None
	#binType=0
	#binInfo=( int(initial_bin), int(final_bin), int(delta_bin))
	binInfo=( initial_bin, final_bin, delta_bin)
	less_than = int(SecndF_upto)
	detector='0D'
	dioFlag=-1
	if 'MLF_DATA_DIR' in os.environ:
	    datadir = os.environ['MLF_DATA_DIR']
	else:
	    #datadir = os.path.join(os.sep,"data",XXX)
            datadir = getVNRConst.GetDataDir(True) #[inamura 180326]
	#trignetData = getTrignetData( runnumber, datadir)
	trignetData = None
	#t0Normalize = False
	t0Norm = False

	histDatas = getNeutronDataTOF( runnumber,datadir, detector, binInfo, binType,
			t0Norm, trignetData,
			filterCondition,
                        positionCondition,filePosition,less_than)

	EC  = mm.ElementContainer()
	if ( histDatas[3] > 0):
	    intensity_array = histDatas[0]
	    t0s = histDatas[3]
	    if ( runStr != '-1'):
		runArray=runStr.split('+')
		for j in range( len( runArray)):
		    runnum2 = int(runArray[j])
		    histData2 = getNeutronDataTOF( runnum2,datadir, detector, binInfo, binType,
			t0Norm, trignetData,
			filterCondition,
                        positionCondition,filePosition,less_than)
		    if ( histData2[3] > 0):
			intensity_array = intensity_array + histData2[0]
			t0s += histData2[3]
	    err_array = np.sqrt( intensity_array)
	    if t0Normalize:
		intensity_array = intensity_array / float( t0s)
		err_array = err_array / float( t0s)

	    print(">>  T0", t0s)

	    hh = mm.HeaderBase()
	    hh.Add("RUNNUMBER", str(runnumber))
	    hh.Add("XAxis", "TOF")
	    hh.Add("XLABEL", "TOF")
	    if ( t0Normalize == True):
		hh.Add("YLABEL", "Intensity")
	    else:
		hh.Add("YLABEL", "Counts")
	    intensity_list = intensity_array.tolist()
	    hh.Add("TotalCount",sum(intensity_list))
	    hh.Add("T0Count", t0s)
	    a2th = PickupCurpos(runnumber, 'A2TH')
	    if ( a2th != -9999.9):
		hh.Add("A2TH", a2th)
	    EC  = mm.ElementContainer(hh)
	    EC.Add("TOF", histDatas[2].tolist(), "microsec")
	    EC.Add("Intensity", intensity_list, "Counts")
	    EC.Add("Error", err_array.tolist(), "Counts")
	    EC.SetKeys("TOF","Intensity","Error")

	    tof1 = EC.ReduceColumn( EC.PutXKey())
	    int1 = EC.PutY()
	    err1 = EC.PutE()

	    #f = open("/usr/local/mlf/VNR/ana/xml/"+str(runnumber).zfill(6)+".tof", 'w')
            f = open(os.path.join(os.sep,getVNRConst.GetUserDir(),"ana","xml",str(runnumber).zfill(6)+".tof"), 'w') #[inamura 180404]
	    #f.write("t_"+str(runnumber)+"\tmp_"+str(runnumber)+"\temp_"+str(runnumber)+"\tpp_"+str(runnumber)+"\tepp_"+str(runnumber)+"\tmm_"+str(runnumber)+"\temm_"+str(runnumber)+"\tpm_"+str(runnumber)+"\tepm_"+str(runnumber)+"\n")
	    for i in range(len(int1)):
##      	f.write("%5.1f\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i], int2[i], err2[i], int3[i], err3[i], int4[i], err4[i]))
		f.write("%5.1f\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i]))
	    f.close()
	return EC
 
#########################################
def GetHist0dDetectorTimeMap(runnumber=111968, bin_range='10000,38100',delta_bin=100.0, timerange='0,-1', timestep=60, t0Normalize=False):
        """
        Load EventData and make map for a specific period of time
        @param  runnumber    (int) Run Number
        @param  bin_range    (string) min, max 
        @param  delta_bin    (double) 
        @param  timerange    (string) start sec. end sec.  
        @param  timestep     (int)  or -1 (not use)
        @param  t0Normalize  (boolen)  
        @retval ECA          (ElementContainer)
        """
	filterCondition = None
	if ( delta_bin >= 1.0):
	    binType = 0
	else:
	    binType = 1
	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= 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

	binInfo=( float(initial_bin), float(final_bin), delta_bin)
	detector='0D'
	dioFlag=-1
	if 'MLF_DATA_DIR' in os.environ:
	    datadir = os.environ['MLF_DATA_DIR']
	else:
	    #datadir = os.path.join(os.sep,"data",XXX)
            datadir = getVNRConst.GetDataDir(True) #[inamura 180326]
	#trignetData = getTrignetData( runnumber, datadir)
	trignetData = None
	#t0Normalize=True

	histDatas = getNeutronDataTime(runnumber,datadir, detector, binInfo, binType,
			t0Normalize, trignetData,
			filterCondition, nT0start, nT0end, nT0step)
	a2th = PickupCurpos(runnumber, 'A2TH')
	if isinstance( histDatas[3], list):
	    #ECA = []
	    ECA = mm.ElementContainerArray()
	    instrument = os.environ["UTSUSEMI_INST_CODE"]
	    ECA.AddToHeader("INSTRUMENT", instrument )
	    ECA.AddToHeader("RUNNUMBER", str(runnumber))

	    for j in range( len(histDatas[3])):
		hh = mm.HeaderBase()
		#intensity_list = histDatas[0][j]
		hh.Add("RUNNUMBER", str(runnumber))
		hh.Add("XAxis", "TOF")
		hh.Add("XLABEL", "TOF")
		if ( t0Normalize == True):
		    hh.Add("YLABEL", "Intensity")
		else:
		    hh.Add("YLABEL", "Counts")
		hh.Add("Label", str(j))
		intensity_array = histDatas[0][j].tolist()
		hh.Add("TotalCount",sum(intensity_array))
		hh.Add("T0Count",histDatas[3][j])
		if ( a2th != -9999.9):
		    hh.Add("A2TH", a2th)
		EC  = mm.ElementContainer(hh)
		EC.Add("TOF", histDatas[2].tolist(), "microsec")
		EC.Add("Intensity", intensity_array, "Counts")
		EC.Add("Error", histDatas[1][j].tolist(), "Counts")
		EC.SetKeys("TOF","Intensity","Error")

		#tof1 = EC.ReduceColumn( EC.PutXKey())
		#int1 = EC.PutY()
		#err1 = EC.PutE()

		#f = open("/usr/local/mlf/VNR/ana/xml/"+str(runnumber).zfill(6)+'_'+str(j).zfill(2)+".tof", 'w')
		##f.write("t_"+str(runnumber)+"\tmp_"+str(runnumber)+"\temp_"+str(runnumber)+"\tpp_"+str(runnumber)+"\tepp_"+str(runnumber)+"\tmm_"+str(runnumber)+"\temm_"+str(runnumber)+"\tpm_"+str(runnumber)+"\tepm_"+str(runnumber)+"\n")
		#for i in range(len(int1)):
##      	    f.write("%5.1f\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i], int2[i], err2[i], int3[i], err3[i], int4[i], err4[i]))
		    #f.write("%5.1f\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i]))
		#f.close()
		#ECA += [EC]
 		xr_v = mm.MakeDoubleVector()
		xr_v.append( float(nT0start) )
		nT0start += nT0step
		xr_v.append( float(nT0start) )
		EC.AddToHeader( "XRANGE", xr_v )
 
		ECA.Add(EC)

	    p=mp.M2Plot(ECA)
	    p.SetXLabel( 'Time (sec)')
	    p.SetYLabel( 'TOF (microsec)')

	    return ECA
	else:
	    ECA  = mm.ElementContainer()
	    if ( histDatas[3] > 0):
		hh = mm.HeaderBase()
		hh.Add("RUNNUMBER", str(runnumber))
		hh.Add("XAxis", "TOF")
		hh.Add("XLABEL", "TOF")
		if ( t0Normalize == True):
		    hh.Add("YLABEL", "Intensity")
		else:
		    hh.Add("YLABEL", "Counts")
		intensity_array = histDatas[0].tolist()
		hh.Add("TotalCount",sum(intensity_array))
		hh.Add("T0Count",histDatas[3])
		if ( a2th != -9999.9):
		    hh.Add("A2TH", a2th)
		ECA  = mm.ElementContainer(hh)
		ECA.Add("TOF", histDatas[2].tolist(), "microsec")
		ECA.Add("Intensity", intensity_array, "Counts")
		ECA.Add("Error", histDatas[1].tolist(), "Counts")
		ECA.SetKeys("TOF","Intensity","Error")

		#tof1 = ECA.ReduceColumn( ECA.PutXKey())
		#int1 = ECA.PutY()
		#err1 = ECA.PutE()

		#f = open("/usr/local/mlf/VNR/ana/xml/"+str(runnumber).zfill(6)+".tof", 'w')
		#f.write("t_"+str(runnumber)+"\tmp_"+str(runnumber)+"\temp_"+str(runnumber)+"\tpp_"+str(runnumber)+"\tepp_"+str(runnumber)+"\tmm_"+str(runnumber)+"\temm_"+str(runnumber)+"\tpm_"+str(runnumber)+"\tepm_"+str(runnumber)+"\n")
		#for i in range(len(int1)):
##      	    f.write("%5.1f\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i], int2[i], err2[i], int3[i], err3[i], int4[i], err4[i]))
		    #f.write("%5.1f\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i]))
		#f.close()
	    return ECA

#########################################
def GetHist0dDetectorTime(runnumber=111968, bin_range='10000,38100',delta_bin=0.01, timerange='0,-1', timestep=-1, t0Normalize=True):
        """
        Load EventData and make histogram for a specific period of time
        @param  runnumber    (int) Run Number
        @param  bin_range    (string) min, max 
        @param  delta_bin    (double) 
        @param  timerange    (string) start sec. end sec.  
        @param  timestep     (int)  or -1 (not use)
        @param  t0Normalize  (boolen)  
        @retval ECA          (ElementContainer)
        """
	filterCondition = None
	if ( delta_bin >= 1.0):
	    binType = 0
	else:
	    binType = 1
	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= 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

	binInfo=( float(initial_bin), float(final_bin), delta_bin)
	detector='0D'
	dioFlag=-1
	if 'MLF_DATA_DIR' in os.environ:
	    datadir = os.environ['MLF_DATA_DIR']
	else:
	    #datadir = os.path.join(os.sep,"data",XXX)
            datadir = getVNRConst.GetDataDir(True) #[inamura 180326]
	#trignetData = getTrignetData( runnumber, datadir)
	trignetData = None
	#t0Normalize=True

	histDatas = getNeutronDataTime(runnumber,datadir, detector, binInfo, binType,
			t0Normalize, trignetData,
			filterCondition, nT0start, nT0end, nT0step)
	a2th = PickupCurpos(runnumber, 'A2TH')
	if isinstance( histDatas[3], list):
	    ECA = []
	    for j in range( len(histDatas[3])):
		hh = mm.HeaderBase()
		#intensity_list = histDatas[0][j]
		hh.Add("RUNNUMBER", str(runnumber))
		hh.Add("XAxis", "TOF")
		hh.Add("XLABEL", "TOF")
		if ( t0Normalize == True):
		    hh.Add("YLABEL", "Intensity")
		else:
		    hh.Add("YLABEL", "Counts")
		hh.Add("Label", str(j))
		intensity_array = histDatas[0][j].tolist()
		hh.Add("TotalCount",sum(intensity_array))
		hh.Add("T0Count",histDatas[3][j])
		if ( a2th != -9999.9):
		    hh.Add("A2TH", a2th)
		EC  = mm.ElementContainer(hh)
		EC.Add("TOF", histDatas[2].tolist(), "microsec")
		EC.Add("Intensity", intensity_array, "Counts")
		EC.Add("Error", histDatas[1][j].tolist(), "Counts")
		EC.SetKeys("TOF","Intensity","Error")

		tof1 = EC.ReduceColumn( EC.PutXKey())
		int1 = EC.PutY()
		err1 = EC.PutE()

		f = open("/usr/local/mlf/VNR/ana/xml/"+str(runnumber).zfill(6)+'_'+str(j).zfill(2)+".tof", 'w')
                f = open(os.path.join(os.sep,getVNRConst.GetUserDir(),"ana","xml",str(runnumber).zfill(6)+'_'+str(j).zfill(2)+".tof"), 'w') #[inamura 180404]
		#f.write("t_"+str(runnumber)+"\tmp_"+str(runnumber)+"\temp_"+str(runnumber)+"\tpp_"+str(runnumber)+"\tepp_"+str(runnumber)+"\tmm_"+str(runnumber)+"\temm_"+str(runnumber)+"\tpm_"+str(runnumber)+"\tepm_"+str(runnumber)+"\n")
		for i in range(len(int1)):
##      	    f.write("%5.1f\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i], int2[i], err2[i], int3[i], err3[i], int4[i], err4[i]))
		    f.write("%5.1f\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i]))
		f.close()
		ECA += [EC]
	    return ECA
	else:
	    ECA  = mm.ElementContainer()
	    if ( histDatas[3] > 0):
		hh = mm.HeaderBase()
		hh.Add("RUNNUMBER", str(runnumber))
		hh.Add("XAxis", "TOF")
		hh.Add("XLABEL", "TOF")
		if ( t0Normalize == True):
		    hh.Add("YLABEL", "Intensity")
		else:
		    hh.Add("YLABEL", "Counts")
		intensity_array = histDatas[0].tolist()
		hh.Add("TotalCount",sum(intensity_array))
		hh.Add("T0Count",histDatas[3])
		if ( a2th != -9999.9):
		    hh.Add("A2TH", a2th)
		ECA  = mm.ElementContainer(hh)
		ECA.Add("TOF", histDatas[2].tolist(), "microsec")
		ECA.Add("Intensity", intensity_array, "Counts")
		ECA.Add("Error", histDatas[1].tolist(), "Counts")
		ECA.SetKeys("TOF","Intensity","Error")

		tof1 = ECA.ReduceColumn( ECA.PutXKey())
		int1 = ECA.PutY()
		err1 = ECA.PutE()

		#f = open("/usr/local/mlf/VNR/ana/xml/"+str(runnumber).zfill(6)+".tof", 'w')
                f = open(os.path.join(os.sep,getVNRConst.GetUserDir(),"ana","xml",str(runnumber).zfill(6)+".tof"), 'w') #[inamura 180404]
		#f.write("t_"+str(runnumber)+"\tmp_"+str(runnumber)+"\temp_"+str(runnumber)+"\tpp_"+str(runnumber)+"\tepp_"+str(runnumber)+"\tmm_"+str(runnumber)+"\temm_"+str(runnumber)+"\tpm_"+str(runnumber)+"\tepm_"+str(runnumber)+"\n")
		for i in range(len(int1)):
##      	    f.write("%5.1f\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i], int2[i], err2[i], int3[i], err3[i], int4[i], err4[i]))
		    f.write("%5.1f\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i]))
		f.close()
	    return ECA

#########################################
def GetHist0dDetector(runnumber=123016, initial_bin=10000.0,final_bin=38100.0,delta_bin=100.0, binType=0, t0Normalize=True):
        """
        Load EventData and convert to histogram for VNR
        @param  runnumber    (int) Run Number
        @param  initial_bin  (double) 
        @param  final_bin    (double) 
        @param  delta_bin    (double) 
        @param  binType      (int) 
        @param  t0Normalize  (boolen)  
        @retval EC           (ElementContainer)
        """
	filterCondition = None
	positionCondition = None
	filePosition = None
	#binType=0
	#binInfo=( int(initial_bin), int(final_bin), int(delta_bin))
	binInfo=( initial_bin, final_bin, delta_bin)
	detector='0D'
	dioFlag=-1
	if 'MLF_DATA_DIR' in os.environ:
	    datadir = os.environ['MLF_DATA_DIR']
	else:
	    #datadir = os.path.join(os.sep,"data",XXX)
            datadir = getVNRConst.GetDataDir(True) #[inamura 180326]
	#trignetData = getTrignetData( runnumber, datadir)
	trignetData = None
	#t0Normalize=True

	histDatas = getNeutronData( runnumber,datadir, detector, binInfo, binType,
			t0Normalize, trignetData,
			filterCondition,
                        positionCondition,filePosition)
	EC  = mm.ElementContainer()
	if ( histDatas[3] > 0):
	    hh = mm.HeaderBase()
	    hh.Add("RUNNUMBER", str(runnumber))
	    hh.Add("XAxis", "TOF")
	    hh.Add("XLABEL", "TOF")
	    if ( t0Normalize == True):
		hh.Add("YLABEL", "Intensity")
	    else:
		hh.Add("YLABEL", "Counts")
	    intensity_array = histDatas[0].tolist()
	    hh.Add("TotalCount",sum(intensity_array))
	    hh.Add("T0Count",histDatas[3])
	    a2th = PickupCurpos(runnumber, 'A2TH')
	    if ( a2th != -9999.9):
		hh.Add("A2TH", a2th)
	    EC  = mm.ElementContainer(hh)
	    EC.Add("TOF", histDatas[2].tolist(), "microsec")
	    EC.Add("Intensity", intensity_array, "Counts")
	    EC.Add("Error", histDatas[1].tolist(), "Counts")
	    EC.SetKeys("TOF","Intensity","Error")

	    tof1 = EC.ReduceColumn( EC.PutXKey())
	    int1 = EC.PutY()
	    err1 = EC.PutE()

	    #f = open("/usr/local/mlf/VNR/ana/xml/"+str(runnumber).zfill(6)+".tof", 'w')
            f = open(os.path.join(os.sep,getVNRConst.GetUserDir(),"ana","xml",str(runnumber).zfill(6)+".tof"), 'w') #[inamura 180404]
	    #f.write("t_"+str(runnumber)+"\tmp_"+str(runnumber)+"\temp_"+str(runnumber)+"\tpp_"+str(runnumber)+"\tepp_"+str(runnumber)+"\tmm_"+str(runnumber)+"\temm_"+str(runnumber)+"\tpm_"+str(runnumber)+"\tepm_"+str(runnumber)+"\n")
	    for i in range(len(int1)):
##      	f.write("%5.1f\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i], int2[i], err2[i], int3[i], err3[i], int4[i], err4[i]))
		f.write("%5.1f\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i]))
	    f.close()
	return EC 


#########################################
def GetHist0dDetectorTrend(runnumber=111968, detector='0D', timerange='0,-1', timestep=-1, flipper='-1',swing=False):
        """
        Load EventData and draw trend-graph (for 0D detector)
        @param  runnumber    (int) Run Number
        @param  detector     (string) '0D', 'He', N2' 
        @param  timerange    (string) min, max 
        @param  timestep     (int) or -1 (not use) 
        @param  flipper	     (string) po, sf2, sf3 or '-1' (not use) 
        @param  swing	     (boolen)  
        @retval EC	     (ElementContainer[])
        """
	#detector='0D'
	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

	if 'MLF_DATA_DIR' in os.environ:
	    datadir = os.environ['MLF_DATA_DIR']
	else:
	    #datadir = os.path.join(os.sep,"data",XXX)
            datadir = getVNRConst.GetDataDir(True) #[inamura 180326]
	if ( flipper != '-1'):
	    if ( swing == True):
		if ( flipper == 'po'):
		    dioFlag = modeDio12Swing( flipper)
		else:
		    dioFlag = modeDioSwing( flipper)
	    else:
		if ( flipper == 'po'):
		    dioFlag = modeDio12( flipper)
		else:
		    dioFlag = modeDio( flipper)
	    trignetData = getTrignetData( runnumber, datadir)
	else:
	    trignetData = None
	    dioFlag = None

	EC = []
	a2th = PickupCurpos(runnumber, 'A2TH')
	if ( trignetData == None):
	    histDatas = getNeutronDataTrend( runnumber,datadir, detector,				trignetData, dioFlag, nT0start, nT0end, nT0step)
	    if ( histDatas[3] > 0):
		hh = mm.HeaderBase()
		hh.Add("RUNNUMBER", str(runnumber))
		hh.Add("XAxis", "Time")
		hh.Add("XLABEL", "Time")
		hh.Add("YLABEL", "Counts")
		intensity_array = histDatas[0].tolist()
		hh.Add("TotalCount",sum(intensity_array))
		hh.Add("T0Count",histDatas[3])
		if ( a2th != -9999.9):
		    hh.Add("A2TH", a2th)
		#hh.Add("Label", Label)
		EC  = mm.ElementContainer(hh)
		EC.Add("Time", histDatas[2].tolist(),"seconds")
		EC.Add("Intensity", intensity_array, "Counts")
		EC.Add("Error", histDatas[1].tolist(), "Counts")
		EC.SetKeys("Time","Intensity","Error")

		tof1 = EC.ReduceColumn( EC.PutXKey())
		int1 = EC.PutY()
		err1 = EC.PutE()

		#f = open("/usr/local/mlf/VNR/ana/xml/"+str(runnumber).zfill(6)+".t", 'w')
                f = open(os.path.join(os.sep,getVNRConst.GetUserDir(),"ana","xml",str(runnumber).zfill(6)+".t"), 'w') #[inamura 180404]
		#f.write("t_"+str(runnumber)+"\tmp_"+str(runnumber)+"\temp_"+str(runnumber)+"\tpp_"+str(runnumber)+"\tepp_"+str(runnumber)+"\tmm_"+str(runnumber)+"\temm_"+str(runnumber)+"\tpm_"+str(runnumber)+"\tepm_"+str(runnumber)+"\n")
		for i in range(len(int1)):
##      	    f.write("%5.1f\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i], int2[i], err2[i], int3[i], err3[i], int4[i], err4[i]))
		    f.write("%5.1f\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i]))
		f.close()
	else:
	  if ( flipper == 'po'):
	    j = 2
	  else:
	    j = 4
	  for i in range(j):
	    histDatas = getNeutronDataTrend( runnumber,datadir, detector,				trignetData, dioFlag[i],nT0start,nT0end,nT0step)
	    if ( histDatas[3] > 0):
		hh = mm.HeaderBase()
		hh.Add("RUNNUMBER", str(runnumber))
		hh.Add("XAxis", "Time")
		hh.Add("XLABEL", "Time")
		hh.Add("YLABEL", "Counts")
		intensity_array = histDatas[0].tolist()
		hh.Add("TotalCount",sum(intensity_array))
		hh.Add("T0Count",histDatas[3])
		if ( a2th != -9999.9):
		    hh.Add("A2TH", a2th)
		if ( i == 0):
		    if ( flipper == 'po'):
			Label = "m"
		    else:
			Label = "mp"
		else:
		    if ( i == 1):
			if ( flipper == 'po'):
			    Label = "p"
			else:
			    Label = "pp"
		    else:
			if ( i == 2):
			    Label = "mm"
			else:
			    Label = "pm"
		hh.Add("Label", Label)
		ec  = mm.ElementContainer(hh)
		ec.Add("Time", histDatas[2].tolist(),"seconds")
		ec.Add("Intensity", intensity_array, "Counts")
		ec.Add("Error", histDatas[1].tolist(), "Counts")
		ec.SetKeys("Time","Intensity","Error")
		EC += [ec]

	  if ( len( EC) == j):
	    #f = open("/usr/local/mlf/VNR/ana/xml/"+str(runnumber).zfill(6)+".t", 'w')
            f = open(os.path.join(os.sep,getVNRConst.GetUserDir(),"ana","xml",str(runnumber).zfill(6)+".t"), 'w') #[inamura 180404]
	    tof1 = EC[0].ReduceColumn( EC[0].PutXKey())
	    int1 = EC[0].PutY()
	    err1 = EC[0].PutE()
	    int2 = EC[1].PutY()
	    err2 = EC[1].PutE()
	    if ( flipper == 'po'):
		f.write("t_"+str(runnumber)+"\tm_"+str(runnumber)+"\tmp_"+str(runnumber)+"\tp_"+str(runnumber)+"\tep_"+str(runnumber)+"\n")
		for i in range(len(int1)):
		    try:
			f.write("%5.1f\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i], int2[i], err2[i]))
		    except IndexError:
			print('There are no data histogram. Data is too few.')
	    else:
		int3 = EC[2].PutY()
		err3 = EC[2].PutE()
		int4 = EC[3].PutY()
		err4 = EC[3].PutE()
		f.write("t_"+str(runnumber)+"\tmp_"+str(runnumber)+"\temp_"+str(runnumber)+"\tpp_"+str(runnumber)+"\tepp_"+str(runnumber)+"\tmm_"+str(runnumber)+"\temm_"+str(runnumber)+"\tpm_"+str(runnumber)+"\tepm_"+str(runnumber)+"\n")
		for i in range(len(int1)):
		    try:
			f.write("%5.1f\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i], int2[i], err2[i], int3[i], err3[i], int4[i], err4[i]))
		    except IndexError:
			print('There are no data histogram. Data is too few.')
	    f.close()

	return EC

#########################################
def GetHist0dDetectorDio(runnumber=120966, initial_bin=10000.0,final_bin=38100.0,delta_bin=100.0,binType=0,t0Normalize=True,flipper='sf3',swing=False):
        """
        Load PA-EventData and convert to histogram for VNR
        @param  runnumber    (int) Run Number
        @param  initial_bin  (double) 
        @param  final_bin    (double) 
        @param  delta_bin    (double) 
        @param  binType      (int) 
        @param  t0Normalize  (boolen)  
        @param  flipper	     (string)  
        @param  swing	     (boolen)  
        @retval EC	     (ElementContainer[])
        """
	positionCondition = None
	filePosition = None
	#binType=0
	#binInfo=( int(initial_bin), int(final_bin), int(delta_bin))
	binInfo=( initial_bin, final_bin, delta_bin)
	detector='0D'
	if ( swing == True):
	    dioFlag = modeDioSwing( flipper)
	else:
	    dioFlag = modeDio( flipper)
	if 'MLF_DATA_DIR' in os.environ:
	    datadir = os.environ['MLF_DATA_DIR']
	else:
	    #datadir = os.path.join(os.sep,"data",XXX)
            datadir = getVNRConst.GetDataDir(True) #[inamura 180326]
	trignetData = getTrignetData( runnumber, datadir)
	#t0Normalize=True

	EC = []
	a2th = PickupCurpos(runnumber, 'A2TH')
	for i in range(4):
	    histDatas = getNeutronData( runnumber,datadir, detector, binInfo, binType,
			t0Normalize, trignetData, dioFlag[i], 
			positionCondition,filePosition)
	    if ( histDatas[3] > 0):
		hh = mm.HeaderBase()
		hh.Add("RUNNUMBER", str(runnumber))
		hh.Add("XAxis", "TOF")
		hh.Add("XLABEL", "TOF")
		if ( t0Normalize == True):
		    hh.Add("YLABEL", "Intensity")
		else:
		    hh.Add("YLABEL", "Counts")
		intensity_array = histDatas[0].tolist()
		hh.Add("TotalCount",sum(intensity_array))
		hh.Add("T0Count",histDatas[3])
		if ( a2th != -9999.9):
		    hh.Add("A2TH", a2th)
		if ( i == 0):
		    Label = "mp"
		else:
		    if ( i == 1):
			Label = "pp"
		    else:
			if ( i == 2):
			    Label = "mm"
			else:
			    Label = "pm"
		hh.Add("Label", Label)
		ec  = mm.ElementContainer(hh)
		ec.Add("TOF", histDatas[2].tolist(),"microsec")
		ec.Add("Intensity", intensity_array, "Counts")
		ec.Add("Error", histDatas[1].tolist(), "Counts")
		ec.SetKeys("TOF","Intensity","Error")
		EC += [ec]

	if ( len( EC) == 4):
	    #f = open("/usr/local/mlf/VNR/ana/xml/"+str(runnumber).zfill(6)+".tof", 'w')
            f = open(os.path.join(os.sep,getVNRConst.GetUserDir(),"ana","xml",str(runnumber).zfill(6)+".tof"), 'w') #[inamura 180404]
	    f.write("t_"+str(runnumber)+"\tmp_"+str(runnumber)+"\temp_"+str(runnumber)+"\tpp_"+str(runnumber)+"\tepp_"+str(runnumber)+"\tmm_"+str(runnumber)+"\temm_"+str(runnumber)+"\tpm_"+str(runnumber)+"\tepm_"+str(runnumber)+"\n")
	
	    tof1 = EC[0].ReduceColumn( EC[0].PutXKey())
	    int1 = EC[0].PutY()
	    err1 = EC[0].PutE()
	    int2 = EC[1].PutY()
	    err2 = EC[1].PutE()
	    int3 = EC[2].PutY()
	    err3 = EC[2].PutE()
	    int4 = EC[3].PutY()
	    err4 = EC[3].PutE()

	    for i in range(len(int1)):
		f.write("%5.1f\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i], int2[i], err2[i], int3[i], err3[i], int4[i], err4[i]))
	    f.close()

	return EC


#########################################
def GetHist0dDetectorDioAdd(runnumber=120966, runStr='-1', initial_bin=10000.0,final_bin=38100.0,delta_bin=100.0,binType=0,flipper='sf3',swing=False):
        """
        Load PA-EventData and convert to histogram for VNR
        @param  runnumber    (int) Run Number
        @param  runStr       (string) Run Number 2 and more
        @param  initial_bin  (double) 
        @param  final_bin    (double) 
        @param  delta_bin    (double) 
        @param  binType      (int) 
        @param  flipper	     (string)  
        @param  swing	     (boolen)  
        @retval EC	     (ElementContainer[])
        """
	positionCondition = None
	filePosition = None
	#binType=0
	#binInfo=( int(initial_bin), int(final_bin), int(delta_bin))
	binInfo=( initial_bin, final_bin, delta_bin)
	detector='0D'
	if ( swing == True):
	    dioFlag = modeDioSwing( flipper)
	else:
	    dioFlag = modeDio( flipper)
	if 'MLF_DATA_DIR' in os.environ:
	    datadir = os.environ['MLF_DATA_DIR']
	else:
	    #datadir = os.path.join(os.sep,"data",XXX)
            datadir = getVNRConst.GetDataDir(True) #[inamura 180326]
	trignetData = getTrignetData( runnumber, datadir)
	#t0Normalize=True

	EC = []
	a2th = PickupCurpos(runnumber, 'A2TH')
	t0Norm = False
	for i in range(4):
	    if ( i == 0):
		print("Mode mp:")
	    else:
		if ( i == 1):
		    print("Mode pp:")
		else:
		    if ( i == 2):
			print("Mode mm:")
		    else:
			print("Mode pm:")
	    histDatas = getNeutronData( runnumber,datadir, detector, binInfo, binType,
			t0Norm, trignetData, dioFlag[i], 
			positionCondition,filePosition)
	    if ( histDatas[3] > 0 or runStr != '-1'):
		intensity_array = histDatas[0]
		t0s = histDatas[3]
		if ( runStr != '-1'):
		    runArray=runStr.split('+')
		    for j in range( len( runArray)):
			runnum2 = int(runArray[j])
			trignetData2 = getTrignetData( runnum2 , datadir)
			histData2 = getNeutronData( runnum2,datadir, detector, binInfo, binType,
			    t0Norm, trignetData2, dioFlag[i], 
			    positionCondition,filePosition)
			if ( histData2[3] > 0):
			    intensity_array = intensity_array + histData2[0]
			    t0s += histData2[3]
		err_array = np.sqrt( intensity_array) / float( t0s)
		intensity_array = intensity_array / float( t0s)
		hh = mm.HeaderBase()
		hh.Add("RUNNUMBER", str(runnumber))
		hh.Add("XAxis", "TOF")
		hh.Add("XLABEL", "TOF")
		#if ( t0Normalize == True):
		hh.Add("YLABEL", "Intensity")
		#else:
		#    hh.Add("YLABEL", "Counts")
		intensity_list = intensity_array.tolist()
		hh.Add("TotalCount",sum(intensity_list))
		hh.Add("T0Count", t0s)
		if ( a2th != -9999.9):
		    hh.Add("A2TH", a2th)
		if ( i == 0):
		    Label = "mp"
		else:
		    if ( i == 1):
			Label = "pp"
		    else:
			if ( i == 2):
			    Label = "mm"
			else:
			    Label = "pm"
		hh.Add("Label", Label)
		ec  = mm.ElementContainer(hh)
		ec.Add("TOF", histDatas[2].tolist(),"microsec")
		ec.Add("Intensity", intensity_list, "Counts")
		ec.Add("Error", err_array.tolist(), "Counts")
		ec.SetKeys("TOF","Intensity","Error")
		EC += [ec]

	if ( len( EC) == 4):
	    #f = open("/usr/local/mlf/VNR/ana/xml/"+str(runnumber).zfill(6)+".tof", 'w')
            f = open(os.path.join(os.sep,getVNRConst.GetUserDir(),"ana","xml",str(runnumber).zfill(6)+".tof"), 'w') #[inamura 180404]
	    f.write("t_"+str(runnumber)+"\tmp_"+str(runnumber)+"\temp_"+str(runnumber)+"\tpp_"+str(runnumber)+"\tepp_"+str(runnumber)+"\tmm_"+str(runnumber)+"\temm_"+str(runnumber)+"\tpm_"+str(runnumber)+"\tepm_"+str(runnumber)+"\n")
	
	    tof1 = EC[0].ReduceColumn( EC[0].PutXKey())
	    int1 = EC[0].PutY()
	    err1 = EC[0].PutE()
	    int2 = EC[1].PutY()
	    err2 = EC[1].PutE()
	    int3 = EC[2].PutY()
	    err3 = EC[2].PutE()
	    int4 = EC[3].PutY()
	    err4 = EC[3].PutE()

	    for i in range(len(int1)):
		f.write("%5.1f\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i], int2[i], err2[i], int3[i], err3[i], int4[i], err4[i]))
	    f.close()

	return EC

#########################################
def GetHist0dDetectorDio12Add(runnumber=94738, runStr='-1', initial_bin=10000.0,final_bin=38100.0,delta_bin=100.0,binType=0,flipper='sf3',swing=False):
        """
        Load PO-EventData and convert to histogram for VNR
        @param  runnumber    (int) Run Number
        @param  runStr       (string) Run Number 2 and more
        @param  initial_bin  (double) 
        @param  final_bin    (double) 
        @param  delta_bin    (double) 
        @param  binType      (int) 
        @param  flipper	     (string)  
        @param  swing	     (boolen)  
        @retval EC	     (ElementContainer[])
        """
	positionCondition = None
	filePosition = None
	#binType=0
	#binInfo=( int(initial_bin), int(final_bin), int(delta_bin))
	binInfo=( initial_bin, final_bin, delta_bin)
	detector='0D'
	if ( swing == True):
	    dioFlag = modeDio12Swing( flipper)
	else:
	    dioFlag = modeDio12( flipper)
	if 'MLF_DATA_DIR' in os.environ:
	    datadir = os.environ['MLF_DATA_DIR']
	else:
	    #datadir = os.path.join(os.sep,"data",XXX)
            datadir = getVNRConst.GetDataDir(True) #[inamura 180326]
	trignetData = getTrignetData( runnumber, datadir)
	#t0Normalize=True

	EC = []
	a2th = PickupCurpos(runnumber, 'A2TH')
	t0Norm = False
	for i in range(2):
	    if ( i == 0):
		print("Mode m:")
	    else:
		print("Mode p:")
	    histDatas = getNeutronData( runnumber,datadir, detector, binInfo, binType,
			t0Norm, trignetData, dioFlag[i], 
			positionCondition,filePosition)

	    if ( histDatas[3] > 0 or runStr != '-1'):
		intensity_array = histDatas[0]
		t0s = histDatas[3]
		if ( runStr != '-1'):
		    runArray=runStr.split('+')
		    for j in range( len( runArray)):
			runnum2 = int(runArray[j])
			trignetData2 = getTrignetData( runnum2 , datadir)
			histData2 = getNeutronData( runnum2,datadir, detector, binInfo, binType,
			    t0Norm, trignetData2, dioFlag[i], 
			    positionCondition,filePosition)
			if ( histData2[3] > 0):
			    intensity_array = intensity_array + histData2[0]
			    t0s += histData2[3]
		err_array = np.sqrt( intensity_array) / float( t0s)
		intensity_array = intensity_array / float( t0s)
		hh = mm.HeaderBase()
		hh.Add("RUNNUMBER", str(runnumber))
		hh.Add("XAxis", "TOF")
		hh.Add("XLABEL", "TOF")
		#if ( t0Normalize == True):
		hh.Add("YLABEL", "Intensity")
		#else:
		#    hh.Add("YLABEL", "Counts")
		intensity_list = intensity_array.tolist()
		hh.Add("TotalCount",sum(intensity_array))
		hh.Add("T0Count",histDatas[3])
		if ( a2th != -9999.9):
		    hh.Add("A2TH", a2th)
		if ( i == 0):
		    Label = "m"
		else:
		    Label = "p"
		hh.Add("Label", Label)
		ec  = mm.ElementContainer(hh)
		ec.Add("TOF", histDatas[2].tolist(), "microsec")
		ec.Add("Intensity", intensity_list, "Counts")
		ec.Add("Error", err_array.tolist(), "Counts")
		ec.SetKeys("TOF","Intensity","Error")
		EC += [ec]

	if ( len(EC) == 2):
	    #f = open("/usr/local/mlf/VNR/ana/xml/"+str(runnumber).zfill(6)+".tof", 'w')
            f = open(os.path.join(os.sep,getVNRConst.GetUserDir(),"ana","xml",str(runnumber).zfill(6)+".tof"), 'w') #[inamura 180404]
	    f.write("t_"+str(runnumber)+"\tm_"+str(runnumber)+"\tem_"+str(runnumber)+"\tp_"+str(runnumber)+"\tep_"+str(runnumber)+"\n")

	    tof1 = EC[0].ReduceColumn( EC[0].PutXKey())
	    int1 = EC[0].PutY()
	    err1 = EC[0].PutE()
	    int2 = EC[1].PutY()
	    err2 = EC[1].PutE()

	    for i in range(len(int1)):
		f.write("%5.1f\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i], int2[i], err2[i]))
	    f.close()

	return EC

#########################################
def GetHist0dDetectorDio12(runnumber=94738, initial_bin=10000.0,final_bin=38100.0,delta_bin=100.0,binType=0,t0Normalize=True,flipper='sf3',swing=False):
        """
        Load PO-EventData and convert to histogram for VNR
        @param  runnumber    (int) Run Number
        @param  initial_bin  (double) 
        @param  final_bin    (double) 
        @param  delta_bin    (double) 
        @param  binType      (int) 
        @param  t0Normalize  (boolen)  
        @param  flipper	     (string)  
        @param  swing	     (boolen)  
        @retval EC	     (ElementContainer[])
        """
	positionCondition = None
	filePosition = None
	#binType=0
	#binInfo=( int(initial_bin), int(final_bin), int(delta_bin))
	binInfo=( initial_bin, final_bin, delta_bin)
	detector='0D'
	if ( swing == True):
	    dioFlag = modeDio12Swing( flipper)
	else:
	    dioFlag = modeDio12( flipper)
	if 'MLF_DATA_DIR' in os.environ:
	    datadir = os.environ['MLF_DATA_DIR']
	else:
	    #datadir = os.path.join(os.sep,"data",XXX)
            datadir = getVNRConst.GetDataDir(True) #[inamura 180326]
	trignetData = getTrignetData( runnumber, datadir)
	#t0Normalize=True

	EC = []
	a2th = PickupCurpos(runnumber, 'A2TH')
	for i in range(2):
	    histDatas = getNeutronData( runnumber,datadir, detector, binInfo, binType,
			t0Normalize, trignetData, dioFlag[i], 
			positionCondition,filePosition)
	    if ( histDatas[3] > 0):
		hh = mm.HeaderBase()
		hh.Add("RUNNUMBER", str(runnumber))
		hh.Add("XAxis", "TOF")
		hh.Add("XLABEL", "TOF")
		if ( t0Normalize == True):
		    hh.Add("YLABEL", "Intensity")
		else:
		    hh.Add("YLABEL", "Counts")
		intensity_array = histDatas[0].tolist()
		hh.Add("TotalCount",sum(intensity_array))
		hh.Add("T0Count",histDatas[3])
		if ( a2th != -9999.9):
		    hh.Add("A2TH", a2th)
		if ( i == 0):
		    Label = "m"
		else:
		    Label = "p"
		hh.Add("Label", Label)
		ec  = mm.ElementContainer(hh)
		ec.Add("TOF", histDatas[2].tolist(), "microsec")
		ec.Add("Intensity", intensity_array, "Counts")
		ec.Add("Error", histDatas[1].tolist(), "Counts")
		ec.SetKeys("TOF","Intensity","Error")
		EC += [ec]

	if ( len(EC) == 2):
	    #f = open("/usr/local/mlf/VNR/ana/xml/"+str(runnumber).zfill(6)+".tof", 'w')
            f = open(os.path.join(os.sep,getVNRConst.GetUserDir(),"ana","xml",str(runnumber).zfill(6)+".tof"), 'w') #[inamura 180404]
	    f.write("t_"+str(runnumber)+"\tm_"+str(runnumber)+"\tem_"+str(runnumber)+"\tp_"+str(runnumber)+"\tep_"+str(runnumber)+"\n")

	    tof1 = EC[0].ReduceColumn( EC[0].PutXKey())
	    int1 = EC[0].PutY()
	    err1 = EC[0].PutE()
	    int2 = EC[1].PutY()
	    err2 = EC[1].PutE()

	    for i in range(len(int1)):
		f.write("%5.1f\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (tof1[i], int1[i], err1[i], int2[i], err2[i]))
	    f.close()

	return EC

#########################################
def ECDividedByEC(ec1=EC, ec2=ec2):
	"""
	ECDividedByEC(ec1,ec2)
	@param   ec1  (ElementContainer)
	@param   ec2  (ElementContainer)
	@retval  EC   (ElementContainer)
	"""
	hh = ec1.PutHeader()
	#q1 = ec1.PutX()
	#q2 = ec2.PutX()
	#print "ec1:", len(q1), " Start:", q1[0], " End: ", q1[-1]
	#print "ec2:", len(q2), " Start:", q2[0], " End: ", q2[-1]
	EC = ec1/ec2
	EC.InputHeader(hh)
	q = EC.PutX()
	print("EC: ", len(q), " Start:", q[0], " End: ", q[-1])

	return EC

#########################################
def ECPDividedByEC(ec1=EC, ec2=ec2):
	"""
	ECPDividedByEC(ec1,ec2)
	@param  ec1  (ElementContainer PA,PO)
	@param  ec2  (ElementContainer)
	@retval EC   (ElementContainerlist)
	"""
	EC = []
	for i in range( len(ec1)):
	    hh = ec1[i].PutHeader()
	    ecp = ec1[i]/ec2
	    ecp.InputHeader(hh)
	    EC += [ecp]

	return EC

def PAcal_r( pn, epn, mn, emn):
	r = pn / mn
	er = r * np.sqrt( epn * epn / pn / pn + emn * emn / mn / mn) 
	for i in range( len(r)):
	    if ( np.isinf( r[i])):
		r[i] = 1.0
		er[i] = 0.0
	    if ( np.isinf(er[i])):
		r[i] = 0.0
		er[i] = 0.0
	return r, er 

def PAcal_pa( r1, er1, r2, er2, r3, er3):
	d3 =  r3 - ( r1 * r2)
	pa = ( 1.0 - r1) * (1.0 - r2) / d3
	d1 = ( r2 * (pa + 1.0) - 1.0) * er1
	d2 = ( r1 * (pa + 1.0) - 1.0) * er2
	epa = np.sqrt( d1*d1 + d2*d2 + pa*pa*er3*er3) / d3
	return pa, epa

def PAcal_f( r1, er1, r2, er2, r3, er3):
	f = (r3 + 1.0 - r1 - r2) / (1.0 - r2) / 2.0
	ef = np.sqrt( er1*er1 + er3*er3 + (f - 1.0)*(f - 1.0)*er2*er2) / (1.0 - r2) / 2.0
	return  f, ef

def PAcheck_r3( pa, r3):
	if ( np.mean( pa) < 0.0):
	    for i in range( len( r3)):
		if ( r3[i] < 1.0):
		    r3[i] = 1.0
		    print("Warning!! R3[%d] is less than 1.0. It is forced to be 1.0.\n" % (i))
	else:
	    for i in range( len( r3)):
		if ( r3[i] > 1.0):
		    r3[i] = 1.0
		    print("Warning!! R3[%d] exceeds 1.0. It is forced to be 1.0.\n" % (i))
	return r3

#########################################
def ReflectivityPA(ec=ec,ec0=ec0,cmode1=1,cmode2=0):
	"""
	Reflectivity for PA ( ec, ec0)
	@param   ec   (ElementContainer)
	@param   ec0  (ElementContainer) i0
	@param   cmode1 (int) 0,1,2
	@param   cmode2 (int) 0,1
	@retval  EC   (ElementContainer)
	"""
	EC = []
	if ( len(ec) == 4 and len(ec0) == 4):
	    q  = ec[0].PutXList()
	    i1 = np.array( ec[0].PutYList())
	    e1 = np.array( ec[0].PutEList())
	    i2 = np.array( ec[1].PutYList())
	    e2 = np.array( ec[1].PutEList())
	    i3 = np.array( ec[2].PutYList())
	    e3 = np.array( ec[2].PutEList())
	    i4 = np.array( ec[3].PutYList())
	    e4 = np.array( ec[3].PutEList())
	    mp  = np.array( ec0[0].PutYList())
	    emp = np.array( ec0[0].PutEList())
	    pp  = np.array( ec0[1].PutYList())
	    epp = np.array( ec0[1].PutEList())
	    mmx = np.array( ec0[2].PutYList())
	    emm = np.array( ec0[2].PutEList())
	    pm  = np.array( ec0[3].PutYList())
	    epm = np.array( ec0[3].PutEList())

	    # Polarization Parameters
	    r1, er1 = PAcal_r( pp, epp, mp, emp)
	    r2, er2 = PAcal_r( mmx, emm, mp, emp)
	    r3, er3 = PAcal_r( pm, epm, mp, emp)
	    if ( cmode1 > 0):
		pa, epa = PAcal_pa( r1, er1, r2, er2, r3, er3)
		r3 = PAcheck_r3( pa, r3)
	    pa, epa = PAcal_pa( r1, er1, r2, er2, r3, er3)
	    f1, ef1 = PAcal_f( r1, er1, r2, er2, r3, er3)
	    f2, ef2 = PAcal_f( r2, er2, r1, er1, r3, er3)

	    ## i0 = 4.0 * (pp + pm + mp + mm)
	    ## ei0 = 4.0 * np.sqrt( epp*epp + epm*epm + emp*emp + emm*emm)

	    # trimming
	    if ( cmode2 == 1):
		for i in range( len( pa)):
		    if ( f1[i] > 1.0):
			f1[i] = 1.0
		    else:
		        if ( f1[i] < -1.0):
			     f1[i] = -1.0
		    if ( f2[i] > 1.0):
			f2[i] = 1.0
		    else:
		        if ( f2[i] < -1.0):
			     f2[i] = -1.0
		    if ( pa[i] > 1.0):
			pa[i] = 1.0
		    else:
		        if ( pa[i] < -1.0):
			     pa[i] = -1.0
	    if ( cmode1 == 0):
		print("Calculation without any polarization corrections.")
		p2 = np.ones( len(pa))
		f1 = p2
		f2 = p2
		p1 = - p2
		pa = p1
		ep1 = np.zeros( len( p1))
		ep2 = ep1
		ef1 = ep1
		ef2 = ep1 
		epa = ep1 
	    else:
		if ( cmode1 == 1):
		    print("Calculation with polarization corrections (R+- and R-+ are  independent.).")
		    p1 = - np.sqrt( np.fabs( pa))
		    ep1 = 0.5 * p1 * np.fabs( epa/pa)
		    p2 = - p1
		    ep2 = - ep1
		else:
		    print("Calculation with polarization corrections (R+- = R-+ constraint).")
		    # cal_p1
		    p10 = (2.0 * f2 - 1.0)*i1 - (2.0 * f2 - 1.0)*i2 + i3 - i4
		    p11 = (2.0 * f1 - 1.0)*i1 - (2.0 * f1 - 1.0)*i3 + i2 - i4
		    p1 = - np.sqrt( np.fabs( p10 / p11 * pa))
		    d1 = (4.0*(i1-i3)*(i1-i3)*ef1*ef1 +(2.0*f1-1.0)*(2.0*f1-1.0)*(e1*e1+e3*e3)+e2*e2+e4*e4)/p11/p11
		    d2 = (4.0*(i1-i2)*(i1-i2)*ef2*ef2 +(2.0*f2-1.0)*(2.0*f2-1.0)*(e1*e1+e2*e2)+e3*e3+e4*e4)/p10/p10
		    ep1 = 0.5 * p1 * np.sqrt( d1 + d2 + epa*epa/pa/pa)
		    # cal_p2
		    p2 = pa / p1
		    ep2 = p2 * np.sqrt( epa*epa/pa/pa + ep1*ep1/p1/p1)
	    # trimming
	    if ( cmode2 == 1):
		print(" with additional constraint ( 0.0 < f1 < 1.0, 0.0 <  f2 < 1.0, -1.0 <  p < 1.0)")
		for i in range( len( p1)):
		    if ( p1[i] > 1.0):
			p1[i] = 1.0
		    else:
		        if ( p1[i] < -1.0):
			     p1[i] = -1.0
		    if ( p2[i] > 1.0):
			p2[i] = 1.0
		    else:
		        if ( p2[i] < -1.0):
			     p2[i] = -1.0
	    a = p1 + 1.0
	    b = p2 + 1.0
	    c = 1.0 - p1
	    d = 1.0 - p2
	    e = 1.0 - (2.0 * f1 - 1.0) * p1
	    f = 1.0 - (2.0 * f2 - 1.0) * p2
	    g = 1.0 + (2.0 * f1 - 1.0) * p1
	    h = 1.0 + (2.0 * f2 - 1.0) * p2

	    # cal_i0
	    # *i0_i1 = mp, *err_i0_i1 = e_mp;
	    # *i0_i2 = pp, *err_i0_i2 = e_pp;
	    # *i0_i3 = mm, *err_i0_i3 = e_mm;
	    # *i0_i4 = pm, *err_i0_i4 = e_pm;
	    i0f = mp + pp + mmx + pm
	    ff = 1.0 + (1.0 - f1)*(1.0 - f2)*pa
	    i0 = i0f / ff / 8.0
	    d1 = (f2 - 1.0)* pa * ef1
	    d2 = (f1 - 1.0)* pa * ef2
	    d3 = (f2 - 1.0)*(f1 - 1.0)* epa
	    ei0 = i0 * np.sqrt( ((d1*d1+d2*d2+d3*d3)/ff/ff)+(emp*emp+epp*epp+emm*emm+epm*epm)/i0f/i0f)

	    # cal_reflectivity_pa
	    i0f = 16.0 * f1 * f2 * pa * i0

	    r_pp = (d * (c * i4 - g * i3) - (c * i2 - g * i1) * h) / i0f
            d1 = (2.0 * p1 * (h * i1 - d * i3)/i0f - r_pp/f1) * ef1
            d2 = (2.0 * p2 * (g * i1 - c * i2)/i0f + r_pp/f2) * ef2
            d3 = (((i2 + (2.0 * f1 -1.0) * i1) * h - d * (i4 + (2.0 * f1 - 1.0) * i3))/i0f - r_pp/p1) * ep1
            d4 = (((2.0 * f2 - 1.0) * (g * i1 - c * i2) + g * i3 - c * i4)/i0f - r_pp/p2) * ep2
            d5 = r_pp/i0 * ei0
            d6 = g * h / i0f * e1
            d7 = c * h / i0f * e2
            d8 = d * g / i0f * e3
            d9 = c * d / i0f * e4
            err_pp = np.sqrt( d1*d1+d2*d2+d3*d3+d4*d4+d5*d5+d6*d6+d7*d7+d8*d8+d9*d9)
	    r_pm = ((c * i2 - g * i1) * f - b * (c * i4 - g * i3)) / i0f
	    d1 = (2.0 * p1 * (i1 * f - b * i3)/i0f + r_pm/f1) * ef1
	    d2 = (2.0 * p2 * (c * i2 - g * i1)/i0f - r_pm/f2) * ef2
	    d3 = (((i2 + (2.0 * f1 -1.0) * i1) * f - b * (i4 + (2.0 * f1 - 1.0) * i3))/i0f - r_pm/p1) * ep1
	    d4 = (((c * i2 - g * i1) * (2.0 * f2 -1.0) + c * i4 - g * i3)/i0f - r_pm/p2) * ep2
	    d5 = r_pm/i0 * ei0
	    d6 = f * g / i0f * e1
	    d7 = c * f / i0f * e2
	    d8 = b * g / i0f * e3
	    d9 = b * c / i0f * e4
	    err_pm = np.sqrt( d1*d1+d2*d2+d3*d3+d4*d4+d5*d5+d6*d6+d7*d7+d8*d8+d9*d9)

	    r_mp = ((a * i2 - e * i1) * h - d * (a * i4 - e * i3)) / i0f
	    d1 = (2.0 * p1 * (i1 * h - d * i3) / i0f - r_mp/f1) * ef1
	    d2 = (2.0 * p2 * (e * i1 - a * i2) / i0f + r_mp/f2) * ef2
	    d3 = (((i2 + (2.0 * f1 -1.0) * i1) * h - d * (i4 + (2.0 * f1 - 1.0) * i3)) / i0f - r_mp/p1) * ep1
	    d4 = (((a * i2 - e * i1) * (2.0 * f2 -1.0) + a * i4 - e * i3) / i0f - r_mp/p2) * ep2
	    d5 = r_mp/i0 * ei0
	    d6 = e * h / i0f * e1
	    d7 = a * h / i0f * e2
	    d8 = d * e / i0f * e3
	    d9 = a * d / i0f * e4
	    err_mp = np.sqrt( d1*d1+d2*d2+d3*d3+d4*d4+d5*d5+d6*d6+d7*d7+d8*d8+d9*d9)

	    r_mm = (b * (a * i4 - e * i3) - (a * i2 - e * i1) * f) / i0f
	    d1 = (2.0 * p1 * (b * i3 - f * i1) / i0f - r_mm/f1) * ef1
	    d2 = (2.0 * p2 * (a * i2 - e * i1) / i0f - r_mm/f2) * ef2
	    d3 = ((b * (i4 + (2.0 * f1 - 1.0) * i3) - (i2 + (2.0 * f1 - 1.0) * i1) * f) / i0f - r_mm/p1) * ep1
	    d4 = ((a * i4 - e * i3 +  (a * i2 - e * i1) * (2.0 * f2 - 1.0)) / i0f - r_mm/p2) * ep2
	    d5 = r_mm/i0 * ei0
	    d6 = e * f / i0f * e1
	    d7 = a * f / i0f * e2
	    d8 = b * e / i0f * e3
	    d9 = a * b / i0f * e4
	    err_mm = np.sqrt( d1*d1+d2*d2+d3*d3+d4*d4+d5*d5+d6*d6+d7*d7+d8*d8+d9*d9)

	    for i in range( len(r_pm)):
		if (r_pm[i] < 0.0):
		    r_pm[i] = 0.0
		    err_pm[i] = 0.0
		if (r_mp[i] < 0.0):
		    r_mp[i] = 0.0
		    err_mp[i] = 0.0

	    del d9
	    del d8
	    del d7
	    del d6
	    del d5
	    del d4
	    del d3
	    del d2
	    del d1
	    del a
	    del b
	    del c
	    del d
	    del e
	    del f
	    del g
	    del h
	    del r1
	    del r2
	    del r3
	    del er1
	    del er2
	    del er3
	    del f1
	    del f2
	    del ef1
	    del ef2
	    del p1
	    del p2
	    del ep1
	    del ep2
	    del i0
	    del ei0
	    del pa
	    del epa
	    del ff
	    del i0f

	    del epm
	    del pm
	    del emm
	    del mmx
	    del epp
	    del pp
	    del emp
	    del mp
	    del e4
	    del i4
	    del e3
	    del i3
	    del e2
	    del i2
	    del e1
	    del i1

	    header = ec[0].PutHeader()
	    runnumber = header.PutString("RUNNUMBER")
	    ylabel = "Intensity"
	    if header.CheckKey("YLABEL"):
		ylabel = header.PutString("YLABEL")

	    hh = mm.HeaderBase()
	    hh.Add("RUNNUMBER", runnumber)
	    hh.Add("XAxis", "Q")
	    hh.Add("XLABEL", "q")
	    hh.Add("YLABEL", ylabel)
	    hh.Add("Label", "mp")
	    ec1 = mm.ElementContainer(hh)
	    ec1.Add("Q", q, "nm-1")
	    ec1.Add("Intensity", r_mp.tolist(), "Counts")
	    ec1.Add("Error", err_mp.tolist(), "Counts")
	    ec1.SetKeys("Q","Intensity","Error")

	    hh1 = mm.HeaderBase()
	    hh1.Add("RUNNUMBER", runnumber)
	    hh1.Add("XAxis", "Q")
	    hh1.Add("XLABEL", "q")
	    hh1.Add("YLABEL", ylabel)
	    hh1.Add("Label", "pp")
	    ec2 = mm.ElementContainer(hh1)
	    ec2.Add("Q", q, "nm-1")
	    ec2.Add("Intensity", r_pp.tolist(), "Counts")
	    ec2.Add("Error", err_pp.tolist(), "Counts")
	    ec2.SetKeys("Q","Intensity","Error")

	    hh2 = mm.HeaderBase()
	    hh2.Add("RUNNUMBER", runnumber)
	    hh2.Add("XAxis", "Q")
	    hh2.Add("XLABEL", "q")
	    hh2.Add("YLABEL", ylabel)
	    hh2.Add("Label", "mm")
	    ec3 = mm.ElementContainer(hh2)
	    ec3.Add("Q", q, "nm-1")
	    ec3.Add("Intensity", r_mm.tolist(), "Counts")
	    ec3.Add("Error", err_mm.tolist(), "Counts")
	    ec3.SetKeys("Q","Intensity","Error")

	    hh3 = mm.HeaderBase()
	    hh3.Add("RUNNUMBER", runnumber)
	    hh3.Add("XAxis", "Q")
	    hh3.Add("XLABEL", "q")
	    hh3.Add("YLABEL", ylabel)
	    hh3.Add("Label", "pm")
	    ec4 = mm.ElementContainer(hh3)
	    ec4.Add("Q", q, "nm-1")
	    ec4.Add("Intensity", r_pm.tolist(), "Counts")
	    ec4.Add("Error", err_pm.tolist(), "Counts")
	    ec4.SetKeys("Q","Intensity","Error")

	    del err_pm
	    del r_pm
	    del err_mm
	    del r_mm
	    del err_pp
	    del r_pp
	    del err_mp
	    del r_mp
	    del q

	    del hh3
	    del hh2
	    del hh1
	    del hh
	    del header

	    EC = [ec1, ec2, ec3, ec4]
	else:
	    print("ElementConteiner need four EC")
	return EC

#########################################
def ReflectivityPO(ec=ec,ec0=ec0,ec1=ec1,cmode1=1):
	"""
	Reflectivity for PO ( ec, ec0, ec1)
	@param   ec   (ElementContainer) [2]
	@param   ec0  (ElementContainer) i0
	@param   ec1  (ElementContainer) [4]
	@param   cmode1 (int) 0,1
	@retval  EC   (ElementContainer)
	"""
	EC = []
	if ( len(ec) < 2):
	    print("ec not have list")
	if ( isinstance(ec0,list) == False and len(ec) >= 2 and len(ec1) == 4):
	    q  = ec[0].PutXList()
	    i_m = np.array( ec[0].PutYList())
	    eiof = np.array( ec[0].PutEList())
	    i_p = np.array( ec[1].PutYList())
	    eion = np.array( ec[1].PutEList())
	    i0 = np.array( ec0.PutYList())
	    ei0 = np.array( ec0.PutEList())

	    #i1 = np.array( ec[0].PutYList())
	    #e1 = np.array( ec[0].PutEList())
	    #i2 = np.array( ec[1].PutYList())
	    #e2 = np.array( ec[1].PutEList())
	    #i3 = np.array( ec[2].PutYList())
	    #e3 = np.array( ec[2].PutEList())
	    #i4 = np.array( ec[3].PutYList())
	    #e4 = np.array( ec[3].PutEList())

	    mp  = np.array( ec1[0].PutYList())
	    emp = np.array( ec1[0].PutEList())
	    pp  = np.array( ec1[1].PutYList())
	    epp = np.array( ec1[1].PutEList())
	    mmx = np.array( ec1[2].PutYList())
	    emm = np.array( ec1[2].PutEList())
	    pm  = np.array( ec1[3].PutYList())
	    epm = np.array( ec1[3].PutEList())

	    # Polarization Parameters
	    r1, er1 = PAcal_r( pp, epp, mp, emp)
	    r2, er2 = PAcal_r( mmx, emm, mp, emp)
	    r3, er3 = PAcal_r( pm, epm, mp, emp)
	    if ( cmode1 > 0):
		print("Calculation with polarization corrections.")
		pa, epa = PAcal_pa( r1, er1, r2, er2, r3, er3)
		r3 = PAcheck_r3( pa, r3)
	    pa, epa = PAcal_pa( r1, er1, r2, er2, r3, er3)
	    f1, ef1 = PAcal_f( r1, er1, r2, er2, r3, er3)
	    #f2, ef2 = PAcal_f( r2, er2, r1, er1, r3, er3)

	    ## i0 = 4.0 * (pp + pm + mp + mm)
	    ## ei0 = 4.0 * np.sqrt( epp*epp + epm*epm + emp*emp + emm*emm)

	    p1 = - np.sqrt( np.fabs( pa))
	    if ( len( f1) != len( i0)):
	    ## i0f = 4.0 * f1 * p1 * i0 ----2016-10-04
		print("len f1, p1, i0", len ( f1), len ( p1), len ( i0))
		print("ERROR! : bin width not equal.")
	    i0f = 2.0 * f1 * p1 * i0
	    ep1 = p1 * epa / np.fabs(pa) / 2.0
	    r_p0 = (1.0 + (2.0 * f1 - 1.0) * p1) * i_m - (1.0 - p1) * i_p
	    r_p = r_p0 / i0f

	    d1 = (2.0 * p1 * i_m - r_p0 / f1) * ef1 / i0f
	    d2 = (((2.0 * f1 - 1.0) * i_m + i_p) - r_p0 / p1) * ep1 / i0f
	    d3 = (1.0 + (2.0 * f1 - 1.0) * p1) / i0f * eiof
	    d4 = (1.0 - p1) / i0f * eion
	    d5 = r_p / i0 * ei0
	    err_rp = np.sqrt( d1*d1 + d2*d2 + d3*d3 + d4*d4 + d5*d5)

	    r_m0 = (1.0  + p1) * i_p - (1.0-(2.0 * f1 -1.0) * p1) * i_m
	    r_m = r_m0 / i0f

	    d1 = (2.0 * p1 * i_m - r_m0 / f1) * ef1 / i0f
            d2 = (((2.0 * f1 - 1.0) * i_m + i_p) - r_m0 / p1) * ep1 / i0f
	    d3 = (1.0 - (2.0 * f1 - 1.0) * p1) / i0f * eiof
            d4 = (1.0 + p1) / i0f * eion
            d5 = r_m / i0 * ei0

            err_rm = np.sqrt( d1*d1 + d2*d2 + d3*d3 + d4*d4 + d5*d5)

	    del d5
	    del d4
	    del d3
	    del d2
	    del d1
	    del r1
	    del r2
	    del r3
	    del er1
	    del er2
	    del er3
	    del f1
	    #del f2
	    del ef1
	    #del ef2
	    del p1
	    del ep1
	    del i0
	    del ei0
	    del pa
	    del epa
	    del i0f

	    del epm
	    del pm
	    del emm
	    del mmx
	    del epp
	    del pp
	    del emp
	    del mp
	    del eion
	    del i_p
	    del eiof
	    del i_m
	    del r_p0
	    del r_m0

	    header = ec[0].PutHeader()
	    runnumber = header.PutString("RUNNUMBER")
	    ylabel = "Intensity"
	    if header.CheckKey("YLABEL"):
		ylabel = header.PutString("YLABEL")
	    hh = mm.HeaderBase()
	    hh.Add("RUNNUMBER", runnumber)
	    hh.Add("XAxis", "Q")
	    hh.Add("XLABEL", "q")
	    hh.Add("YLABEL", ylabel)
	    hh.Add("Label", "p")
	    ec1 = mm.ElementContainer(hh)
	    ec1.Add("Q", q, "nm-1")
	    ec1.Add("Intensity", r_p.tolist(), "Counts")
	    ec1.Add("Error", err_rp.tolist(), "Counts")
	    ec1.SetKeys("Q","Intensity","Error")
	    hh1 = mm.HeaderBase()
	    hh1.Add("RUNNUMBER", runnumber)
	    hh1.Add("XAxis", "Q")
	    hh1.Add("XLABEL", "q")
	    hh1.Add("YLABEL", ylabel)
	    hh1.Add("Label", "m")
	    ec2 = mm.ElementContainer(hh1)
	    ec2.Add("Q", q, "nm-1")
	    ec2.Add("Intensity", r_m.tolist(), "Counts")
	    ec2.Add("Error", err_rm.tolist(), "Counts")
	    ec2.SetKeys("Q","Intensity","Error")

	    del err_rm
	    del r_m
	    del err_rp
	    del r_p
	    del q

	    del hh1
	    del hh
	    del header

	    EC = [ec2, ec1]
	else:
	    print("ElementConteiner need four EC")
	return EC

#########################################
def ConvertTof2Qaniso(ec=ec, startQ=-1.0,endQ=-1.0,angle=-1.0):
        """
        Convert TOF to Q for VNR
        @param  ec     (ElementContainer)
        @param  startQ  (double)
        @param  endQ    (double)
        @param  angle   (double)
        @retval EC      (ElementContainer)
        """
	EC = mm.ElementContainer()
 	header = ec.PutHeader()
	if ( angle == -1.0):
	    if header.CheckKey("A2TH"):
		angle2th = header.PutDouble("A2TH")
		angle = angle2th / 2.0
	    else:
		print("")
		print("Please set A2TH angle")
		print("")
		return EC
	else:
	    angle2th = angle * 2.0

	runnumber = header.PutString("RUNNUMBER")
	ylabel = "Intensity"
	if header.CheckKey("YLABEL"):
	    ylabel = header.PutString("YLABEL")
	hh = mm.HeaderBase()
	hh.Add("RUNNUMBER", runnumber)
	hh.Add("XAxis", "Q")
	hh.Add("XLABEL", "q")
	hh.Add("YLABEL", ylabel)
	if header.CheckKey("Label"):
	    Label = header.PutString("Label")
	    hh.Add("Label", Label)
	hh.Add("A2TH", angle2th)
	EC = mm.ElementContainer(hh)

	print("runNo.:", runnumber, " A2TH:", angle2th)

	# head = header.PutString("XAxis")
	if (header.PutString("XAxis") == "TOF"):
	    ql = []
	    intensity = []
	    error = []
	    #tof = ec.ReduceColumn( ec.PutXKey())
	    tof  = ec.PutX()
	    puty = ec.PutY()
	    err  = ec.PutE()
	    t = (4.0 * math.pi * math.sin(math.pi * angle/180.0)*(18.0e7/3955.6))/ np.array( tof)
	    q = t.tolist()

	    for i in range(len(puty)):
		f = 1.0 /(tof[i+1] - tof[i])
		intensity.insert(0, puty[i] * f)
		error.insert(0, err[i] * f)
		ql.insert(0, q[i])
	    ql.insert(0, q[-1])
	    print("q range:", ql[0]," - ",ql[-1])
	    if ( startQ < 0.0 and endQ < 0.0):
        	EC.Add("Q", ql, "nm-1")
        	EC.Add("Intensity", intensity, "Counts")
        	EC.Add("Error", error, "Counts")
	    else:
		stp = 0
		edp = len(tof)
		if (startQ > 0.0):
		    i = 0
		    while i <len(puty):
			if (startQ < ql[i+1]):
			    stp = i
			    i = len(puty)
			i += 1
		if (endQ > 0.0):
		    i = stp
		    while i < len(puty):
			i += 1
			if (endQ < ql[i]):
			    edp = i
			    i = len(puty)
		if ( stp >= edp):
		    print("")
		    print("Please set correct startQ/endQ")
		    print("")
		    return EC
		else:
        	    EC.Add("Intensity", intensity[stp:edp], "Counts")
        	    EC.Add("Error", error[stp:edp], "Counts")
		    edp += 1
        	    EC.Add("Q", ql[stp:edp], "nm-1")
		
	    EC.SetKeys("Q","Intensity","Error")
	else:
	    print("")
	    print("Please set A2TH angle")
	    print("")

	return EC

#########################################
def ConvertTof2Qp(ec=ec, startQ=-1.0,endQ=-1.0,angle=-1.0):
        """
        Convert TOF to Q for polarized
        @param  ec     (ElementContainer)
        @param  startQ  (double)
        @param  endQ    (double)
        @param  angle   (double)
        @retval ECA     (ElementContainer)
        """
	if isinstance( ec, list ):
	    ECA = []
	    for ec1 in ec:
		ECA.append( ConvertTof2Qaniso( ec1, startQ, endQ, angle))
	    return ECA
	else:
	    return ConvertTof2Qaniso( ec, startQ, endQ, angle)

#########################################
def TextOutEC(EC=EC, filename="/dev/shm/temp.tof"):
        """
        Text Out TOF
        @param  EC       (ElementContainer)
        @param  filename (string)
        """

	if len( filename) > 0:
	    f = open( filename, 'w')
	    if isinstance( EC, list ):
 		header = EC[0].PutHeader()
		if header.CheckKey("XAxis"):
		    axis = header.PutString( "XAxis")
		else:
		    axis = "TOF"
		if header.CheckKey("RUNNUMBER"):
		    runnumber = header.PutString( "RUNNUMBER")
		else:
		    runnumber = ""
		if ( len( EC) == 2):
		    q1 = EC[0].ReduceColumn( EC[0].PutXKey())
		    int1 = EC[0].PutY()
		    err1 = EC[0].PutE()
		    int2 = EC[1].PutY()
		    err2 = EC[1].PutE()
		    if (axis == "Q" or axis == "q"):
			f.write("q_"+runnumber+"\tref_p_"+runnumber+"\terr_p_"+runnumber+"\tref_m_"+runnumber+"\terr_m_"+runnumber+"\n")
			for i in range(len(int1)):
			    q1[i] /= 10.0
			    f.write("%16.12g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (q1[i], int2[i], err2[i], int1[i], err1[i]))
		    else:
			if header.CheckKey("XLABEL"):
			    xlabel = header.PutString( "XLABEL")
			    xlabel = xlabel.lower()
			else:
			    xlabel = "tof"
			f.write(xlabel+"_"+runnumber+"\tref_p_"+runnumber+"\terr_p_"+runnumber+"\tref_m_"+runnumber+"\terr_m_"+runnumber+"\n")
			for i in range(len(int1)):
			    f.write("%7.3f\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (q1[i], int2[i], err2[i], int1[i], err1[i]))
		    del err2
		    del int2
		    del err1
		    del int1
		    del q1

		if ( len( EC) == 4):
		    q1 = EC[0].ReduceColumn( EC[0].PutXKey())
		    int1 = EC[0].PutY()
		    err1 = EC[0].PutE()
		    int2 = EC[1].PutY()
		    err2 = EC[1].PutE()
		    int3 = EC[2].PutY()
		    err3 = EC[2].PutE()
		    int4 = EC[3].PutY()
		    err4 = EC[3].PutE()
		    if (axis == "Q" or axis == "q"):
			f.write("q_"+runnumber+"\tref_p_"+runnumber+"\terr_p_"+runnumber+"\tref_m_"+runnumber+"\terr_m_"+runnumber+"\tref_pm_"+runnumber+"\terr_pm_"+runnumber+"\n")
			for i in range(len(int1)):
			    q1[i] /= 10.0
			    f.write("%16.12g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (q1[i], int2[i], err2[i], int3[i], err3[i], (int1[i]+int4[i])/2.0, math.sqrt(err1[i]*err1[i] + err4[i]*err4[i])))
		    else:
			if header.CheckKey("XLABEL"):
			    xlabel = header.PutString( "XLABEL")
			    xlabel = xlabel.lower()
			else:
			    xlabel = "tof"
			f.write(xlabel+"_"+runnumber+"\tref_p_"+runnumber+"\terr_p_"+runnumber+"\tref_m_"+runnumber+"\terr_m_"+runnumber+"\tref_pm_"+runnumber+"\terr_pm_"+runnumber+"\n")
			for i in range(len(int1)):
			    f.write("%7.3f\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\t%20.16g\n" % (q1[i], int2[i], err2[i], int3[i], err3[i], (int1[i]+int4[i])/2.0, math.sqrt(err1[i]*err1[i] + err4[i]*err4[i])))
		    del err4
		    del int4
		    del err3
		    del int3
		    del err2
		    del int2
		    del err1
		    del int1
		    del q1

	    else:
 		header = EC.PutHeader()
		if header.CheckKey("XAxis"):
		    axis = header.PutString( "XAxis")
		else:
		    axis = "TOF"
		if header.CheckKey("RUNNUMBER"):
		    runnumber = header.PutString( "RUNNUMBER")
		else:
		    runnumber = ""
		q1 = EC.ReduceColumn( EC.PutXKey())
		int1 = EC.PutY()
		err1 = EC.PutE()
		if (axis == "Q" or axis == "q"):
		    f.write("q_"+runnumber+"\tref_"+runnumber+"\terr_ref_"+runnumber+"\n")
		    for i in range(len(int1)):
			q1[i] /= 10.0
			f.write("%16.12g\t%20.16g\t%20.16g\n" % (q1[i], int1[i], err1[i]))
		else:
		    if header.CheckKey("XLABEL"):
			xlabel = header.PutString( "XLABEL")
			xlabel = xlabel.lower()
			if ( xlabel != "tof"):
			    f.write(xlabel+"_"+runnumber+"\tref_"+runnumber+"\terr_ref_"+runnumber+"\n")
		    for i in range(len(int1)):
			f.write("%7.3f\t%20.16g\t%20.16g\n" % (q1[i], int1[i], err1[i]))
		del err1
		del int1
		del q1
	    f.close()
	else:
	    print("filename not found!!")

#########################################
def ConvertArray2EC(ec=ec, n=0):
        """
        Convert EC[n] array to EC
        @param  ec     (ElementContainer)
        @param  n      (int)
        @retval EC     (ElementContainer)
        """
	if isinstance( ec, list ):
	    EC = ec[n]
	else:
	    EC = ec
	return EC

#########################################
def ConvertTof2QpPO(ec=ec, startQ=-1.0,endQ=-1.0,angle=-1.0):
        """
        Convert TOF to Q for polarized PO
        @param  ec     (ElementContainer)
        @param  startQ  (double)
        @param  endQ    (double)
        @param  angle   (double)
        @retval ECA     (ElementContainer)
        """
	if isinstance( ec, list ):
	    ECA = []
	    ECA.append( ConvertTof2Qaniso( ec[2], startQ, endQ, angle))
	    ECA.append( ConvertTof2Qaniso( ec[1], startQ, endQ, angle))
	    return ECA
	else:
	    return ConvertTof2Qaniso( ec, startQ, endQ, angle)
#########################################
# Dictionary for entry the name of functions
_functions = {
	"PickupCurpos":PickupCurpos,
	"PickupAxisCurpos":PickupAxisCurpos,
	"GetHist0dDetector":GetHist0dDetector,
	"GetHist0dDetectorTime":GetHist0dDetectorTime,
	"GetHist0dDetectorTimeMap":GetHist0dDetectorTimeMap,
	"GetHist0dDetectorTrend":GetHist0dDetectorTrend,
	"GetHist0dDetectorAdd":GetHist0dDetectorAdd,
	"GetHist0dDetectorAddTOF":GetHist0dDetectorAddTOF,
	"GetHist0dDetectorDio":GetHist0dDetectorDio,
	"GetHist0dDetectorDioAdd":GetHist0dDetectorDioAdd,
	"GetHist0dDetectorDio12":GetHist0dDetectorDio12,
	"GetHist0dDetectorDio12Add":GetHist0dDetectorDio12Add,
	"ECDividedByEC":ECDividedByEC,
	"ECPDividedByEC":ECPDividedByEC,
	"ReflectivityPA":ReflectivityPA,
	"ReflectivityPO":ReflectivityPO,
	"ConvertArray2EC":ConvertArray2EC,
	"ConvertTof2Qaniso":ConvertTof2Qaniso,
	"ConvertTof2Qp":ConvertTof2Qp,
	"ConvertTof2QpPO":ConvertTof2QpPO,
	"TextOutEC":TextOutEC,
	"Concatenate":Concatenate,
	"ConcatenateNorm":ConcatenateNorm,
	"ConcatenateNorm2":ConcatenateNorm2
	      }
_functionsOrder = [
	"PickupCurpos",
	"PickupAxisCurpos",
	"GetHist0dDetector",
	"GetHist0dDetectorTrend",
	"GetHist0dDetectorTime",
	"GetHist0dDetectorTimeMap",
	"GetHist0dDetectorAdd",
	"GetHist0dDetectorAddTOF",
	"GetHist0dDetectorDio",
	"GetHist0dDetectorDioAdd",
	"GetHist0dDetectorDio12",
	"GetHist0dDetectorDio12Add",
	"ECDividedByEC",
	"ECPDividedByEC",
	"ReflectivityPA",
	"ReflectivityPO",
	"ConvertArray2EC",
	"ConvertTof2Qaniso",
	"ConvertTof2Qp",
	"ConvertTof2QpPO",
	"TextOutEC",
	"Concatenate",
	"ConcatenateNorm",
	"ConcatenateNorm2"
    ]
