import xml.etree.ElementTree as ElementTree
import decimal
#---------------------------------------------------------------------------------

from xml.dom import minidom

def prettify(elem):
    rough_string = ElementTree.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    text = reparsed.toprettyxml(indent="  ")

    lindex=0
    rindex=-1
    while 1:
        tmp_r  = text[lindex:-1].find(">")
        rindex = tmp_r+lindex
        tmp_l  = text[rindex:-1].find("<")
        lindex = tmp_l+rindex
        if len(text[rindex+1:lindex].strip())!=0:
            org_text_length=len(text)
            text = text[:rindex+1]+text[rindex+1:lindex].strip()+text[lindex:]
            new_text_length=len(text)
            rindex-= (org_text_length-new_text_length)
            lindex-= (org_text_length-new_text_length)
        if tmp_r==-1 or tmp_l ==-1:
            break

    texts = text.split("\n")
    texts = [text for text in texts if len(text.strip())!=0]
    text="\n".join(texts)

    return text
#---------------------------------------------------------------------------------
def operationParams(root,index,begin,end,operation,val):
    val=str(val)
    pi = root.find("positionInfo")
    i=0
    for po in pi.findall("position"):
        if begin<=i<=end:
            params=po.text.split(",")
            if len(params)>index:
                if operation=="+":
                    params[index]=str(decimal.Decimal(params[index])+decimal.Decimal(val))
                if operation=="-":
                    params[index]=str(decimal.Decimal(params[index])-decimal.Decimal(val))
                if operation=="/":
                    params[index]=str(decimal.Decimal(params[index])/decimal.Decimal(val))
                if operation=="*":
                    params[index]=str(decimal.Decimal(params[index])*decimal.Decimal(val))
            po.text=",".join(params)
        i+=1
    return root
#---------------------------------------------------------------------------------

filename   ="DetectorPosiOldManyo.xml"
newfilename="DetectorPosiOldManyo.xml.1"
tree=ElementTree.parse(filename)
root=tree.getroot()

index = 1
begin = 0
end   = 223

root=operationParams(root,index,begin,end,"-","0.4")

text=prettify(root)
#print text
files=open(newfilename,"w")
files.write(text)
files.close()
