from __future__ import print_function
import Cmm
import Manyo as mm
import math
import os
import glob

############
#T.Yamada[130424]
def DNAQSlice2D(ecm, Qxzc,Qyc,dQ=0.05):
    tempI = []
    tempSD =[]
    tempINum = []
    flag = 0
    for psd in range(ecm.PutTableSize()):
        if psd%20 ==0:
            print("PSD %d is Start" %(psd))
        if int(ecm.Put(psd).PutHeader().PutDouble("MASKED")) != 1:
            eca = ecm.Put(psd)
            for pix in range(eca.PutTableSize()):
                if int(eca.Put(pix).PutHeader().PutDouble("MASKED")) != 1:
                    ec = eca.Put(pix)
                    if(ec.CheckKey("Energy")==1):
                        ELabel = "Energy"
                    elif(ec.CheckKey("HW") ==1):
                        ELabel = "HW"
                    else:
                        ec.Dump()
                        print("Error")
                        return -1
                    Ef = ec.PutHeader().PutDouble("Ef")
                    Pa = ec.PutHeader().PutDouble("PolarAngle")
                    Aa = ec.PutHeader().PutDouble("AzimAngle")
                    EList = ec.PutList(ELabel)
                    IList = ec.PutList("Intensity")
                    SDList = ec.PutList("Error")

                    if flag==0: #Set ResultArray
                        tempI = [0.0]*len(IList)
                        tempSD = [0.0]*len(IList)
                        tempINum = [0]*len(IList)
                        flag = 1

                    for ii in range(len(IList)):
                        Ei = (EList[ii]+EList[ii+1])/2+Ef
                        Qxz,Qy = GetQxzQy(Ef, Pa, Aa, Ei)
                        if ((Qxz-Qxzc)*(Qxz-Qxzc)+(Qy-Qyc)*(Qy-Qyc)<dQ*dQ):
                            tempI[ii] += IList[ii]
                            tempSD[ii] += SDList[ii]*SDList[ii]
                            tempINum[ii] +=1

    for ii in range(len(IList)):
        if int(tempINum[ii]) != 0:
            tempI[ii] = tempI[ii]/tempINum[ii]
            tempSD[ii] = math.sqrt(tempSD[ii])/tempINum[ii]
        
        ec = mm.ElementContainer()
        ec.Add("Intensity",tempI)
        ec.Add("Error",tempSD)
        ec.Add("Energy",EList)
        ec.Add("NumofPix", tempINum)
        
        if ecm.PutHeader().CheckKey("RUNNUMBER")==1:
            runNo = ecm.PutHeader().PutInt4("RUNNUMBER")
            ec.AddToHeader("RUNNUMBER",runNo)
    ec.AddToHeader("Qxzcenter",Qxzc)
    ec.AddToHeader("Qycenter",Qyc)
    ec.AddToHeader("dQ",dQ)

    ec.SetKeys("Energy","Intensity","Error")
    
    return ec
#######
#T. Yamada [130125]
def DNAmakeQE2D(ecm, Qxzmin=-2.0,Qxzmax=2.0,dQxz=0.05,Qymin=-0.3,Qymax=0.3,dQy=0.02):
	Qxzlist = []
	for jj in range(int((Qxzmax-Qxzmin)/dQxz)):
		Qxzlist.append(Qxzmin+jj*dQxz+dQxz/2)
	#print Qxzlist[0],Qxzlist[-1],jj

	Qylist = []
	Qytemp = Qymin
	while(Qytemp <=Qymax+0.001):
		Qylist.append(Qytemp)
		Qytemp+=dQy

	QxzNum = len(Qxzlist)
	QyNum = len(Qylist)-1
	#print Qylist[0], Qylist[-1],Qytemp

	tempI=[]
	tempEr = []
	tempENum =[]
	for jj in range(len(Qxzlist)):
		tempI.append([0.0]*(len(Qylist)-1))
		tempEr.append([0.0]*(len(Qylist)-1))
		tempENum.append([0.0]*(len(Qylist)-1))

	for psd in range(ecm.PutTableSize()):
		if psd%20 == 0:
			print("PSD%d is Start" %(psd))
		if int(ecm.Put(psd).PutHeader().PutDouble("MASKED")) != 1:
			eca = ecm.Put(psd)
			for pix in range(eca.PutTableSize()):
				if int(eca.Put(pix).PutHeader().PutDouble("MASKED")) !=1:
					ec = eca.Put(pix)
					Ef = ec.PutHeader().PutDouble("Ef")
					Pa = ec.PutHeader().PutDouble("PolarAngle")
					Aa = ec.PutHeader().PutDouble("AzimAngle")
					if(ec.CheckKey("Energy") ==1):
						ELabel = "Energy"
					elif(ec.CheckKey("HW") ==1):
						ELabel = "HW"
					else:
						ec.Dump()
					EiList = ec.PutList(ELabel)
					IntList = ec.PutList("Intensity")
					ErrList = ec.PutList("Error")
					for ii in range(len(EiList)-1):
						Ei = (EiList[ii]+EiList[ii+1])/2+Ef
						Qxz,Qy = GetQxzQy(Ef, Pa, Aa, Ei)
						QxzPos = int((Qxz-Qxzmin-dQxz*0.5)/dQxz)
						QyPos = int((Qy-Qymin-dQy*0.5)/dQy)
						if (QxzPos<QxzNum) and (QyPos<QyNum):
							tempI[QxzPos][QyPos]+= IntList[ii]
							tempEr[QxzPos][QyPos] += ErrList[ii]*ErrList[ii]
							tempENum[QxzPos][QyPos] += 1
	
	for jj in range(len(tempI)):
		for ii in range(len(tempI[jj])):
			if(int(tempENum[jj][ii]) !=0):
				tempI[jj][ii] = tempI[jj][ii]/tempENum[jj][ii]
				tempEr[jj][ii] = math.sqrt(tempEr[jj][ii])/tempENum[jj][ii]

	ECAResult = mm.ElementContainerArray()
	for jj in range(len(tempI)):
		ec = mm.ElementContainer()
		xr = [Qxzlist[jj]-dQxz*0.5, Qxzlist[jj]+dQxz*0.5]
		xr_vector = mm.ListToDoubleVector(xr)
		ec.AddToHeader("XRANGE",xr_vector)
		ec.AddToHeader("Qxz",Qxzlist[jj])
		ec.Add("Qy",Qylist)
		ec.Add("Intensity",tempI[jj])
		ec.Add("Error",tempEr[jj])
		ec.Add("ENum", tempENum[jj])
		ec.SetKeys("Qy","Intensity","Error")
		ECAResult.Add(ec)	
	
	ECAResult.AddToHeader("XLABEL","Qxz / Angstrom-1")
	ECAResult.AddToHeader("YLABEL","Qy / Angstrom-1")

	hh = ecm.PutHeader()
	if(hh.CheckKey("RUNNUMBER")==1):
		runNo = hh.PutInt4("RUNNUMBER")	
		ECAResult.AddToHeader("RUNNUMBER",runNo)
	return ECAResult

#######
#T. Yamada [130125]	
def DNAmakeAngle2D(ecm, Theta2xzmin = -180.0,Theta2xzmax = 180.0,dTheta2xz = 3.0, ElevAnglemin=-20.0, ElevAnglemax = 20.0, dElevAngle = 0.5):
	Theta2xzlist = []
	for jj in range(int((Theta2xzmax-Theta2xzmin)/dTheta2xz)):
		Theta2xzlist.append(Theta2xzmin+jj*dTheta2xz+dTheta2xz/2)

	ElevAnglelist = []
	ElevAngletemp = ElevAnglemin
	while(ElevAngletemp <=ElevAnglemax+0.001):
		ElevAnglelist.append(ElevAngletemp)
		ElevAngletemp+=dElevAngle

	Theta2xzNum = len(Theta2xzlist)
	ElevAngleNum = len(ElevAnglelist)-1

	tempI=[]
	tempEr = []
	tempENum =[]
	for jj in range(len(Theta2xzlist)):
		tempI.append([0.0]*(len(ElevAnglelist)-1))
		tempEr.append([0.0]*(len(ElevAnglelist)-1))
		tempENum.append([0.0]*(len(ElevAnglelist)-1))
	
	for psd in range(ecm.PutTableSize()):
		if psd%20 == 0:
			print("PSD%d is Start" %(psd))
		if int(ecm.Put(psd).PutHeader().PutDouble("MASKED")) != 1:
			eca = ecm.Put(psd)
			for pix in range(eca.PutTableSize()):
				if int(eca.Put(pix).PutHeader().PutDouble("MASKED")) !=1:
					ec = eca.Put(pix)
					Ef = ec.PutHeader().PutDouble("Ef")
					Pa = ec.PutHeader().PutDouble("PolarAngle")
					Aa = ec.PutHeader().PutDouble("AzimAngle")
					if(ec.CheckKey("Energy") ==1):
						ELabel = "Energy"
					elif(ec.CheckKey("HW") ==1):
						ELabel = "HW"
					EiList = ec.PutList(ELabel)
					IntList = ec.PutList("Intensity")
					ErrList = ec.PutList("Error")
					for ii in range(len(EiList)-1):
						Ei = (EiList[ii]+EiList[ii+1])/2+Ef
						Theta2xz,ElevAngle = GetAngle(Pa, Aa)
						Theta2xzPos = int((math.degrees(Theta2xz)-Theta2xzmin-dTheta2xz*0.5)/dTheta2xz)
						ElevAnglePos = int((math.degrees(ElevAngle)-ElevAnglemin-dElevAngle*0.5)/dElevAngle)
						if (Theta2xzPos<Theta2xzNum) and (ElevAnglePos<ElevAngleNum):
							tempI[Theta2xzPos][ElevAnglePos]+= IntList[ii]
							tempEr[Theta2xzPos][ElevAnglePos] += ErrList[ii]*ErrList[ii]
							tempENum[Theta2xzPos][ElevAnglePos] += 1
	
	for jj in range(len(tempI)):
		for ii in range(len(tempI[jj])):
			if(int(tempENum[jj][ii]) !=0):
				tempI[jj][ii] = tempI[jj][ii]/tempENum[jj][ii]
				tempEr[jj][ii] = math.sqrt(tempEr[jj][ii])/tempENum[jj][ii]

	ECAResult = mm.ElementContainerArray()
	for jj in range(len(tempI)):
		ec = mm.ElementContainer()
		xr = [Theta2xzlist[jj]-dTheta2xz*0.5, Theta2xzlist[jj]+dTheta2xz*0.5]
		xr_vector = mm.ListToDoubleVector(xr)
		ec.AddToHeader("XRANGE",xr_vector)
		ec.AddToHeader("Theta2xz",Theta2xzlist[jj])
		ec.Add("ElevAngle",ElevAnglelist)
		ec.Add("Intensity",tempI[jj])
		ec.Add("Error",tempEr[jj])
		ec.Add("ENum", tempENum[jj])
		ec.SetKeys("ElevAngle","Intensity","Error")
		ECAResult.Add(ec)	
	
	ECAResult.AddToHeader("XLABEL","2Theta(xz) / deg")
	ECAResult.AddToHeader("YLABEL","Elevation Angle / deg")

	hh = ecm.PutHeader()
	if(hh.CheckKey("RUNNUMBER")==1):
		runNo = hh.PutInt4("RUNNUMBER")	
		ECAResult.AddToHeader("RUNNUMBER",runNo)
	return ECAResult
	
#######
#T. Yamada [130125]	
def GetQxzQy(Ef,PAf, AAf,Ei):
#	MASS_NEUTRON=1.674928e-27 # in unit of [kg]
#	HBAR=1.054571596e-34 # in unit of [J][s]  

	PAi = 0.0
	AAi = 0.0  
	ki = 0.6947*math.sqrt(Ei)
	kf = 0.6947*math.sqrt(Ef)

	Qx = kf*math.sin(PAf)*math.cos(AAf)#-ki*math.sin(PAi)*math.cos(AAi)
	Qy = kf*math.sin(PAf)*math.sin(AAf)#-ki*math.sin(PAi)*math.sin(AAi)
	Qz = kf*math.cos(PAf)-ki*math.cos(PAi)
	
	Qxz = math.sqrt(Qx*Qx+Qz*Qz)
	if(AAf>=math.pi/2.0) or (AAf<=-(math.pi/2.0)):
		Qxz = -Qxz
	return Qxz,Qy #Qxz, Qy
#######
#T. Yamada [130125]
def GetAngle(PAf,AAf):
	PAi = 0.0
	AAi = 0.0  					
	kfx = math.sin(PAf)*math.cos(AAf)#-ki*math.sin(PAi)*math.cos(AAi)
	kfy = math.sin(PAf)*math.sin(AAf)#-ki*math.sin(PAi)*math.sin(AAi)
	kfz = math.cos(PAf)
	
	Theta2xz = math.atan2(kfx,kfz)
	ElevAngle = math.atan2(kfy,math.sqrt(kfx*kfx+kfz*kfz))
	
	return Theta2xz, ElevAngle

##################################
def TYDNAGetRockingCurve_org(StartEndRunNo,StartEndpsd,StartEndPix,LambdaParam,mode,startomega,domega,OmgPlot):
    """
    Get rocking curver
    TYGetRockingCurve(StartEndRunNo=" ",StartEndpsd=" ",StartEndPix=" ",
                        LambdaParam="",mode=111,startOmega=0.0,domega=0.5,output=""):
    @param StartEndRunNo (string) start and end runNo
    @param StartEndpsd (string) start and end psd
    @param StartEndPix (string) start and end pixel
    @param LambdaParam (string) lambda center and delta lambda
    @param mode (ing) select Si analyzer 111 or 333
    @param startOmega (double) start omega [deg]
    @param domega (double) delta omega [deg]
    @param OmgPlot (bool) output as omega or runNo
    """

    RunNoParam = StartEndRunNo.split(",")
    if len(RunNoParam)==2:
        startRunNo = int(RunNoParam[0])
        endRunNo = int(RunNoParam[1])
    else:
        print("RockingCurve-> Error, start or end RunNo is incorrect", StartEndRunNo)

    psdParam = StartEndpsd.split(",")
    if len(psdParam)==2:
        startpsd = int(psdParam[0])
        endpsd = int(psdParam[1])
        if(endpsd > 223):
            endpsd = 223
    else:
        print("RockingCurve-> Error, start or end psd is incorrect", StartEndpsd)

    pixParam = StartEndPix.split(",")
    if len(pixParam)==2:
        startpix = int(pixParam[0])
        endpix = int(pixParam[1])
        if(endpix>119):
            endpix = 119
    else:
        print("RockingCurve-> Error, start or end pixel is incorrect", StartEndPix)

#    saveString = ""
#    jj = 0
    runNolist = [float(startRunNo)-0.5]
    omegalist = [float(startomega)-domega/2]
    TIlist = []
    TElist = []
    for runNo in range(startRunNo,endRunNo+1):
        TI = 0.0
        TE = 0.0
        psd = 0
        print(runNo)

        if TYCheckedbFile(runNo): #T.Yamada Add.for check file. [130207]      
            if int(mode) == 111:
                dat = Cmm.GetHistogramHW( runNo, "0.005,-0.2,0.2",LambdaParam,0, False, "-1,-1", False )
            elif int(mode) == 333:
                dat = Cmm.GetHistogramHW333( runNo, "0.05,-0.5,0.2",LambdaParam,0, False, "-1,-1", False )
            else:
                print("Check SiLattice")
            print("----> GetBeamCurrent", runNo)
            Cmm.NormByBeamWithParams(dat, runNo)
            Cmm.MutiplyConstant(dat,10000.0)

            for psd in range( startpsd,endpsd+1 ):
                    ECA = dat.PutPointer( psd )
                    pix = 0
                    for pix in range( startpix,endpix+1 ):
                        ec = ECA.PutPointer( pix )
                        yy = ec.PutY()
                        ee = ec.PutE()
                        for kk in range (len(yy)):
                            TI += float(yy[kk])
                            TE += float(ee[kk])*float(ee[kk])
        else:
            print(runNo, "is skipped because edbfile has no data.")

        runNolist.append(runNo+0.5)
        omegalist.append(omegalist[len(omegalist)-1]+domega)
        TIlist.append(TI)
        TElist.append(math.sqrt(TE))

    #--- Set ElementContainer
    EC = mm.ElementContainer()
    EC.Add("runNo",runNolist,"run No.")
    EC.Add("omega",omegalist, "omega / deg")
    EC.Add("Intensity",TIlist, "Intensity / a.u.")
    EC.Add("Error",TElist)

    if OmgPlot:
        EC.SetKeys("omega","Intensity","Error")
    else:
        EC.SetKeys("runNo","Intensity","Error")

    EC.AddToHeader("RUNNUMBER",str(startRunNo))
    EC.AddToHeader("startomega",startomega)
    EC.AddToHeader("deltaomega",domega)
    EC.AddToHeader("mode",mode)
    EC.AddToHeader("startpsd", startpsd)
    EC.AddToHeader("endpsd", endpsd)
    EC.AddToHeader("startpix",startpix)
    EC.AddToHeader("endpix", endpix)

    ConditionString =""
    ConditionString +="#start RunNo: %d\n" %(startRunNo)
    ConditionString +="#end RunNo: %d\n" %(endRunNo)
    ConditionString +="#start omega: %.2f\n" %(startomega)
    ConditionString +="#delta omega: %.2f\n" %(domega)
    ConditionString +="#Si Analyzer: %d\n" %(mode)
    ConditionString +="#Lambda Param:"+LambdaParam+"\n"
    ConditionString +="#start psd: %d\n" %(startpsd)
    ConditionString +="#end psd: %d\n" %(endpsd)
    ConditionString +="#start pix: %d\n" %(startpix)
    ConditionString +="#end pix: %d\n" %(endpix)
    
    print("Measurement Condition")
    print(ConditionString)
#    EC.AddToHeader("Condition",ConditionString)

    return EC
###############################

###############################
#T. Yamada [130125]
def TYSaveRockingCurve(ec):
	"""
	@param ec	(ElementConateiner)
	
	save ec as text
	"""
	hh = ec.PutHeader()
	ConditionString = ""
	if hh.CheckKey("Condition")==1:
		ConditionString = hh.PutString("Condition")
	if hh.CheckKey("RUNNUMBER")==1:
		runNo = hh.PutInt4("RUNNUMBER")
	else:
		runNo = 0
	
	Xlist = ec.PutXList()
	Ylist = ec.PutYList()
	Elist = ec.PutEList()
	
	for ii in range(len(Ylist)):
		ConditionString +="%.4f,%.4f,%.4f\n" %((Xlist[ii]+Xlist[ii+1])/2,Ylist[ii], Elist[ii])

	#savePath = "/home/dnaadmin/DNA/tmp"
        #savePath = os.path.join( os.environ["UTSUSEMI_USR_PRIV_HOME"],"DNA","tmp" )
	savePath = os.path.join( mu.UtsusemiEnvGetUserDir(),"DNA","tmp" )
	filename = "Run%dRC.txt" %(runNo)
	
	filename = savePath+filename
	
    #--- file check
	flug = os.path.exists(filename)
	if flug:
	      os.rename(filename,filename+"_bk1" )

    #--- output file
	print("Now output (%s)"%filename)
	fo = open( filename, "w" )
	fo.write( ConditionString )
	fo.close()

#################################
#T. Yamada [130207]    
def TYCheckedbFile(runNo):
    if "MLF_SYS_NAME" in os.environ:
        ss = os.environ["MLF_SYS_NAME"]
        ss = ss + "%06d" % runNo
#        print ss

        #T0Path = "/data/tmp/"+ss+"_0*[01]*.t0b" T.Yamada comment out[121123]
        edbPath = "/data/DNA/"+ss+"_*/"+ss+"_0[01]*.edb" #T. Yaamda Modified [121123]
        edbflist = glob.glob(edbPath)
        edbflist.sort()
        filesizeSum = 0
        if len(edbflist)>=14:
            for edbfile in edbflist:
                if os.path.getsize(edbfile) == 0:
                    return False
        else:
            return False
    return True

#################################
#M. Matsuura [131024]
def TYDNAGetRockingCurve_MM(StartEndRunNo,StartEndpsd,StartEndPix,LambdaParam,mode,startomega,domega,OmgPlot):
    """
    Get rocking curver
    TYGetRockingCurve(StartEndRunNo=" ",StartEndpsd=" ",StartEndPix=" ",
                        LambdaParam="",mode=111,startOmega=0.0,domega=0.5,output=""):
    @param StartEndRunNo (string) start and end runNo
    @param StartEndpsd (string) start and end psd
    @param StartEndPix (string) start and end pixel
    @param LambdaParam (string) lambda center and delta lambda
    @param mode (ing) select Si analyzer 111 or 333
    @param startOmega (double) start omega [deg]
    @param domega (double) delta omega [deg]
    @param OmgPlot (bool) output as omega or runNo
    """

    RunNoParam = StartEndRunNo.split(",")
    if len(RunNoParam)==2:
        startRunNo = int(RunNoParam[0])
        endRunNo = int(RunNoParam[1])
    else:
        print("RockingCurve-> Error, start or end RunNo is incorrect", StartEndRunNo)

    psdParam = StartEndpsd.split(",")
    if len(psdParam)==2:
        startpsd = int(psdParam[0])
        endpsd = int(psdParam[1])
        if(endpsd > 223):
            endpsd = 223
    else:
        print("RockingCurve-> Error, start or end psd is incorrect", StartEndpsd)

    pixParam = StartEndPix.split(",")
    if len(pixParam)==2:
        startpix = int(pixParam[0])
        endpix = int(pixParam[1])
        if(endpix>119):
            endpix = 119
    else:
        print("RockingCurve-> Error, start or end pixel is incorrect", StartEndPix)

#    saveString = ""
#    jj = 0
    runNolist = [float(startRunNo)-0.5]
    omegalist = [float(startomega)-domega/2]
    TIlist = []
    TElist = []
    for runNo in range(startRunNo,endRunNo+1):
        TI = 0.0
        TE = 0.0
        psd = 0
        print(runNo)

        if TYCheckedbFile(runNo): #T.Yamada Add.for check file. [130207]      
            if int(mode) == 111:
#                dat = Cmm.GetHistogramHW( runNo, "0.005,-0.2,0.2",LambdaParam,0, False, "-1,-1", False )
# modified by MM [20131024]
                dat = Cmm.GetHistogram(runNo,28320,38320,10,startpsd,endpsd,120)
            elif int(mode) == 333:
#                dat = Cmm.GetHistogramHW333( runNo, "0.05,-0.5,0.2",LambdaParam,0, False, "-1,-1", False )
# modified by MM [20131024]
                dat = Cmm.GetHistogram(runNo,19440,29440,10,startpsd,endpsd,120)
            else:
                print("Check SiLattice")
            print("----> GetBeamCurrent", runNo)
            #Cmm.NormByBeamWithParams(dat, runNo)
            Cmm.NormByBeamCurrent( dat, isCT8Neutron=True ) #[inamura 170615]
            Cmm.MutiplyConstant(dat,10000.0)

            for psd in range( startpsd,endpsd+1 ):
                    ECA = dat.PutPointer( psd )
                    pix = 0
                    for pix in range( startpix,endpix+1 ):
                        ec = ECA.PutPointer( pix )
                        yy = ec.PutY()
                        ee = ec.PutE()
                        for kk in range (len(yy)):
                            TI += float(yy[kk])
                            TE += float(ee[kk])*float(ee[kk])
            del dat #[inamura 170615]
        else:
            print(runNo, "is skipped because edbfile has no data.")

        runNolist.append(runNo+0.5)
        omegalist.append(omegalist[len(omegalist)-1]+domega)
        TIlist.append(TI)
        TElist.append(math.sqrt(TE))

    #--- Set ElementContainer
    EC = mm.ElementContainer()
    EC.Add("runNo",runNolist,"run No.")
    EC.Add("omega",omegalist, "omega / deg")
    EC.Add("Intensity",TIlist, "Intensity / a.u.")
    EC.Add("Error",TElist)

    if OmgPlot:
        EC.SetKeys("omega","Intensity","Error")
    else:
        EC.SetKeys("runNo","Intensity","Error")

    EC.AddToHeader("RUNNUMBER",str(startRunNo))
    EC.AddToHeader("startomega",startomega)
    EC.AddToHeader("deltaomega",domega)
    EC.AddToHeader("mode",mode)
    EC.AddToHeader("startpsd", startpsd)
    EC.AddToHeader("endpsd", endpsd)
    EC.AddToHeader("startpix",startpix)
    EC.AddToHeader("endpix", endpix)

    ConditionString =""
    ConditionString +="#start RunNo: %d\n" %(startRunNo)
    ConditionString +="#end RunNo: %d\n" %(endRunNo)
    ConditionString +="#start omega: %.2f\n" %(startomega)
    ConditionString +="#delta omega: %.2f\n" %(domega)
    ConditionString +="#Si Analyzer: %d\n" %(mode)
    ConditionString +="#Lambda Param:"+LambdaParam+"\n"
    ConditionString +="#start psd: %d\n" %(startpsd)
    ConditionString +="#end psd: %d\n" %(endpsd)
    ConditionString +="#start pix: %d\n" %(startpix)
    ConditionString +="#end pix: %d\n" %(endpix)
    
    print("Measurement Condition")
    print(ConditionString)
#    EC.AddToHeader("Condition",ConditionString)

    return EC
###############################

def TYDNAGetRockingCurve(StartEndRunNo,StartEndpsd,StartEndPix,LambdaParam,mode,startomega,domega,OmgPlot):
    """
    Get rocking curver
    TYGetRockingCurve(StartEndRunNo=" ",StartEndpsd=" ",StartEndPix=" ",
                        LambdaParam="",mode=111,startOmega=0.0,domega=0.5,output=""):
    @param StartEndRunNo (string) start and end runNo
    @param StartEndpsd (string) start and end psd
    @param StartEndPix (string) start and end pixel
    @param LambdaParam (string) lambda center and delta lambda
    @param mode (ing) select Si analyzer 111 or 333
    @param startOmega (double) start omega [deg]
    @param domega (double) delta omega [deg]
    @param OmgPlot (bool) output as omega or runNo
    """

    RunNoParam = StartEndRunNo.split(",")
    if len(RunNoParam)==2:
        startRunNo = int(RunNoParam[0])
        endRunNo = int(RunNoParam[1])
    else:
        print("RockingCurve-> Error, start or end RunNo is incorrect", StartEndRunNo)

    psdParam = StartEndpsd.split(",")
    if len(psdParam)==2:
        startpsd = int(psdParam[0])
        endpsd = int(psdParam[1])
        if(endpsd > 223):
            endpsd = 223
    else:
        print("RockingCurve-> Error, start or end psd is incorrect", StartEndpsd)

    pixParam = StartEndPix.split(",")
    if len(pixParam)==2:
        startpix = int(pixParam[0])
        endpix = int(pixParam[1])
        if(endpix>119):
            endpix = 119
    else:
        print("RockingCurve-> Error, start or end pixel is incorrect", StartEndPix)

#    saveString = ""
#    jj = 0
    runNolist = [float(startRunNo)-0.5]
    omegalist = [float(startomega)-domega/2]
    TIlist = []
    TElist = []
    for runNo in range(startRunNo,endRunNo+1):
        TI = 0.0
        TE = 0.0
        psd = 0
        print(runNo)

        if TYCheckedbFile(runNo): #T.Yamada Add.for check file. [130207]      
            if int(mode) == 111:
#                dat = Cmm.GetHistogramHW( runNo, "0.005,-0.2,0.2",LambdaParam,0, False, "-1,-1", False )
# modified by MM [20131024]
                dat = Cmm.GetHistogram(runNo,28325,38325,100,startpsd,endpsd,120)
            elif int(mode) == 333:
#                dat = Cmm.GetHistogramHW333( runNo, "0.05,-0.5,0.2",LambdaParam,0, False, "-1,-1", False )
# modified by MM [20131024]
                dat = Cmm.GetHistogram(runNo,19442,29442,100,startpsd,endpsd,120)
            else:
                print("Check SiLattice")
            print("----> GetBeamCurrent", runNo)
            #Cmm.NormByBeamWithParams(dat, runNo)
            Cmm.NormByBeamCurrent( dat, isCT8n=True ) #[inamura 180920]
            Cmm.MutiplyConstant(dat,10000.0)


            import Manyo
            SIH = Manyo.SearchInHeader(dat)
            SIH.SearchArray("DETID", startpsd,endpsd)
            ECM = SIH.PutResultSearchArray()
            if ECM.PutSize()==0:
                raise UserWarning("RockingCurve :: Searching Result are empty")
            for i in range(ECM.PutSize()):
                ECA = ECM.PutPointer(i)
                pix = 0
                for pix in range( startpix,endpix+1 ):
                    ec = ECA.PutPointer( pix )
                    yy = ec.PutY()
                    ee = ec.PutE()
                    for kk in range (len(yy)):
                        TI += float(yy[kk])
                        TE += float(ee[kk])*float(ee[kk])
            """
            for psd in range( startpsd,endpsd+1 ):
                    ECA = dat.PutPointer( psd )
                    pix = 0
                    for pix in range( startpix,endpix+1 ):
                        ec = ECA.PutPointer( pix )
                        yy = ec.PutY()
                        ee = ec.PutE()
                        for kk in range (len(yy)):
                            TI += float(yy[kk])
                            TE += float(ee[kk])*float(ee[kk])
            """
            del dat #[inamura 170615]
        else:
            print(runNo, "is skipped because edbfile has no data.")

        runNolist.append(runNo+0.5)
        omegalist.append(omegalist[len(omegalist)-1]+domega)
        TIlist.append(TI)
        TElist.append(math.sqrt(TE))

    #--- Set ElementContainer
    EC = mm.ElementContainer()
    EC.Add("runNo",runNolist,"run No.")
    EC.Add("omega",omegalist, "omega / deg")
    EC.Add("Intensity",TIlist, "Intensity / a.u.")
    EC.Add("Error",TElist)

    if OmgPlot:
        EC.SetKeys("omega","Intensity","Error")
    else:
        EC.SetKeys("runNo","Intensity","Error")

    EC.AddToHeader("RUNNUMBER",str(startRunNo))
    EC.AddToHeader("startomega",startomega)
    EC.AddToHeader("deltaomega",domega)
    EC.AddToHeader("mode",mode)
    EC.AddToHeader("startpsd", startpsd)
    EC.AddToHeader("endpsd", endpsd)
    EC.AddToHeader("startpix",startpix)
    EC.AddToHeader("endpix", endpix)

    ConditionString =""
    ConditionString +="#start RunNo: %d\n" %(startRunNo)
    ConditionString +="#end RunNo: %d\n" %(endRunNo)
    ConditionString +="#start omega: %.2f\n" %(startomega)
    ConditionString +="#delta omega: %.2f\n" %(domega)
    ConditionString +="#Si Analyzer: %d\n" %(mode)
    ConditionString +="#Lambda Param:"+LambdaParam+"\n"
    ConditionString +="#start psd: %d\n" %(startpsd)
    ConditionString +="#end psd: %d\n" %(endpsd)
    ConditionString +="#start pix: %d\n" %(startpix)
    ConditionString +="#end pix: %d\n" %(endpix)
    
    print("Measurement Condition")
    print(ConditionString)
#    EC.AddToHeader("Condition",ConditionString)

    return EC
###############################
