#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
WiringFile.xmlの編集
0.9 [150414] improve ReSetNumOfPixel
0.8 [141209] add set_TofMask
0.7 [140412] add set_LLD
0.6 [130304] add SelectByDetType
0.5 [130218]
0.4 [120626] add control frameInfo
0.3 [110104] add control tofDoubleFrameBoundary
"""
import os, datetime
from xml.dom.minidom import parse

__version__ = '0.9'
################################
# XML def for WiringInfo file 
################################
class WiringFileDef(object):
    """
    """
    def __init__(self):
        """
        """
        self.ROOT="wiringInfo"
        self.ROOT_AT_INST="inst"
        self.ROOT_AT_VER="version"
        self.ROOT_AT_DATE="update"

        self.ROOT_PIXELINFO="pixelInfo"
        self.ROOT_PIXELINFO_DAQ="daq"
        self.ROOT_PIXELINFO_DAQ_AT_ID="daqId"

        self.ROOT_PIXELINFO_DAQ_MOD="module"
        self.ROOT_PIXELINFO_DAQ_MOD_AT_NO="moduleNo"
        self.ROOT_PIXELINFO_DAQ_MOD_AT_TYPE="detType"
        self.ROOT_PIXELINFO_DAQ_MOD_AT_TRIGINDEX="trigIndex"

        self.ROOT_PIXELINFO_DAQ_MOD_DET="detector"
        self.ROOT_PIXELINFO_DAQ_MOD_DET_AT_ID="detId"
        self.ROOT_PIXELINFO_DAQ_MOD_DET_AT_AXIS="numAxis"
        self.ROOT_PIXELINFO_DAQ_MOD_DET_AT_HEAD="headPixelId"
        self.ROOT_PIXELINFO_DAQ_MOD_DET_AT_NUM="numPixel"
        
        self.ROOT_PSDPARAM="psdParam"
        self.ROOT_PSDPARAM_PARAM="parameter"
        self.ROOT_PSDPARAM_PARAM_AT_ID="detId"

        self.ROOT_PSDBININFO="psdBinInfo"
        self.ROOT_PSDBININFO_AT_ID="psdBinSetId"
        self.ROOT_PSDBININFO_BIN="positionBin"
        self.ROOT_PSDBININFO_BIN_AT_NUM="numPixel"
        self.ROOT_PSDBININFO_BIN_AT_DELTA="deltaX"
        self.ROOT_PSDBININFO_BIN_AT_OFFSET="offsetX"

        self.ROOT_TOFBININFO="tofBinInfo"
        self.ROOT_TOFBININFO_TOFBIN="tofBin"
        self.ROOT_TOFBININFO_TOFBIN_AT_PAT="patternId"
        self.ROOT_TOFBININFO_TOFBIN_AT_MASK="maskPtnId"
        self.ROOT_TOFBININFO_TOFBIN_AT_OFFSET="offsetBin"

        self.ROOT_TOFBINPAT="tofBinPatternList"
        self.ROOT_TOFBINPAT_PAT="tofBinPattern"
        self.ROOT_TOFBINPAT_PAT_AT_ID="patternId"
        self.ROOT_TOFBINPAT_PAT_AT_TYPE="type"

        self.ROOT_TOFMASKPAT="tofMaskPatternList"
        self.ROOT_TOFMASKPAT_PAT="tofMaskPattern"
        self.ROOT_TOFMASKPAT_PAT_AT_ID="maskPtnId"

        self.ROOT_TOFDOUBLEFRAME="tofDoubleFrameBoundary"
        
        self.ROOT_FRAMEINFO="frameInfo"
        self.ROOT_FRAMEINFO_FRAMENO="frameNo"
        self.ROOT_FRAMEINFO_BOUNDARY="boundary"

        self.TOF_BIN_PATTERN_FORM_DIC = {
            2:[3,"%f,%f,%f"],
            3:[3,"%f,%f,%f"],
            4:[7,"%f,%f,%f,%f,%f,%f,%f"],
            12:[3,"%f,%f,%f"],
            13:[3,"%f,%f,%f"],
            20:[5,"%f,%f,%f,%f,%f"],
            21:[3,"%f,%f,%f"],
            22:[6,"%f,%f,%f,%f,%f,%f"],
            23:[3,"%f,%f,%f"],
            24:[3,"%f,%f,%f"],
            25:[3,"%f,%f,%f"],
            27:[0,""] }
        
################################
#      ContainerBase
################################
class ContainerBase(object):
    """
    各種コンテナのベースクラス
    """
    ################################
    def __init__(self,id):
        """
        コンストラクタ

        @param id (UInt4)
        """
        self.Id = id
        self.Status = 1

    def SetId(self,id):
        """
        Idの設定

        @param id (UInt4)
        """
        self.Id = id

    def PutId(self):
        """
        Idを返す

        @retval (UInt4)
        """
        return self.Id

    def SetStatus(self, status ):
        """
        Statusを定める
        
        @param self
        @param status (UInt4) 0:killed / 1:alived
        """
        if (status!=0)&(status!=1):
            return
        self.Status = status

    def PutStatus(self):
        """
        Statusを返す
        
        @retval 0 killed
        @retval 1 alived
        """
        return self.Status

        
################################
#      OneDetInfo
################################
class OneDetInfo(ContainerBase):
    """
    PSD１本分の情報をおさめるクラス
    """
    ################################
    def __init__(self,id,num=0,axis=1,pA=0.0,pB=0.0,pC=0.0,LLD1=0.0,LLD2=0.0,dx=0,offsetx=0):
        """
        コンストラクタ

        @param self
        @param id (UInt4) detID
        @param num (UInt4) PSDのPixel分割数
        @param axis (UInt4) PSDの軸の数
        @param pA (Double)  PSDの位置決定用パラメータA
        @param pB (Double)  PSDの位置決定用パラメータB
        @param pC (Double)  PSDの位置決定用パラメータC
        @param LLD1 (Double)  PSDの波高のしきい値(最小値)
        @param LLD2 (Double)  PSDの波高のしきい値(最大値)
        @param dx (UInt4)  PSDの位置決定用分割幅
        @param offsetx (UInt4) PSDの位置決定用オフセット値
        """
        #self.DetId = id
        ContainerBase.__init__(self,id)
        self.NumOfPixel = num
        self.NumAxis = axis
        self.PA = pA
        self.PB = pB
        self.PC = pC
        self.LLD1 = LLD1
        self.LLD2 = LLD2
        self.BIN_num = num
        self.BIN_dx = dx
        self.BIN_offset = offsetx
        self.HeadPixelId = -1
        self.Status = 1 # alive:1 / killed:0
        self.FlagChangedNumPixel = 0
        self.CommentHead = "  OneDetInfo > "
        self.InfoStatus = [False,False,False,False] # flags for [ SetPixelinfo, SetHeadPixelId, SetPsdInfo, SetPsdBinInfo ]
        
    def SetPixelInfo(self, id, num, axis=1):
        """
        PixelInfoを定める
        
        @param self
        @param id (UInt4) detID
        @param num (UInt4) PSDのPixel分割数
        @param axis (UInt4) PSDの軸の数
        """
        #self.DetId = id
        self.SetId(id)
        if (self.NumOfPixel!=num):
            self.NumOfPixel = num
            self.FlagChangedNumPixel = 1
            if (self.BIN_num!=0):
                self._SetPsdBinNewNum(num)
        self.NumAxis = axis
        self.InfoStatus[0]=True

    def SetHeadPixelId(self, hp ):
        """
        HeadPixelIdを定める
        
        @param self
        @param hp (UInt4) HeadPixelId
        """
        self.HeadPixelId = hp
        self.InfoStatus[1]=True

    def SetPsdInfo(self, pa,pb,pc,ld1,ld2):
        """
        PsdInfoを定める
        
        @param self
        @param pA (Double)  PSDの位置決定用パラメータA
        @param pB (Double)  PSDの位置決定用パラメータB
        @param pC (Double)  PSDの位置決定用パラメータC
        @param LLD1 (Double)  PSDの波高のしきい値(最小値)
        @param LLD2 (Double)  PSDの波高のしきい値(最大値)
        """
        self.PA = pa
        self.PB = pb
        self.PC = pc
        self.LLD1 = ld1
        self.LLD2 = ld2
        self.InfoStatus[2]=True

    def SetPsdBinInfo(self, num, dx, offsetx):
        """
        PsdBinInfoを定める
        PSDを分割するパラメータ
        @param self
        @param dx (UInt4)  PSDの位置決定用分割幅
        @param offsetx (UInt4) PSDの位置決定用オフセット値
        """
        self.BIN_num = num
        if self.BIN_num!=self.NumOfPixel:
            print self.CommentHead+"The number of pixels of PsdBinInfo is different one of PixelInfo."
            return
        self.BIN_dx = dx
        self.BIN_offset = offsetx
        self.InfoStatus[3]=True

    def _SetPsdBinNewNum(self,num):
        """
        PsdBinInfoのnumを変更
        numが変更になると、分割幅dxの変更が必要になる
        @param self
        @param num (UInt4) PSDの分割数
        """
        length  = self.BIN_dx * self.BIN_num
        self.BIN_num = num
        self.BIN_dx = round(length/num)

    def PutPixelInfo(self):
        """
        PixelInfoを返す

        @retval tapple ( DetId (UInt4), NumOfPixel (UInt4) )
        """
        return (self.PutId(), self.NumOfPixel, self.NumAxis)

    def PutHeadPixelId(self):
        """
        HeadPixelIdを返す

        @retval HeadPixelId (UInt4)
        """
        if self.HeadPixelId==-1:
            print self.CommentHead+"Warning: Did not calculate Head PixelId."
            return -1
        else:
            return self.HeadPixelId
    
    def PutPsdInfo(self):
        """
        PsdInfoを返す

        @retval tapple of PA, PB, PC, LLD1, LLD2
        """
        return (self.PA, self.PB, self.PC, self.LLD1, self.LLD2)

    def PutPsdBinInfo(self):
        """
        PsdBinInfoを返す

        @retval tapple of BIN_num, BIN_dx, BIN_offset
        """
        return (self.BIN_num, self.BIN_dx, self.BIN_offset)


################################
#      PsdBinPositionInfo
################################
class PsdBinPositionInfo(ContainerBase):
    """
    PSDのpixel位置決定用情報をおさめるクラス
    左右の波高値とPSDInfoのA,B,Cで計算されるx = A*Hr / (Hl + B*Hr) + C　をPixelIdに変換するためのパラメータ。
    PixelId = HeadPixelId + (x - offset)/dx　：ただしxはUInt4である必要がある。
    """
    def __init__(self,id,num=0,dx=0,offset=0,index=""):
        """
        コンストラクタ
        
        @param self
        @param id (UInt4) Id
        @param num (UInt4) このPSDのPixel数
        @param dx (UInt4)
        @param offset (UInt4)
        @param index (String) このエレメントが適応されるPsdIdを指定（"All", "1-3"など）
        """
        #self.Id = id
        ContainerBase.__init__(self,id)
        self.SetPsdBinInfo(id,num,dx,offset,index)

    #def PutId(self):
    #    return self.Id

    def SetPsdBinInfo(self,id,num,dx,offset,index):
        """
        パラメータ設定

        @param self
        @param id (UInt4) 
        @param num (UInt4) 
        @param dx (UInt4)
        @param offset (UInt4)
        @param index (String)
        """
        self.SetId(id)
        self.numPixel = num
        self.deltaX = dx
        self.offsetX = offset
        self.index = index

    def PutPsdBinInfo(self):
        """
        パラメータ出力
        
        @param self
        @retval tapple of (numPixel, dx, offset, index)
        """
        return (self.numPixel, self.deltaX, self.offsetX, self.index)

################################
#      TofBinInfo
################################
class TofBinInfo(ContainerBase):
    """
    各PSDにおけるTOFの分割方法を収める
    ここで指定されるのはTofBinPatternにて定義されたpatternIdのみである。
    """
    def __init__(self,id,patternId=0,offset=0,index="",maskPtnId=-1):
        """
        コンストラクタ
        
        @param id (UInt4) 
        @param patternId (UInt4)
        @param offset (UInt4)
        @param index (String)
        @param maskPtnId (Int4)
        """
        #self.Id = id
        ContainerBase.__init__(self,id)
        self.SetTofBinInfo(id,patternId,offset,index,maskPtnId)

    #def PutId(self):
    #    return self.Id

    def SetTofBinInfo(self,id,patternId,offset,index,maskPtnId):
        """
        各種パラメータ設定
        
        @param id (UInt4) 
        @param patternId (UInt4)
        @param offset (UInt4)
        @param index (String)
        """
        self.SetId(id)
        self.patternId = patternId
        self.offsetBin = offset
        self.index = index
        self.maskPtnId = maskPtnId

    def PutTofBinInfo(self):
        """
        パラメータを返す
        
        @retval tupple (patternId, offsetBin, index, maskPtnId)
        """
        return (self.patternId, self.offsetBin, self.index, self.maskPtnId)

################################
#      TofBinPattern
################################
class TofBinPattern(ContainerBase):
    """
    TOFの分割方法をパターン化して収める
    指定されたTofBinPatternをpatternIdで定義する。
    """
    def __init__(self,id,patternId=0,type=1,contents=""):
        """
        コンストラクタ
        
        @param id (UInt4) 
        @param patternId (UInt4)
        @param type (UInt4)
        @param contents (String)
        """
        #self.Id = id
        ContainerBase.__init__(self,id)
        self.SetTofBinPattern(id,patternId,type,contents)

    #def PutId(self):
    #    return self.Id

    def SetTofBinPattern(self,id,patternId,type,contents):
        """
        パラメータの設定
        
        @param id (UInt4) 
        @param patternId (UInt4)
        @param type (UInt4)  1:羅列, 2:deltaT=const., 3:dT/T = const., 0:複合
        @param contents (String)
        """
        self.SetId(id)
        self.patternId = patternId
        self.type = type
        self.Cont = contents

    def PutTofBinPattern(self):
        """
        パラメータを返す

        @retval tupple (patternId, type, Cont)
        """
        return (self.patternId, self.type, self.Cont)

################################
#      TofDoubleFrameBoundary
# added 2011.01.04
################################
class TofDoubleFrameBoundary(ContainerBase):
    """
    Boundary TOF of Double Frame
    This keeps tof value
    """
    def __init__(self,id,boundaryTof=0.0):
        """
        コンストラクタ
        
        @param id (UInt4) 
        @param boundaryTof (Double)

        """
        #self.Id = id
        ContainerBase.__init__(self,id)
        self.SetTofDoubleFrameBoundary(id,boundaryTof)


    def SetTofDoubleFrameBoundary(self,id,boundaryTof):
        """
        パラメータの設定
        
        @param id (UInt4)
        @param boundaryTof (Double)

        """
        self.SetId(id)
        self.boundaryTof = boundaryTof

    def PutTofDoubleFrameBoundary(self):
        """
        パラメータを返す

        @retval double ( tof of DoubleFrameBoundary)
        """
        return self.boundaryTof

################################
#      FrameInfo
# added 2012.06.26
################################
class FrameInfo(ContainerBase):
    """
    Use frameNo and Boundary TOF
    This keeps tof value
    """
    def __init__(self,id,frameNo=0,boundaryTof=0.0):
        """
        コンストラクタ
        
        @param id (UInt4)
        @param frameNo (UInt4)
        @param boundaryTof (Double)

        """
        #self.Id = id
        ContainerBase.__init__(self,id)
        self.SetFrameInfo(id,frameNo,boundaryTof)
        

    def SetFrameInfo(self,id,frameNo,boundaryTof):
        """
        パラメータの設定
        
        @param id (UInt4)
        @param frameNo (UInt4)
        @param boundaryTof (Double)

        """
        self.SetId(id)
        self.frameNo = frameNo
        self.boundaryTof = boundaryTof

    def PutFrameInfo(self):
        """
        パラメータを返す

        @retval double ( tof of DoubleFrameBoundary)
        """
        return (self.frameNo,self.boundaryTof)

################################
#      TofMaskPattern
# added 2014.12.09
################################
class TofMaskPattern(ContainerBase):
    """
    TOFのMask方法をパターン化して収める
    指定されたTofMaskPatternをmaskPtnIdで定義する。
    """
    def __init__(self,id,maskPtnId=0,contents=""):
        """
        コンストラクタ
        
        @param id (UInt4) 
        @param maskPtnId (UInt4)
        @param contents (String)
        """
        
        ContainerBase.__init__(self,id)
        self.SetTofMaskPattern(id,maskPtnId,contents)


    def SetTofMaskPattern(self,id,maskPtnId,contents):
        """
        パラメータの設定
        
        @param id (UInt4) 
        @param maskPtnId (UInt4)
        @param contents (String)
        """
        self.SetId(id)
        self.maskPtnId = maskPtnId
        self.Cont = contents

    def PutTofMaskPattern(self):
        """
        パラメータを返す

        @retval tupple (maskPtnId, Cont)
        """
        return (self.maskPtnId, self.Cont)


################################
#      Container
################################
class Carrier(ContainerBase):
    """
    ContainerBaseから派生した各種コンテナを収めるクラス
    コンテナを収め、それらをIDで管理する。
    """
    def __init__(self,id,note="Container"):
        """
        コンストラクタ

        @param id (UInt4)
        @param note (String) 自由なメモがわり
        """
        #self.Id=id
        ContainerBase.__init__(self,id)
        self.Note = note
        #self.Status = 1   #1:alive 0:killed
        self.NumOfCont=0
        self.ListCont=[]
        #self.ListContId=[]
        self.ContType=None
        self.CommentHead = "  Carrier >"
        
    """
    def SetId(self,id):
        self.Id=id

    def PutId(self):
        return self.Id

    def SetStatus(self,status):
        self.Status = status

    def PutStatus(self):
        return self.Status
    """
    def PutContainerIdList(self):
        """
        このコンテナに収められているIDのリストを返す

        @retval list
        """
        ret = []
        for cont in self.ListCont:
            ret.append(cont.PutId())
        return ret
            
    def AddContainer(self,cont):
        """
        新しいコンテナを追加
        同じidがあった場合は無視する
        @param cont (ContainerBase)
        """
        if self.ContType==None:
            self.ContType=type(cont)

        if (self.ContType==type(cont)):
            id = cont.PutId()
            list = self.PutContainerIdList()
            if list.count(id)!=0:
                print self.CommentHead+"The id is already used in this container. id=",id
                return -1
            self.ListCont.append(cont)
            self.NumOfCont = len(self.ListCont)
            return 0
        else:
            print self.CommentHead+"Argument is invalid."
            print self.CommentHead+"Original type = ",self.ContType," and new type = ",type(cont)
            return -1

    def PutContainer(self,id):
        """
        コンテナを返す
        
        @param id (UInt4) id
        @retval (ContainerBase)
        """
        index = self._SearchId(id)
        if index!=-1:
            return self.ListCont[index]
        else:
            #print "ID is invalid."
            return -1

    def RemoveContainer(self,id):
        """
        コンテナを取り除く

        @param id (UInt4) 
        """
        index = self._SearchId(id)
        if index!=-1:
            self.NumOfCont -= 1
            orgList = self.ListCont
            self.ListCont=[]
            for i in range(self.NumOfCont+1):
                if i!=index:
                    self.ListCont.append(orgList[i])
            return 0
        else:
            #print "ID is invalid."
            return -1
                
    def _SearchId(self, Id):
        for i in range(self.NumOfCont):
            cont = self.ListCont[i]
            id_i = cont.PutId()
            if Id==id_i :
                return i
        return -1
            
    def PutNote(self):
        """
        ノートを取り出す

        @retval (String)
        """
        return self.Note
    
    def SortId(self):
        """
        コンテナをそのIdで並び替える

        """
        orgList = self.ListCont
        orgListId = self.PutContainerIdList()
        dic = {}
        for i in range( len( orgList ) ):
            dic[ orgListId[i] ]=orgList[i]
            
        orgListId.sort()
        self.ListCont=[]
        for id in orgListId:
            self.ListCont.append(dic[ id ])
            
################################
#      OneModule
################################
class OneModule(Carrier):
    def __init__(self,id,type="",note="Container"):
        """
        コンストラクタ

        @param id (UInt4)
        @param note (String) 自由なメモがわり
        """
        #self.Id=id
        Carrier.__init__(self,id,note)
        self.DetectorType=type
        self.TrigIndex=-1
        
    def PutDetectorType(self):
        return self.DetectorType
    
    def SetTrigIndex(self,ind):
        self.TrigIndex=ind
    
    def PutTrigIndex(self):
        return self.TrigIndex
    
    
################################
#      EditWiringInfo
################################           
class EditWiringInfo(object):
    """
    DetectorInfo.xmlを読み込み、編集し、書き出すためのクラス
    各種情報はないように応じたコンテナに収められ、IdをつけてContainerへ収まる。
    InstCode : Instrument Code (ex. AMR, SIK, MAT,...)
    InstInfo : PixelInfoのDAQ,module,detectorの構造を収める。
    DetInfoList : DetInfoList[detID] = (flag,daq,mod) flag:0/No set, 1/Set daq:daq id, mod:module number
    MaxDetId : 読み込まれたDetIdの最大値
    psdBinInfoList : psdBinInfoの情報を収める（PSDの位置）
    tofBinInfo : TOFの分割の情報を持つ
    tofBinPattern : TOF分割のパターンを収める
    """
    InstCode = ""
    InstInfo = None
    DetInfoList = []
    MaxDetId = 0
    psdBinInfoList = None

    tofBinInfo = None
    tofBinPattern = None
    tofDoubleFrameBoundary = None ##[inamura 110104]
    frameInfo = None              ##[inamura 120626]
    
    WFDef = WiringFileDef()
    
    def __init__(self,filename, debug=0):
        """
        コンストラクタ

        @param filename (String) 読み込むDetectorInfo.xml
        @param debug (UInt4) 0:debug off / 1:debug on
        """
        self.FileName = filename
        self.Debug = debug
        self.CommentHead = "EditDetectorInfo >>> "
        
        self._ReadContainer()


    def PutInfo(self):
        """
        InstInfoキャリアを返す
        @retval Carrier
        """
        return self.InstInfo


    def _ReadContainer(self):
        """
        DetectorInfo.xmlを読み込み各種コンテナへ収める
        @retval None
        """
        ## load XML file
        if os.path.exists(self.FileName):
            xmlfile = parse(self.FileName)
        else:
            print self.CommentHead+"Can't read ",self.FileName
            return

        max_detId = 0

        #W=WiringFileDef()
        W = self.WFDef
        # check inst
        detTopInfoXml = xmlfile.getElementsByTagName(W.ROOT)[0]
        self.InstCode = detTopInfoXml.getAttribute(W.ROOT_AT_INST)
        if self.InstCode!="SIK":
            print self.CommentHead+self.FileName," is for ",self.InstCode
        
        # pixelInfo tag
        pixelInfoXml = detTopInfoXml.getElementsByTagName(W.ROOT_PIXELINFO)[0]
        num_of_daq = int( pixelInfoXml.getAttribute("n") )
        
        ListDaqInfoXml = pixelInfoXml.getElementsByTagName(W.ROOT_PIXELINFO_DAQ)

        if self.Debug!=0: print self.CommentHead+"The number of DAQ tag = ",len(ListDaqInfoXml)

        # Analysis of XML for pixelInfo
        InstInfo = Carrier(0,"Container for DAQ")
        for daq_i in range(num_of_daq):
            daq = self._SearchIndexInXml(ListDaqInfoXml,daq_i)
            if (daq!=-1):
                daqInfoXml = ListDaqInfoXml[daq]
                daqId = int( daqInfoXml.getAttribute(W.ROOT_PIXELINFO_DAQ_AT_ID) )
                daqInfo = Carrier(daqId,"Container for Module")
                
                ListModInfoXml = daqInfoXml.getElementsByTagName(W.ROOT_PIXELINFO_DAQ_MOD)
                num_of_mod = int( daqInfoXml.getAttribute("n") )
                for mod_i in range(num_of_mod):
                    mod = self._SearchIndexInXml(ListModInfoXml,mod_i)
                    if (mod!=-1):
                        modInfoXml = ListModInfoXml[mod]
                        modNo = int( modInfoXml.getAttribute(W.ROOT_PIXELINFO_DAQ_MOD_AT_NO) )
                        #modInfo = Carrier(modNo,"Container for PSD")
                        detType = modInfoXml.getAttribute(W.ROOT_PIXELINFO_DAQ_MOD_AT_TYPE)
                        modInfo = OneModule(modNo,detType,"Container for PSD")
                        
                        if detType in ["PSD","N2MON","N2MON1","N2MON2"]:
                            ListDetInfoXml = modInfoXml.getElementsByTagName(W.ROOT_PIXELINFO_DAQ_MOD_DET)
                            num_of_det = int( modInfoXml.getAttribute("n") )
                            for det_i in range(num_of_det):
                                det = self._SearchIndexInXml(ListDetInfoXml,det_i)
                                if (det!=-1):
                                    detInfoXml = ListDetInfoXml[det]
                                    detId = int( detInfoXml.getAttribute(W.ROOT_PIXELINFO_DAQ_MOD_DET_AT_ID) )
                                    numAxis = int( detInfoXml.getAttribute(W.ROOT_PIXELINFO_DAQ_MOD_DET_AT_AXIS) )
                                    headPixelId = int( detInfoXml.getAttribute(W.ROOT_PIXELINFO_DAQ_MOD_DET_AT_HEAD) )
                                    numPixel = int( detInfoXml.getAttribute(W.ROOT_PIXELINFO_DAQ_MOD_DET_AT_NUM) )

                                    detInfo = OneDetInfo(detId,numPixel,numAxis)
                                    detInfo.SetHeadPixelId(headPixelId)
                                    if (modInfo.AddContainer( detInfo )<0):
                                        print self.CommentHead+"False to AddContainer modInfo( detInfo=",detInfo.Id,")"
                                    if self.Debug!=0:
                                        print self.CommentHead+"        store OneDetInfo(id=",detId,") into ModInfo(",modNo,")"
                                    if detId>max_detId:
                                        max_detId = detId

                                else:
                                    print self.CommentHead+"Cannot find detector i=",det_i," in mod(",modNo,") in daq(",daqId,")"
                        elif detType=="TRIGNET":
                            trigIndex = int( modInfoXml.getAttribute(W.ROOT_PIXELINFO_DAQ_MOD_AT_TRIGINDEX) )
                            modInfo.SetTrigIndex( trigIndex )
                            
                        else:
                            pass
                        
                        if (daqInfo.AddContainer(modInfo)<0):
                            print self.CommentHead+"False to AddContainer daqInfo( modInfo=",modInfo.Id,")"
                        if self.Debug!=0:
                            print self.CommentHead+"    Stored ModInfo(",modNo,") into DaqInfo(id=",daqId,")"
                    else:
                        print self.CommentHead+"Cannot find module i=",mod_i," in DAQ(id=",daqId,")"
                
                if (InstInfo.AddContainer(daqInfo)<0):
                    print self.CommentHead+"False to AddContainer InstInfo( daqInfo=",daqInfo.Id,")"
                
            else:
                print self.CommentHead+"Cannot find Daq i=",daq_i," in loaded XML file."
        
        self.InstInfo = InstInfo
        self.MaxDetId = max_detId
        if self.Debug!=0: print self.CommentHead+"finish: makeing InstInfo."
        
        # Make list to convert from detId and [daq,mod]
        DetInfoList = []
        for detId in range((max_detId+1)):
            InfoList = (0, 0, 0) # ( flag, daqId, modNo ) flag=0:No loaded , flag=1: loaded
            DetInfoList.append(InfoList)

        for daq in self.InstInfo.PutContainerIdList():
            for mod in self.InstInfo.PutContainer(daq).PutContainerIdList():
                for detId in self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainerIdList():
                    if DetInfoList[detId][0]==0:
                        DetInfoList[detId] = ( 1, daq, mod )
                    else:
                        print self.CommentHead+"Warning: There is double definision of detId = ",detId
                        print self.CommentHead+"       : at daq=",DetInfoList[detId][1],", mod=",DetInfoList[detId][2]," and"
                        print self.CommentHead+"       : at daq=",daq,", mod=",mod,"."
                    # You can take out OneDetInfo of detId
                    # (flag,daq,mod) = DetInfoList[detId]
                    # InstInfo.PutContainer( daq ).PutContainer( mod ).PutContainer( detId )
        self.DetInfoList = DetInfoList
        
        # Check of HeadPixelId
        #self.CheckHeadPixelId()
            
        # Analysis of XML for psdParam 
        psdParamXml = detTopInfoXml.getElementsByTagName(W.ROOT_PSDPARAM)[0]
        num_of_psdParam = int( psdParamXml.getAttribute("n") )
        paramListXml = psdParamXml.getElementsByTagName(W.ROOT_PSDPARAM_PARAM)

        for param_i in range(num_of_psdParam):
            param = self._SearchIndexInXml(paramListXml,param_i)
            if (param!=-1):
                paramXml = paramListXml[param]
                detId = int( paramXml.getAttribute(W.ROOT_PSDPARAM_PARAM_AT_ID) )
                cont_str = paramXml.firstChild.data
                cont_str_list = cont_str.split(',')
                cont_list = []
                for i in range(len(cont_str_list)):
                    cont_list.append( float( cont_str_list[i] ) )
                
                if detId>=(len(self.DetInfoList)):
                    continue
                (flag,daq,mod) = self.DetInfoList[detId]
                #flag = self.DetInfoList[detId][0]
                #daq = self.DetInfoList[detId][1]
                #mod = self.DetInfoList[detId][2]
                if flag==0:
                    continue
                info = self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(detId)
                
                if (len(cont_list)==3):
                    info.SetPsdInfo(cont_list[0],cont_list[1],cont_list[2],0.0,10000.0)
                elif (len(cont_list)==5):
                    info.SetPsdInfo(cont_list[0],cont_list[1],cont_list[2],cont_list[3],cont_list[4])
                else:
                    print self.CommentHead+"Error : the number of psd parameters at detId=",detId
                    print self.CommentHead+"      : and these parameters are not set."
        
        for i_detId in range(self.MaxDetId+1):
            (flag,daq,mod) = self.DetInfoList[i_detId]
            if flag==1:
                info = self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(i_detId)
                if not info.InfoStatus[2]:
                    msg = self.CommentHead+"Error : PsdParameter is not set on detId=%d"%(i_detId)
                    raise UserWarning,msg
        
            
        # Analysis of XML for psdBinInfo
        binInfoXml_list = detTopInfoXml.getElementsByTagName(W.ROOT_PSDBININFO)
        psdBinInfoList = Carrier(0,"Container for psdBinInfo")
        for binInfoXml in binInfoXml_list:
            psdBinSetId = int( binInfoXml.getAttribute(W.ROOT_PSDBININFO_AT_ID) )
            num_of_binInfo = int( binInfoXml.getAttribute("n") )
            posiBinListXml = binInfoXml.getElementsByTagName(W.ROOT_PSDBININFO_BIN)

            psdBinInfo = Carrier(psdBinSetId,"Container for positionBin")
            for posiBin_i in range(num_of_binInfo):
                posiBin = self._SearchIndexInXml(posiBinListXml,posiBin_i)
                
                if (posiBin!=-1):
                    posiBinXml = posiBinListXml[posiBin]
                    pb_numPixel = int( posiBinXml.getAttribute(W.ROOT_PSDBININFO_BIN_AT_NUM) )
                    pb_deltaX = int( posiBinXml.getAttribute(W.ROOT_PSDBININFO_BIN_AT_DELTA) )
                    pb_offsetX = int( posiBinXml.getAttribute(W.ROOT_PSDBININFO_BIN_AT_OFFSET) )
                    cont_str = posiBinXml.firstChild.data
                    cont_str_list = cont_str.split(',')
                    for tag in cont_str_list:
                        ret=self._CheckIndexOnTag(tag)
                        if ret==[-10,-10]: # means false of analysis
                            print self.CommentHead+"Warning: invalid index on posisionBin."
                        elif ret==[-1,-1]: # means "All"
                            for detId in range( len(self.DetInfoList) ):
                                if self.DetInfoList[detId][0]!=0:
                                    (flag,daq,mod) = self.DetInfoList[detId]
                                    info = self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(detId)
                                    info.SetPsdBinInfo( pb_numPixel, pb_deltaX, pb_offsetX )
                        elif ret[0]==ret[1]:
                            detId = ret[0]
                            if detId>(len(self.DetInfoList)+1):
                                continue
                            if self.DetInfoList[detId][0]!=0:
                                (flag,daq,mod) = self.DetInfoList[detId]
                                info = self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(detId)
                                info.SetPsdBinInfo( pb_numPixel, pb_deltaX, pb_offsetX )
                            else:
                                print self.CommentHead+"Warning: invalid index on posisionBin at detId = ",ret[0]
                    
                        else:
                            for detId in range(ret[0],(ret[1]+1)):
                                if detId>(len(self.DetInfoList)+1):
                                    continue
                                
                                if self.DetInfoList[detId][0]!=0:
                                    (flag,daq,mod) = self.DetInfoList[detId]
                                    info = self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(detId)
                                    info.SetPsdBinInfo( pb_numPixel, pb_deltaX, pb_offsetX )
                                
                    positionBin = PsdBinPositionInfo(posiBin,pb_numPixel, pb_deltaX, pb_offsetX, cont_str)
                 
                else:
                    print self.CommentHead+"Warning:Cannot find positionBin i=",posiBin_i
        
                psdBinInfo.AddContainer(positionBin)
            
            psdBinInfoList.AddContainer(psdBinInfo)
        self.psdBinInfoList = psdBinInfoList
        
        # Analysis of XML for tofBinInfo
        print self.CommentHead+"Analysis for tofBinInfo"
        tofInfoXml = detTopInfoXml.getElementsByTagName(W.ROOT_TOFBININFO)[0]
        num_of_tofInfo = int( tofInfoXml.getAttribute("n") )
        tofBinListXml = tofInfoXml.getElementsByTagName(W.ROOT_TOFBININFO_TOFBIN)

        print self.CommentHead+"num_of_tofInfo=",num_of_tofInfo
        tofBinInfo = Carrier(0,"Container for tofBinInfo")
        for tofBin_i in range(num_of_tofInfo):
            tof_bin_i = self._SearchIndexInXml(tofBinListXml,tofBin_i)
            
            if (tof_bin_i!=-1):
                tofBinXml = tofBinListXml[tof_bin_i]
                tb_patternId = int( tofBinXml.getAttribute(W.ROOT_TOFBININFO_TOFBIN_AT_PAT) )
                tb_offsetBin = int( tofBinXml.getAttribute(W.ROOT_TOFBININFO_TOFBIN_AT_OFFSET) )
                ##[inamura 141209]-->
                st_tofMaskPtnId = tofBinXml.getAttribute(W.ROOT_TOFBININFO_TOFBIN_AT_MASK)
                tb_maskPtnId = -1
                if (st_tofMaskPtnId!=""):
                    tb_maskPtnId = int(st_tofMaskPtnId)
                cont_str = tofBinXml.firstChild.data
                tofBin = TofBinInfo(tof_bin_i, tb_patternId, tb_offsetBin, cont_str, tb_maskPtnId) ##[inamura 141209]
            else:
                print self.CommentHead+"Warnning:Cannot find tofBin i=",tofBin_i
            
            tofBinInfo.AddContainer(tofBin)

        self.tofBinInfo = tofBinInfo
        
        # Analysis of XML for tofBinPattern
        tofPtnXml = detTopInfoXml.getElementsByTagName(W.ROOT_TOFBINPAT)[0]
        num_of_tofPtn = int( tofPtnXml.getAttribute("n") )
        tofPtnListXml = tofPtnXml.getElementsByTagName(W.ROOT_TOFBINPAT_PAT)
        
        self.tofBinPattern = Carrier(0,"Container for tofBinPattern")
        for tofPtn_i in range(num_of_tofPtn):
            tof_ptn_i = self._SearchIndexInXml(tofPtnListXml, tofPtn_i)
            
            if(tof_ptn_i!=-1):
                tofPtnXml = tofPtnListXml[tof_ptn_i]
                pt_patternId = int( tofPtnXml.getAttribute(W.ROOT_TOFBINPAT_PAT_AT_ID) )
                pt_type = int( tofPtnXml.getAttribute(W.ROOT_TOFBINPAT_PAT_AT_TYPE) )
                cont_str = tofPtnXml.firstChild.data
                tofPattern = TofBinPattern(tof_ptn_i, pt_patternId, pt_type, cont_str )
            else:
                print self.CommentHead+"Warning: Cannot find tofBinPattern i=",tofPtn_i
            
            self.tofBinPattern.AddContainer(tofPattern)
        
        ##[inamura 141209]-->
        # Analysis of XML for tofMaskPattern
        maskPtnXml = detTopInfoXml.getElementsByTagName(W.ROOT_TOFMASKPAT)
        self.tofMaskPattern = Carrier(0,"Container for tofMaskPattern")
        if (len(maskPtnXml)!=0):
            maskPtnXml = maskPtnXml[0]
            num_of_maskPtn = int( maskPtnXml.getAttribute("n") )
            maskPtnListXml = maskPtnXml.getElementsByTagName(W.ROOT_TOFMASKPAT_PAT)
            
            for maskPtn_i in range( num_of_maskPtn ):
                mask_ptn_i = self._SearchIndexInXml(maskPtnListXml, maskPtn_i)
                if (mask_ptn_i!=-1):
                    a_maskPtnXml = maskPtnListXml[mask_ptn_i]
                    pt_maskPtnId = int( a_maskPtnXml.getAttribute(W.ROOT_TOFMASKPAT_PAT_AT_ID) )
                    cont_str = a_maskPtnXml.firstChild.data
                    maskPattern = TofMaskPattern(mask_ptn_i, pt_maskPtnId,  cont_str )
                else:
                    print self.CommentHead+"Warning: Cannot find tofMaskPattern i=",maskPtn_i

                self.tofMaskPattern.AddContainer(maskPattern)
        ##<--[inamura 141209]
        
        ##[inamura 110104]-->
        # Analysis of TofDoubleFrameBoundary
        # print "TofDoubleFrameBoudary Setting"
        self.tofDoubleFrameBoundary = TofDoubleFrameBoundary( 0, 0.0 )
        tofDFBoundary_list = detTopInfoXml.getElementsByTagName(W.ROOT_TOFDOUBLEFRAME)
        if len(tofDFBoundary_list)==1:
            tof_boundary = float( tofDFBoundary_list[0].firstChild.data )
            if tof_boundary!=0.0:
                self.tofDoubleFrameBoundary = TofDoubleFrameBoundary( 0, tof_boundary )
        ##<--[inamura 110104]

        ##[inamura 120626]-->
        # Analysis of FrameInfo
        #print "FrameInfo Setting"
        self.frameInfo = FrameInfo( 0 )
        frameInfo_list = detTopInfoXml.getElementsByTagName(W.ROOT_FRAMEINFO)
        if len(frameInfo_list)==1:
            frameNo = float( frameInfo_list[0].getAttribute( W.ROOT_FRAMEINFO_FRAMENO ) )
            boundary= float( frameInfo_list[0].getAttribute( W.ROOT_FRAMEINFO_BOUNDARY ) )
            self.frameInfo.SetFrameInfo( 0, frameNo, boundary )
        ##<--[inamura 120626]
        
        #detTopInfoXml.unlink()
        xmlfile.unlink()
        

    def _SearchIndexInXml(self, ListXml, index ):
        """
        XMLのエレメントのリストからインデックスiで検索する
        XMLのエレメントgetElementByTagなどで得られたエレメントのリストから、attribute iがindexとなるエレメントを取り出す。
        @param ListXml(List) XMLエレメント
        @param index(UInt4) 必要なindex
        @retval (XML Element)
        """
        num_list = len( ListXml )
        i=0
        while(True):
            monoXml = ListXml[i]
            if (int( monoXml.getAttribute("i") )==index):
                return i
            else:
                if i<(num_list-1):
                    i+=1
                else:
                    print self.CommentHead+"::_SearchIndexInXml : Index is invalid. i<num_list-1 = ",i,"<",num_list-1
                    return -1

        
    def _CheckIndexOnTag(self,tag):
        """
        XMLのコンテンツにおける範囲指定の解析
        使えるのは'All' 'num-num'
        @param tag (String)
        @retval None
        """
        tag = tag.replace(' ','')
        if tag=='All':
            retval = [-1,-1]
        else:
            tag_sp = tag.split('-')
            if len(tag_sp)==2:
                retval = [ int(tag_sp[0]), int(tag_sp[1]) ]
            elif len(tag_sp)==1:
                retval = [ int(tag_sp[0]), int(tag_sp[0]) ]
            else:
                retval = [-10,-10]
        
        return retval

    def CheckHeadPixelId(self):
        """
        HeadPixelIdのチェック
        <detector>のnumPixelsからHeadPixelIdをチェックする
        @retval None
        """
        continue_flag = 0
        curr_headPixelId = 0
        ort_headPixelId = 0
        for detId in range(self.MaxDetId+1):
            if self.DetInfoList[detId][0]==0:
                curr_headPixelId = 0
                curr_num = 0
                continue_flag = 0
            else:
                (flag,daq,mod) = self.DetInfoList[detId]
                #print (flag,daq,mod,detId)
                info = self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(detId)
                if continue_flag==0:
                    curr_headPixelId = info.PutHeadPixelId()
                    (det,num,axis) = info.PutPixelInfo()
                    curr_num = num
                    continue_flag = 1
                else:
                    curr_headPixelId += curr_num
                    org_headPixelId = info.PutHeadPixelId()
                    if org_headPixelId!=curr_headPixelId:
                        print self.CommentHead+"Warning: invalid headPixelId was given at detID=",detId
                        print self.CommentHead+"       : Correct from ",org_headPixelId," to ",curr_headPixelId
                    info.SetHeadPixelId(curr_headPixelId)
                    (det,num,axis) = info.PutPixelInfo()
                    curr_num = num
                    continue_flag = 1


    def ReSetNumOfPixel(self,start_id=0,end_id=0,headId=-1,num=0):
        """
        HeadPixelIdの再計算
        1PSDあたりのPixel数からHeadPixelIdを再計算
        @param start_id (int) 最初のPSD-ID
        @param end_id (int) 最後のPSD-ID
        @param headId (int) 最初のPSD-IDのHeadPixelId (-1: use first headPixelId )
        @param num (int) Pixel数 at one PSD
        @retval None
        """
        if (start_id==0)&(end_id==0)&(headId==0)&(num==0):
            print self.CommentHead+"ReSetNumOfPixel( start_id, end_id, headPixelId, numOfPixel )"
            return
        if self.Debug!=0:
            print self.CommentHead+"Start Id = ",start_id
            print self.CommentHead+"End Id = ",end_id
            print self.CommentHead+"HeadPixelId at Start Id = ",headId
            print self.CommentHead+"number of pixels = ",num
        
        curr_headId = headId
        isChangedHeadId = False
        for detId in range(start_id,(end_id+1)):
            if self.DetInfoList[detId][0]!=0:
                (flag,daq,mod) = self.DetInfoList[detId]
                info = self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(detId)
                
                ##[inamura 150414]-->
                if info.Status==0:
                    continue
                if (isChangedHeadId==False) and (info.NumOfPixel!=num):
                    isChangeHeadId = True
                
                if curr_headId==-1:
                    curr_headId=info.PutHeadPixelId()
                
                info.SetPixelInfo(detId,num)
                if (isChangedHeadId):
                    info.SetHeadPixelId(curr_headId)
                    curr_headId += num
                else:
                    curr_headId = info.PutHeadPixelId()

                #info.SetPixelInfo(detId,num)
                #info.SetHeadPixelId(curr_headId)
                #curr_headId += num
                
        if (isChangedHeadId):
            self.CheckHeadPixelId()
                ##<--[inamura 150414]

    def CopyAPsd(self,from_psdId_in,to_psdId_in):
        if type(from_psdId_in)==type(0):
            from_psdId = from_psdId_in
            (f_flag,f_daq,f_mod) = self.DetInfoList[from_psdId]
        elif len(from_psdId_in)==3:
            from_psdId = from_psdId_in[2]
            (f_flag,f_daq,f_mod) = self.DetInfoList[from_psdId]
        if (f_flag==0):
            print self.CommentHead+"Original PsdId is not exist."
            return

        f_psd_info = self.InstInfo.PutContainer(f_daq).PutContainer(f_mod).PutContainer(from_psdId)
        (id,num_pixel,axis) = f_psd_info.PutPixelInfo()
        headPixelId = f_psd_info.PutHeadPixelId()
        (A,B,C,LD,LD2)=self.PutPsdParam(from_psdId)
        (num,dx,offset)=self.PutPsdPositionInfo(from_psdId)
        
        if type(to_psdId_in)==type(0):
            to_psdId = to_psdId_in
            (t_flag,t_daq,t_mod) = self.DetInfoList[to_psdId]
        elif len(to_psdId_in)==3:
            to_psdId = to_psdId_in[2]
            if to_psdId>self.MaxDetId:
                (t_flag,t_daq,t_mod)=(0,-1,-1)
            else:
                (t_flag,t_daq,t_mod) = self.DetInfoList[to_psdId]
        if (t_flag==0):
            if (len(to_psdId_in)!=3):
                print self.CommentHead+"PsdId copied to is not exist."
                return
            else:
                (t_daq,t_mod) = (to_psdId_in[0],to_psdId_in[1])
                if t_daq in self.InstInfo.PutContainerIdList():
                    if not t_mod in self.InstInfo.PutContainer(t_daq).PutContainerIdList():
                        self.AddNewModule(t_daq,t_mod)
                else:
                    print self.CommentHead+"There is no such DAQ ID",t_daq
                    return

        t_mod_info = self.InstInfo.PutContainer(t_daq).PutContainer(t_mod)
        if not to_psdId in t_mod_info.PutContainerIdList():
            self.AddNewDet(t_daq,t_mod,to_psdId,num_pixel)

        to_psdId_info = t_mod_info.PutContainer(to_psdId)
        to_psdId_info.SetPixelInfo(to_psdId,num_pixel,axis)
        to_psdId_info.SetHeadPixelId(headPixelId)
        self.SetPsdParam(to_psdId,A,B,C,LD,LD2)
        self.SetPsdPositionInfo(to_psdId,dx,offset)
            

    def SuspendDaq(self,daq=-1):
        if (daq==-1):
            daq_list = self.InstInfo.PutContainerIdList()
        else:
            daq_list = [daq]
        
        for daq_i in daq_list:
            info_daq = self.InstInfo.PutContainer(daq_i)
            if info_daq!=-1:
                info_daq.SetStatus(0)
                for mod in info_daq.PutContainerIdList():
                    self.SuspendModules(daq_i,mod)
                """
                for detId in info_daq.PutContainer(mod).PutContainerIdList():
                    (flag,daq,mod) = self.DetInfoList[detId]
                    info = self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(detId)
                    info.SetStatus(0)
                    #self.DetInfoList[detId][0]=0
                """

    def ResumeDaq(self,daq):
        info_daq = self.InstInfo.PutContainer(daq)
        if info_daq!=-1:
            info_daq.SetStatus(1)
            for mod in info_daq.PutContainerIdList():
                self.ResumeModules(daq,mod)
                """
                for detId in info_daq.PutContainer(mod).PutContainerIdList():
                    (flag,daq,mod) = self.DetInfoList[detId]
                    info = self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(detId)
                    info.SetStatus(1)
                    #self.DetInfoList[detId][0]=1
                """

    def SuspendModules(self,daq,mod_in):
        self._ChangeAliveDet(daq,mod_in,0)

    def ResumeModules(self,daq,mod_in):
        self._ChangeAliveDet(daq,mod_in,1)
        
    def SelectByDetType(self,detType):
        for daq in self.InstInfo.PutContainerIdList():
            mod_list = self.InstInfo.PutContainer(daq).PutContainerIdList()
            if len(mod_list)==0:
                continue
            for mod in mod_list:
                detType_mod = self.InstInfo.PutContainer(daq).PutContainer(mod).PutDetectorType()
                if type(detType)==type([]):
                    if detType_mod in detType:
                        pass
                    else:
                        self.SuspendModules(daq,mod)
                else:
                    if detType!=detType_mod:
                        self.SuspendModules(daq,mod)
                #else:
                #    self.ResumeModules(daq,mod)
                
    def _ChangeAliveDet(self,daq_in,mod_in,flag_in):
        if flag_in==1:
            self.InstInfo.PutContainer(daq_in).SetStatus(flag_in)
        if type(mod_in)==type([]):
            for mod in mod_in:
                mod_info = self.InstInfo.PutContainer(daq_in).PutContainer(mod)
                mod_info.SetStatus(flag_in)
                detId_list = mod_info.PutContainerIdList()
                for detId in detId_list:
                    (dummy,daq,mod) = self.DetInfoList[detId]
                    if daq_in != daq:
                        print self.CommentHead+"DetId %d is not in DAQ%d but in DAQ%d." % (detId,daq_in,daq)
                    info = self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(detId)
                    info.SetStatus(flag_in)
                    #self.DetInfoList[detId][0]=flag
        elif type(mod_in)==type(0):
            #print "Do Change Status of module"
            mod_info = self.InstInfo.PutContainer(daq_in).PutContainer(mod_in)
            mod_info.SetStatus(flag_in)
            detId_list = mod_info.PutContainerIdList()
            for detId in detId_list:
                (dummy,daq,mod) = self.DetInfoList[detId]
                if daq_in != daq:
                    print self.CommentHead+"DetId %d is not in DAQ%d but in DAQ%d." % (detId,daq_in,daq)
                info = self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(detId)
                info.SetStatus(flag_in)
                #self.DetInfoList[detId][0]=flag
        elif type(mod_in)==type(""):
            st_mod_list = mod_in.split(',')
            for item in st_mod_list:
                ret = self._CheckIndexOnTag(item)
                if ret==[-10,-10]:
                    print self.CommentHead+"Error: Cannot analysis your arguments"
                    return
                elif ret==[-1,-1]:
                    self.RemoveDaq(daq_in)
                elif ret[0]==ret[1]:
                    mod_info = self.InstInfo.PutContainer(daq_in).PutContainer(ret[0])
                    mod_info.SetStatus(flag_in)
                    detId_list = mod_info.PutContainerIdList()
                    for detId in detId_list:
                        (dummy,daq,mod) = self.DetInfoList[detId]
                        info = self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(detId)
                        info.SetStatus(flag_in)
                        #self.DetInfoList[detId][0]=flag
                else:
                    for mod in range(ret[0],(ret[1]+1)):
                        mod_info = self.InstInfo.PutContainer(daq_in).PutContainer(mod)
                        mod_info.SetStatus(flag_in)
                        detId_list = mod_info.PutContainerIdList()
                        for detId in detId_list:
                            (dummy,daq,mod) = self.DetInfoList[detId]
                            info = self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(detId)
                            info.SetStatus(flag_in)
                            #self.DetInfoList[detId][0]=flag

    def CheckAliveAll(self):
        daq_list = self.InstInfo.PutContainerIdList()
        for daq in daq_list:
            daq_info = self.InstInfo.PutContainer(daq)
            alive_mod = 0
            mod_list = daq_info.PutContainerIdList()
            for mod in mod_list:
                mod_info = daq_info.PutContainer(mod)
                if mod_info.PutDetectorType()=="TRIGNET":
                    pass
                else:
                    alive_det = 0
                    det_list = mod_info.PutContainerIdList()
                    for det in det_list:
                        alive_det = alive_det + mod_info.PutContainer(det).PutStatus()
                    if alive_det == 0:
                        mod_info.SetStatus(0)
                    else:
                        mod_info.SetStatus(1)
                alive_mod = alive_mod + mod_info.PutStatus()
            
            if alive_mod ==0:
                daq_info.SetStatus(0)
            else:
                daq_info.SetStatus(1)
        
            
    # add or remove one Daq
    def RemoveDaq(self,daq_in):
        daq_info = self.InstInfo.PutContainer(daq_in)
        if daq_info==-1:
            print self.CommentHead+"Error : This DAQ id is not existed."
            return
        mod_list = daq_info.PutContainerIdList()
        for mod in mod_list:
            self.RemoveModule(daq_in,mod)

        self.InstInfo.RemoveContainer(daq_in)


    def AddNewDaq(self,daq_in):
        daq_info = self.InstInfo.PutContainer(daq_in)
        if daq_info!=-1:
            print self.CommentHead+"Error : This DAQ id is already existed."
            return
        new_daq = Carrier(daq_in,"Container for modules")
        self.InstInfo.AddContainer(new_daq)
        self.InstInfo.PutContainer(new_daq)

    # add or remove one module
    def RemoveModule(self,daq_in,mod_in):
        daq_info = self.InstInfo.PutContainer(daq_in)
        if daq_info==-1:
            print self.CommentHead+"Error : This DAQ id is not existed."
            return
        mod_info = daq_info.PutContainer(mod_in)
        if mod_info==-1:
            print self.CommentHead+"Error : This Module No. is not existed."
            return
        det_list = mod_info.PutContainerIdList()
        for det in det_list:
            self.RemoveDet(det)
        
        daq_info.RemoveContainer(mod_in)

    def AddNewModule(self,daq_in,mod_in):
        daq_info = self.InstInfo.PutContainer(daq_in)
        if daq_info==-1:
            print self.CommentHead+"Error : This DAQ id is not existed."
            return
        mod_info = daq_info.PutContainer(mod_in)
        if mod_info!=-1:
            print self.CommentHead+"Error : This module No. is already existed."
            return
        new_mod = Carrier(mod_in,"Container for detectors")
        daq_info.AddContainer(new_mod)
        daq_info.SortId()
        
    # add or remove one detId
    def RemoveDet(self,detId):
        if (detId<0)|(detId>self.MaxDetId):
            print self.CommentHead+"Error : invalid detector ID."
            return
        (flag,daq,mod) = self.DetInfoList[detId]
        if flag==0:
            print self.CommentHead+"Error : invalide detector ID."
            return
        self.InstInfo.PutContainer(daq).PutContainer(mod).RemoveContainer(detId)
        self.DetInfoList[detId] = (0,0,0)

    def AddNewDet(self,daq_in,mod_in,detId,numPixel):
        if detId<0:
            print self.CommentHead+"Error : invalid detector ID."
            return
        if (detId<=self.MaxDetId):
            if (self.DetInfoList[detId][0]==1):
                print self.CommentHead+"Error : This detId is already existed."
                return

        daq_info = self.InstInfo.PutContainer(daq_in)
        if daq_info==-1:
            print self.CommentHead+"Error : invalid Daq ID"
            return
        mod_info = daq_info.PutContainer(mod_in)
        if mod_info==-1:
            print self.CommentHead+"Error : invalid module No."
            return
        det_info = OneDetInfo(detId,numPixel)
        mod_info.AddContainer(det_info)
        mod_info.SortId()
        
        if detId>self.MaxDetId:
            org_DetInfoList = self.DetInfoList
            self.DetInfoList = []
            for i in range(self.MaxDetId+1):
                self.DetInfoList.append(org_DetInfoList[i])
            for i in range(self.MaxDetId+1,detId):
                self.DetInfoList.append( (0,-1,-1) )
            self.DetInfoList.append( (1,daq_in,mod_in) )
            self.MaxDetId = detId
        else:
            self.DetInfoList[detId] = (1,daq_in,mod_in)

    def _IsExistDaqModDetId(self,daq,mod,detId):
        daq_info = self.InstInfo.PutContainer(daq)
        if daq_info==-1:
            print self.CommentHead+"Error : This DAQ id is not existed."
            return False
        mod_info = daq_info.PutContainer(mod)
        if mod_info==-1:
            print self.CommentHead+"Error : This module No. is not existed."
            return False
        det_info = mod_info.PutContainer(detId)
        if det_info==-1:
            print self.CommentHead+"Error : This DetId is not existed in this module."
            return False
        
        return True

    def _ReturnOneDetInfo(self,detId):
        if (detId<0)|(detId>len(self.DetInfoList)):
            print self.CommentHead+"detId is invalid!!"
            return -1
        (flag,daq,mod) = self.DetInfoList[detId]
        if flag==0:
            print self.CommentHead+"detId is invalid!"
            return -1

        return self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(detId)

    def PutPsdParam(self,detId):
        det_info = self._ReturnOneDetInfo(detId)
        if det_info!=-1:
            return det_info.PutPsdInfo()
        else:
            return (-1,-1,-1,-1,-1)

    def SetPsdParam(self,detId,pa,pb,pc,lld1,lld2):
        det_info = self._ReturnOneDetInfo(detId)
        if det_info!=-1:
            det_info.SetPsdInfo(pa,pb,pc,lld1,lld2)

    def PutPsdPositionInfo(self,detId):
        det_info = self._ReturnOneDetInfo(detId)
        if det_info!=-1:
            return det_info.PutPsdBinInfo()
        else:
            return (-1,-1,-1)
        
    def SetPsdPositionInfo(self,detId,width,offset):
        det_info = self._ReturnOneDetInfo(detId)
        if det_info!=-1:
            (det_id,num,axis) = det_info.PutPixelInfo()
            det_info.SetPsdBinInfo(num,width,offset)

        
    def _MakePsdPositionInfo(self):
        Dict = {}
        Dict_out = {}
        daq_list = self.InstInfo.PutContainerIdList()
        for daqId in daq_list:
            mod_list = self.InstInfo.PutContainer(daqId).PutContainerIdList()
            for modNo in mod_list:
                det_list = self.InstInfo.PutContainer(daqId).PutContainer(modNo).PutContainerIdList()
                for detId in det_list:
                    det_info = self.InstInfo.PutContainer(daqId).PutContainer(modNo).PutContainer(detId)
                    if det_info.PutStatus()==1:
                        (id,num,axis) = det_info.PutPixelInfo()
                        (num2,deltax,offsetx) = det_info.PutPsdBinInfo()
                        bin_key = str(int(round(num)))+"-"+str(int(round(deltax)))+"-"+str(int(round(offsetx)))
                        if Dict.has_key(bin_key):
                            Dict[bin_key].append(detId)
                        else:
                            Dict[bin_key] = [detId]
        
        (sum_of_det,sum_of_pixel) = self.PutNumOfBoth()
        keylist = Dict.keys()
        keyOfAll = ""
        flag_a = 0
        for key_i in keylist:
            cont = Dict[key_i]
            if (len(cont)>(sum_of_det*0.5))&(flag_a==0):
                Dict_out[key_i] = "All"
                keyOfAll = key_i
                flag_a = 1
            else:
                cont_out = ""
                pre_c = cont[0]
                cont_out += str(pre_c)
                flag_cc = 0
                for cc in range(1,len(cont)):
                    if cont[cc] == (pre_c+1):
                        flag_cc=1
                        pre_c = cont[cc]
                        if cc==(len(cont)-1):
                            cont_out +="-"+str(cont[cc])
                    else:
                        if (flag_cc==1):
                            cont_out +="-"+str(pre_c)+","+str(cont[cc])
                        else:
                            cont_out +=","+str(cont[cc])
                        pre_c = cont[cc]
                        flag_cc=0
                        
                Dict_out[key_i] = cont_out

        psdBinInfoList = Carrier(0,"Container for psdBinInfo")
        psdBinSetId = 0
        psdBinInfo = Carrier(psdBinSetId,"Container for positionBin")
        # contents ="All" pattern
        if keyOfAll!="":
            cont = Dict_out[keyOfAll]
            k_list = keyOfAll.split("-")
            if (len(k_list)!=3):
                print self.CommentHead+" Key in PsdBinInfo is wrong: key=",keyOfAll
                return
            if self.Debug!=0:
                print "key = ",keyOfAll
                print "keys= ",k_list[0],k_list[1],k_list[2]
            positionBin = PsdBinPositionInfo(0,int(k_list[0]), int(k_list[1]), int(k_list[2]), cont)
            psdBinInfo.AddContainer(positionBin)
        # contents not equal "All" pattern
        i=1
        for key in Dict_out.keys():
            if key!=keyOfAll:
                cont = Dict_out[key]
                k_list = key.split("-")
                if (len(k_list)!=3):
                    print self.CommentHead+" Key in PsdBinInfo is wrong: key=",key
                    return
                if self.Debug!=0:
                    print "key = ",key
                    print "keys= ",k_list[0],k_list[1],k_list[2]
                positionBin = PsdBinPositionInfo(i,int(k_list[0]), int(k_list[1]), int(k_list[2]), cont)
                psdBinInfo.AddContainer(positionBin)
                i += 1
        
        psdBinInfoList.AddContainer(psdBinInfo)

        self.psdBinInfoList = psdBinInfoList
        
        return
        #return (Dict,Dict_out)
    
    def Show(self):
        self.CheckAliveAll()
        print "| |       |       |       |HeadOf | NumOf |        PSD parameter        |  Pulse Height | Calc Position|"
        print "| | DaqId | ModNo | detId |PixelId| Pixel |    A    |    B    |    C    |  LLD  | upper | width |offset|"
        print "|-|-------|-------|-------|-------|-------|---------|---------|---------|-------|-------|-------|------|"
        flags = [" ","*"]
        for daq in self.InstInfo.PutContainerIdList():
            status_daq = self.InstInfo.PutContainer(daq).PutStatus()
            mod_list = self.InstInfo.PutContainer(daq).PutContainerIdList()
            if len(mod_list)==0:
                st_list = "| | %3d(%s)| %s |" % (daq,flags[status_daq],"Empty")
                st_list += "       |"*3 + "         |"*3 + "       |"*2
                print st_list
            else:
                for mod in mod_list:
                    status_mod = self.InstInfo.PutContainer(daq).PutContainer(mod).PutStatus()
                    det_list = self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainerIdList()
                    if len(det_list)==0:
                        st_list  = "| | %3d(%s)| %3d(%s)| %s |" % (daq,flags[status_daq],mod,flags[status_mod],"Empty")
                        st_list += "       |"*2 + "         |"*3 + "       |"*2
                        print st_list
                    else:
                        info_mod = self.InstInfo.PutContainer(daq).PutContainer(mod)
                        for detId in det_list:
                    #alive = self.DetInfoList[detId][0]
                            alive = info_mod.PutContainer(detId).PutStatus()
                            info = info_mod.PutContainer(detId)
                            (id,num,axis) = info.PutPixelInfo()
                            hp = info.PutHeadPixelId()
                            st_list =  "| | %3d(%s)| %3d(%s)" % (daq,flags[status_daq],mod,flags[status_mod])
                            st_list += "| %3d(%s)| %5d | %5d |" % (detId,flags[alive],hp,num)
                            st_list += "%9.4f|%9.4f|%9.4f|%7.2f|%7.2f|" % (info.PutPsdInfo())
                            (num2,deltax,offsetx) = info.PutPsdBinInfo()
                            st_list += "  %4d | %4d |" % (deltax,offsetx)
                            if num!=num2:
                                st_list +="*"
                            print st_list

    def ShowModuleList(self):
        self.CheckAliveAll()
        print "| |       |       |Detect |Sum of |"
        print "| | DaqId | ModNo |  Type | DetId | DetId List [ alive(*) / killed( ) ]"
        print "|-|-------|-------|-------|-------|------------------------------------------------------- "
        for daq in self.InstInfo.PutContainerIdList():
            mod_list = self.InstInfo.PutContainer(daq).PutContainerIdList()
            if len(mod_list)==0:
                st_list = "|%1d|  %3d  | %s |" % (0,daq,"Empty")
                #st_list += "       |"*3 + "         |"*3 + "       |"*2
                print st_list
            else:
                for mod in mod_list:
                    mod_info = self.InstInfo.PutContainer(daq).PutContainer(mod)
                    mod_alive = mod_info.PutStatus()
                    det_list = mod_info.PutContainerIdList()
                    detType = mod_info.PutDetectorType()
                    if len(det_list)==0:
                        st_list  = "|%1d|  %3d  |  %3d  |%7s| %s |" % (0,daq,mod,detType,"Empty")
                        #st_list += "       |"*2 + "         |"*3 + "       |"*2
                        print st_list
                    else:
                        info_mod = self.InstInfo.PutContainer(daq).PutContainer(mod)
                        n_detId = len( det_list )
                        st_list = "|%1d|  %3d  |  %3d  |%7s|  %3d  |" % (mod_alive,daq,mod,detType,n_detId)
                        for detId in det_list:
                            alive = info_mod.PutContainer(detId).PutStatus()
                            if alive==0:
                                st_list += " %4d%s," % (detId," ")
                            else:
                                st_list += " %4d%s," % (detId,"*")
                        print st_list

    def ShowPsdPositionInfo(self):
        self._MakePsdPositionInfo()
        print '|SetId|index|numPixel| delta |offset| Regions'
        psdBinSetId_list = self.psdBinInfoList.PutContainerIdList()
        for psdBinSetId in psdBinSetId_list:
            psdBin_info = self.psdBinInfoList.PutContainer(psdBinSetId)
            cont = '| %3d |' % (psdBinSetId)
            posiBin_list = psdBin_info.PutContainerIdList()
            index = 0
            for posiBin in posiBin_list:
                pB_info = psdBin_info.PutContainer(posiBin)
                (numPixel,deltaX,offsetX,regions) = pB_info.PutPsdBinInfo()
                print cont+" %3d |  %5d | %5d | %4d | %s" % (index, numPixel, deltaX, offsetX, regions)
                index += 1

    def PutNumOfBoth(self):
        sum_of_det = 0
        sum_of_pixel = 0
        for i in range(len(self.DetInfoList)):
            (flag,daq,mod) = self.DetInfoList[i]
            if flag!=0:
                info = self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(i)
                if info.PutStatus()==1:
                    (dummy,num,axis) = info.PutPixelInfo()
                    sum_of_det += 1
                    sum_of_pixel += num

        return (sum_of_det,sum_of_pixel)

    def SaveToXml(self,filename,ver="1.5"):
        if os.path.exists(filename):
            print self.CommentHead+"The file with this name is existing.Old one is stored in "+filename+".org"
            comm="mv "+filename+" "+filename+".org"
            os.system(comm)
            
        self.CheckAliveAll()
        self._MakePsdPositionInfo()
        
        (sum_of_det,sum_of_pixel) = self.PutNumOfBoth()

        of = open(filename,'w')
        
        def tab(x):
            return '    '*x

        W=WiringFileDef()
        cont = '<?xml version="1.0" encoding="utf-8" ?>\n'
        cont += '<!DOCTYPE WiringInfo SYSTEM "WiringInfo.dtd" >\n'
        str_date = datetime.datetime.now().strftime("%y%m%d%H%M")
        cont += '<%s %s="%3s" %s="%s" %s="%s">\n' % (W.ROOT,W.ROOT_AT_INST,self.InstCode,W.ROOT_AT_VER, ver, W.ROOT_AT_DATE,str_date)
        #cont += '    <numOfDetId>%d</numOfDetId>\n' % (sum_of_det)
        #cont += '    <numOfPixelId>%d</numOfPixelId>\n' % (sum_of_pixel)
        cont += '    \n'
        #cont += '    <pixelInfo n="%d">\n' % ( len( self.InstInfo.PutContainerIdList() ) )

        num_of_alive_daq = 0
        daqIdList = self.InstInfo.PutContainerIdList()
        daq_i = 0
        c_daq = ''
        for daqId in daqIdList:
            daq_info = self.InstInfo.PutContainer(daqId)
            if (daq_info.PutStatus()==1)&(daq_info.NumOfCont>0):
                num_of_alive_daq += 1
                modNoList = daq_info.PutContainerIdList()
                #cont += tab(2)+'<daq i="%d" daqId="%d" n="%d">\n' % ( daq_i, daqId, len(modNoList) )
            
                modNo_i = 0
                c_m = ''
                for modNo in modNoList:
                    
                    mod_info = daq_info.PutContainer(modNo)
                    if (mod_info.PutStatus()==1):
                        if mod_info.PutDetectorType()=="TRIGNET":
                            c_m += tab(3)+'<%s i="%d"' % (W.ROOT_PIXELINFO_DAQ_MOD,modNo_i)
                            c_m += ' %s="%d"' % (W.ROOT_PIXELINFO_DAQ_MOD_AT_NO,modNo)
                            c_m += ' %s="%s"' % (W.ROOT_PIXELINFO_DAQ_MOD_AT_TYPE,mod_info.PutDetectorType())
                            c_m += ' %s="%s"/>\n' % (W.ROOT_PIXELINFO_DAQ_MOD_AT_TRIGINDEX,mod_info.PutTrigIndex())
                        else:
                            if mod_info.NumOfCont>0:
                                detIdList = mod_info.PutContainerIdList()
                                #cont += tab(3)+'<module i="%d" moduleNo="%d" n="%d">\n' % (modNo_i,modNo,len(detIdList))

                                detId_i = 0
                                c_d = ''
                                for detId in detIdList:
                                    info = mod_info.PutContainer(detId)
                                    if info.PutStatus()==1:
                                    #if self.DetInfoList[detId][0]==1:
                                        (dummy,num,axis) = info.PutPixelInfo()
                                        headpixel = info.PutHeadPixelId()
                                        c_d += tab(4)+'<%s i="%d"' % (W.ROOT_PIXELINFO_DAQ_MOD_DET,detId_i)
                                        c_d += ' %s="%d"' % (W.ROOT_PIXELINFO_DAQ_MOD_DET_AT_ID,detId)
                                        c_d += ' %s="%d"' % (W.ROOT_PIXELINFO_DAQ_MOD_DET_AT_AXIS,axis)
                                        c_d += ' %s="%d"' % (W.ROOT_PIXELINFO_DAQ_MOD_DET_AT_HEAD,headpixel)
                                        c_d += ' %s="%d" />\n' % (W.ROOT_PIXELINFO_DAQ_MOD_DET_AT_NUM,num)

                                        detId_i += 1
                                c_m += tab(3)+'<%s i="%d"' % (W.ROOT_PIXELINFO_DAQ_MOD,modNo_i)
                                c_m += ' %s="%d"' % (W.ROOT_PIXELINFO_DAQ_MOD_AT_NO,modNo)
                                c_m += ' %s="%s"' % (W.ROOT_PIXELINFO_DAQ_MOD_AT_TYPE,mod_info.PutDetectorType())
                                c_m += ' n="%d">\n' % (detId_i)
                                c_m += c_d
                                c_m += tab(3)+'</%s>\n' % (W.ROOT_PIXELINFO_DAQ_MOD)
                                #cont += tab(3)+'</module>\n'
                        modNo_i += 1
                    
                c_daq += tab(2)+'<%s i="%d"' % ( W.ROOT_PIXELINFO_DAQ,daq_i )
                c_daq += ' %s="%d"' % ( W.ROOT_PIXELINFO_DAQ_AT_ID, daqId)
                c_daq += ' n="%d">\n' % ( modNo_i )
                c_daq += c_m
                c_daq += tab(2)+'</%s>\n' % (W.ROOT_PIXELINFO_DAQ)
                #cont += tab(2)+'</daq>\n'
                daq_i += 1
        cont += '    <%s n="%d">\n' % (W.ROOT_PIXELINFO,daq_i)
        cont += c_daq
        cont += '    </%s>\n' % (W.ROOT_PIXELINFO)
        
        of.write(cont)

        cont = '\n'

        num_of_alive = 0
        cont2 = ''
        detId_i = 0
        for detId in range( len(self.DetInfoList) ):
            (flag,daq,mod) = self.DetInfoList[detId]
            if flag!=0:
                info = self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(detId)
                if info.PutStatus()==1:
            #if self.DetInfoList[detId][0]==1:
                    num_of_alive +=1
                #daq = self.DetInfoList[detId][1]
                #mod = self.DetInfoList[detId][2]
                #info = self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(detId)
                    cont2 += tab(2)+'<%s i="%d" %s="%d" >' % (W.ROOT_PSDPARAM_PARAM,detId_i,W.ROOT_PSDPARAM_PARAM_AT_ID,detId)
                    #cont2 += '%10.4f,%10.4f,%10.4f,%8.2f,%8.2f' % (info.PutPsdInfo())
                    cont2 += '%f,%f,%f,%8.2f,%8.2f' % (info.PutPsdInfo())
                    cont2 += '</%s>\n' % (W.ROOT_PSDPARAM_PARAM)
                    detId_i += 1

        cont += '    <%s n="%d">\n' % (W.ROOT_PSDPARAM,num_of_alive)
        cont += cont2
        cont += '    </%s>\n' % (W.ROOT_PSDPARAM)
            
        of.write(cont)

        cont = '\n'
        psdBinSetId_list = self.psdBinInfoList.PutContainerIdList()
        for psdBinSetId in psdBinSetId_list:
            psdBin_info = self.psdBinInfoList.PutContainer(psdBinSetId)
            cont += '    <%s %s="%d" n="%d">\n' % (W.ROOT_PSDBININFO,W.ROOT_PSDBININFO_AT_ID,psdBinSetId,psdBin_info.NumOfCont)
            posiBin_list = psdBin_info.PutContainerIdList()
            posiBin_i = 0
            for posiBin in posiBin_list:
                pB_info = psdBin_info.PutContainer(posiBin)
                cont += tab(2)+'<%s i="%d"' % (W.ROOT_PSDBININFO_BIN,posiBin_i)
                pB_params = pB_info.PutPsdBinInfo()
                cont += ' %s="%d"' % (W.ROOT_PSDBININFO_BIN_AT_NUM,pB_params[0])
                cont += ' %s="%d"' % (W.ROOT_PSDBININFO_BIN_AT_DELTA,pB_params[1])
                cont += ' %s="%d" >%s' % (W.ROOT_PSDBININFO_BIN_AT_OFFSET,pB_params[2],pB_params[3])
                cont += '</%s>\n' % (W.ROOT_PSDBININFO_BIN)
                posiBin_i +=1
            
            cont += '    </%s>\n' % (W.ROOT_PSDBININFO)
            
        cont +='\n'
        
        tofBin_list = self.tofBinInfo.PutContainerIdList()
        cont += '    <%s n="%d">\n' % ( W.ROOT_TOFBININFO,len(tofBin_list) )
        tofBin_i = 0
        for tofBin in tofBin_list:
            tofBin_info = self.tofBinInfo.PutContainer(tofBin)
            cont += tab(2)+'<%s i="%d"' % (W.ROOT_TOFBININFO_TOFBIN,tofBin_i)
            tmp = tofBin_info.PutTofBinInfo()
            cont += ' %s="%d"' % (W.ROOT_TOFBININFO_TOFBIN_AT_PAT,tmp[0])
            cont += ' %s="%d"' % (W.ROOT_TOFBININFO_TOFBIN_AT_OFFSET,tmp[1])
            if (tmp[3]!=-1):
                cont += ' %s="%d"' % (W.ROOT_TOFBININFO_TOFBIN_AT_MASK,tmp[3])
            cont += '> %s </%s>\n' % (tmp[2],W.ROOT_TOFBININFO_TOFBIN)
            tofBin_i += 1
            
        cont += '    </%s>\n' % (W.ROOT_TOFBININFO)
        
        cont += '\n'
        
        tofBinPtn_list = self.tofBinPattern.PutContainerIdList()
        cont += '    <%s n="%d">\n' % (W.ROOT_TOFBINPAT,len(tofBinPtn_list) )
        
        tofBinPtn_i = 0
        for BinPtn in tofBinPtn_list:
            BinPtn_info = self.tofBinPattern.PutContainer(BinPtn)
            cont += tab(2)+'<%s i="%d"' % (W.ROOT_TOFBINPAT_PAT,tofBinPtn_i)
            tmp = BinPtn_info.PutTofBinPattern()
            cont += ' %s="%d"' % ( W.ROOT_TOFBINPAT_PAT_AT_ID,tmp[0] )
            cont += ' %s="%d" >%s' % ( W.ROOT_TOFBINPAT_PAT_AT_TYPE,tmp[1],tmp[2] )
            cont += '</%s>\n' % (W.ROOT_TOFBINPAT_PAT)
            tofBinPtn_i += 1
            
        cont += '    </%s>\n'% (W.ROOT_TOFBINPAT)
        
        ##[inamura 141209]-->
        cont += '\n'
        tofMaskPtn_list = self.tofMaskPattern.PutContainerIdList()
        if len(tofMaskPtn_list)>0:
            cont += '    <%s n="%d">\n' % (W.ROOT_TOFMASKPAT,len(tofMaskPtn_list) )

            tofMaskPtn_i = 0
            for MaskPtn in tofMaskPtn_list:
                MaskPtn_info = self.tofMaskPattern.PutContainer(MaskPtn)
                cont += tab(2)+'<%s i="%d"' % (W.ROOT_TOFMASKPAT_PAT,tofMaskPtn_i)
                tmp = MaskPtn_info.PutTofMaskPattern()
                cont += ' %s="%d"' % ( W.ROOT_TOFMASKPAT_PAT_AT_ID,tmp[0] )
                cont += ' > %s </%s>\n' % (tmp[1],W.ROOT_TOFMASKPAT_PAT)
                tofMaskPtn_i += 1

            cont += '    </%s>\n'% (W.ROOT_TOFMASKPAT)
        ##<--[inamura 141209]
        
        of.write(cont)

        ##[inamura 110104]-->
        #cont  = '\n'
        #cont += '    <%s>' % (W.ROOT_TOFDOUBLEFRAME)
        #cont += "%f" % (self.tofDoubleFrameBoundary.PutTofDoubleFrameBoundary())
        #cont += '</%s>\n' % (W.ROOT_TOFDOUBLEFRAME)
        #of.write(cont)
        ##<--[ianmrua 110104]
        ##[inamura 120626]-->
        cout  = '\n'
        frameNo, boundary = self.frameInfo.PutFrameInfo()
        cout += '    <%s %s="%d" ' % (W.ROOT_FRAMEINFO,W.ROOT_FRAMEINFO_FRAMENO,frameNo)
        cout += '%s="%f" />\n' % (W.ROOT_FRAMEINFO_BOUNDARY,boundary)
        of.write(cout)
        ##<--[inamura 120626]
        
        cont  = '\n'            
        cont += '</%s>\n' % (W.ROOT)
        of.write(cont)

        of.close()

        comm="chmod go+w "+filename
        os.system(comm)


    def show_TofBinPattern(self):
        list=self.tofBinPattern.PutContainerIdList()
        for item in list:
            print self.CommentHead+"Index = ",item
            (patternId,type,Cont)=self.tofBinPattern.PutContainer(item).PutTofBinPattern()
            print self.CommentHead+"PatternID=",patternId," : type = ",type
            print self.CommentHead+"Cont = ",Cont
            print self.CommentHead+"-----------"


    def change_TofBinPattern(self,pID=-1,type=2,cont_in=[]):
        if not self.WFDef.TOF_BIN_PATTERN_FORM_DIC.has_key(type):
            print self.CommentHead+"This type (",type,") is invalid."
            return -1
        tform = self.WFDef.TOF_BIN_PATTERN_FORM_DIC[type]
        if len(cont_in)<tform[0]:
            print self.CommentHead+" Arguments (",cont_in,") is invalid for type=",type,"."
            return -2
        cont = tform[1] % tuple(cont_in)
        #print "@@@@ cont_in=",cont_in
        #print "@@@@ cont result = ",cont
        list=self.tofBinPattern.PutContainerIdList()
        if pID!=-1:
            for item in list:
                tbp = self.tofBinPattern.PutContainer(item)
                (patternId,dammy_type,dammy_cont)=tbp.PutTofBinPattern()
                if patternId==pID:
                    tbp.SetTofBinPattern(item,pID,type,cont)
                    if (self.Debug==1):
                        self.show_TofBinPattern()
                    return pID
        
        pId_list = []
        for item in list:
            tbp = self.tofBinPattern.PutContainer(item)
            (patternId,dammy_type,dammy_cont)=tbp.PutTofBinPattern()
            pId_list.append(patternId)
        
        tmpId = pId_list[0]
        while( tmpId in pId_list ):
            tmpId += 1
        
        list.sort()
        tbp = TofBinPattern((list[-1]+1),tmpId,type,cont)
        ret=self.tofBinPattern.AddContainer(tbp)
        if ret==-1:
            raise
        return tmpId
        

    def setTofBin_Tconst(self,pID=0,tof_start=-1,tof_end=-1,delta_tof=-1):
        list=self.tofBinPattern.PutContainerIdList()
        for item in list:
            tbp = self.tofBinPattern.PutContainer(item)
            (patternId,type,Cont)=tbp.PutTofBinPattern()
            if (patternId==pID)and(type==2):
                cont_list = Cont.split(",")
                if tof_start==-1:
                    tof_start = int(cont_list[0])
                if tof_end==-1:
                    tof_end = int(cont_list[1])
                if delta_tof==-1:
                    delta_tof = int(cont_list[2])
                cont = "%d, %d, %d " % (tof_start,tof_end,delta_tof)
                tbp.SetTofBinPattern(item,pID,2,cont)
                if (self.Debug==1):
                    self.show_TofBinPattern()
                break

    def show_TofBinInfo(self):
        tofBin_list = self.tofBinInfo.PutContainerIdList()
        tofBin_i = 0
        print "--------------------------"
        print "TofBInInfo"
        print " --------"
        for tofBin in tofBin_list:
            tofBin_info = self.tofBinInfo.PutContainer(tofBin)
            cont  = 'i="%d" ' % (tofBin_i)
            cont += 'patternId="%d" offsetBin="%d" contents=%s maskPtnId=%s' % ( tofBin_info.PutTofBinInfo() )
            print cont
            tofBin_i += 1
        return

    def setall_TofBinInfo(self,binPtnId=0,offset=0,maskId=-1): ##[inamura 141209]
        self.tofBinInfo = Carrier(0,"Container for tofBinInfo")
        tofBin = TofBinInfo(0, binPtnId, offset, "All", maskId)
        self.tofBinInfo.AddContainer(tofBin)


    def add_TofBinInfo(self,binPtnId,offset=0,cont="All",maskId=-1): ##[inamura 141209]
        tofBin_list = self.tofBinInfo.PutContainerIdList()
        tofBin_list.sort()
        
        self.tofBinInfo.AddContainer( TofBinInfo( tofBin_list[-1], binPtnId,offset, cont, maskId ))

    ##[inamura 110104]-->
    def set_TofDoubleFrameBoundary(self, tof=0.0):
        if (tof<0.0) or (tof>40000.0):
            message = "Invalid value for Boundary TOF of Double Frame."
            raise "InvalidValue",message
        
        try:
            self.tofDoubleFrameBoundary.SetTofDoubleFrameBoundary( 0,tof )
        except:
            self.tofDoubleFrameBoundary = TofDoubleFrameBoundary( 0,tof )
    ##<--[inamura 110104]

    ##[inamura 120626]-->
    def set_FrameInfo(self, frameNo=0, boundary=0.0 ):
        if (frameNo<0) or (frameNo>3):
            message = "Invalid value for frame No on FrameInfo."
            raise "InvalidValue",message

        if (boundary<0.0) or (boundary>40000.0):
            message = "Invalid value for boundary tof on FrameInfo.(boundary=%f)"%(boundary)
            raise "InvalidValue",message

        self.frameInfo.SetFrameInfo(0, frameNo, boundary )

        
    ##[inamura 140412]-->
    def set_LLD(self, LLD=0, HLD=10000, startDetId=0, endDetId=0 ):
        if startDetId==0 and endDetId==0:
            for det_id in range( len(self.DetInfoList) ):
                flag,daq,mod = self.DetInfoList[det_id]
                if flag==0:
                    #print "det_id(%d) is not set"%(det_id)
                    pass
                else:
                    info = self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(det_id)
                    paramA = info.PA
                    paramB = info.PB
                    paramC = info.PC
                    info.SetPsdInfo( paramA, paramB, paramC, LLD, HLD )
        elif startDetId==endDetId or endDetId==0:
            if startDetId>=len(self.DetInfoList):
                raise "UserWarning", "Given DetId is invalid(%d)"%(startDetId)
            flag,daq,mod = self.DetInfoList[startDetId]
            if flag==0:
                print "det_id(%d) is not set"%(det_id)
            else:
                info = self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(startDetId)
                paramA = info.PA
                paramB = info.PB
                paramC = info.PC
                info.SetPsdInfo( paramA, paramB, paramC, LLD, HLD )
        elif endDetId>startDetId:
            for det_id in range(startDetId, (endDetId+1)):
                if det_id>=len(self.DetInfoList):
                    raise "UserWarning", "Given DetId is invalid (%d)"%(det_id)
                flag,daq,mod = self.DetInfoList[det_id]
                if flag==0:
                    print "det_id(%d) is not set"%(det_id)
                else:
                    info = self.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(det_id)
                    paramA = info.PA
                    paramB = info.PB
                    paramC = info.PC
                    info.SetPsdInfo( paramA, paramB, paramC, LLD, HLD )
    ##<--[inamura 140412]

    ##[inamura 141209]-->
    def set_TofMask(self, maskPtnId=0, conts="" ):
        id_list = self.tofMaskPattern.PutContainerIdList()
        tmp_tofmask = None
        for id in id_list:
            if tofMaskPtn_list.PutContainer(id).maskPtnId == maskPtnid:
                self.tofMaskPattern.RemoveContainer(id)
                tmp_tofmask = TofMaskPattern( id, maskPtnId, conts )
        
        if tmp_tofmask==None:
            new_id = 0
            if len(id_list)!=0:
                id_list.sort()
                new_id = id_list[-1]
            tmp_tofmask = TofMaskPattern( new_id, maskPtnId, conts )
        
        if tmp_tofmask!=None:
            self.tofMaskPattern.AddContainer( tmp_tofmask )
        else:
            print "Failed to set TofMask"
        return
    ##<--[inamura 141209]
