# -*- coding: ISO-8859-1 -*-
""" capellaScript -- 24.02.2006 Andreas Herzog
>>> Freiheit für Vorzeichen

    Mit diesem Skript kann man Tonarten in Capella frei gestalten.|
    |
    
    |
    Version 1.01   |
    
    |
    
        |

<<<

# Version 1.0:  Ursprungsversion
          1.01  15.03.2008 Berücksichtigung von 3-fach Punktierung (Vlg)


"""

import xml.dom
import string


from xml.dom.minidom import NodeList

Alterationen = []
KeyPos = [-0.5,-1.0,-1.5,-2.0,-2.5,-3.0,-3.5]
ClefPos = [0,0.5,-0.5,1.0]
voiceNoteContent = []
voiceTimeContent = []
voiceBarlineContent = []


# doc = [] # parentNode von score

class settings:
    def __init__(self):
        self.CAlteration = 0.0
        self.DAlteration = 0.0
        self.EAlteration = 0.0
        self.FAlteration = 0.0
        self.GAlteration = 0.0
        self.AAlteration = 0.0
        self.HAlteration = 0.0

        self.CKeyPos = 0
        self.DKeyPos = 0
        self.EKeyPos = 0
        self.FKeyPos = 0
        self.GKeyPos = 0
        self.AKeyPos = 0
        self.HKeyPos = 0

        self.CKeyOctave = 0
        self.DKeyOctave = 0
        self.EKeyOctave = 0
        self.FKeyOctave = 0
        self.GKeyOctave = 0
        self.AKeyOctave = 0
        self.HKeyOctave = 0    	
        
        self.ClefChosen = 0
    
defaults = settings()
dlgSet = settings()

options = ScriptOptions() 
opt = options.get()


def getOptions():
    global CAlteration, DAlteration, EAlteration, FAlteration, GAlteration, AAlteration, HAlteration
    global CKeyPos, DKeyPos, EKeyPos, FKeyPos, GKeyPos, AKeyPos, HKeyPos
    global CKeyOctave, DKeyOctave, EKeyOctave, FKeyOctave, GKeyOctave, AKeyOctave, HKeyOctave
    global ClefChosen, Alterationen
    
    CAlteration = eval(opt.get('CAlteration', str(CAlteration)))
    DAlteration = eval(opt.get('DAlteration', str(DAlteration)))
    EAlteration = eval(opt.get('EAlteration', str(EAlteration)))
    FAlteration = eval(opt.get('FAlteration', str(FAlteration)))
    GAlteration = eval(opt.get('GAlteration', str(GAlteration)))
    AAlteration = eval(opt.get('AAlteration', str(AAlteration)))
    HAlteration = eval(opt.get('HAlteration', str(HAlteration)))
    
    CKeyPos = eval(opt.get('CKeyPos', str(CKeyPos)))
    DKeyPos = eval(opt.get('DKeyPos', str(DKeyPos)))
    EKeyPos = eval(opt.get('EKeyPos', str(EKeyPos)))
    FKeyPos = eval(opt.get('FKeyPos', str(FKeyPos)))
    GKeyPos = eval(opt.get('GKeyPos', str(GKeyPos)))
    AKeyPos = eval(opt.get('AKeyPos', str(AKeyPos)))
    HKeyPos = eval(opt.get('HKeyPos', str(HKeyPos)))
    
    CKeyOctave = eval(opt.get('CKeyOctave', str(CKeyOctave)))
    DKeyOctave = eval(opt.get('DKeyOctave', str(DKeyOctave)))
    EKeyOctave = eval(opt.get('EKeyOctave', str(EKeyOctave)))
    FKeyOctave = eval(opt.get('FKeyOctave', str(FKeyOctave)))
    GKeyOctave = eval(opt.get('GKeyOctave', str(GKeyOctave)))
    AKeyOctave = eval(opt.get('AKeyOctave', str(AKeyOctave)))
    HKeyOctave = eval(opt.get('HKeyOctave', str(HKeyOctave)))
    
    ClefChosen = eval(opt.get('ClefChosen', str(ClefChosen)))
        
    
    Alterationen = [[CAlteration,CKeyPos,CKeyOctave],[DAlteration,DKeyPos,DKeyOctave],[EAlteration,EKeyPos,EKeyOctave],[FAlteration,FKeyPos,FKeyOctave],[GAlteration,GKeyPos,GKeyOctave],[AAlteration,AKeyPos,AKeyOctave],[HAlteration,HKeyPos,HKeyOctave]]

def setOptions():
    global dlgSet


    opt.update(dict(CAlteration = str(CAlteration),
                    DAlteration = str(DAlteration),
                    EAlteration = str(EAlteration),
                    FAlteration = str(FAlteration),
                    GAlteration = str(GAlteration),
                    AAlteration = str(AAlteration),
                    HAlteration = str(HAlteration),
                    CKeyPos = str(CKeyPos),
                    DKeyPos = str(DKeyPos),
                    EKeyPos = str(EKeyPos),
                    FKeyPos = str(FKeyPos),
                    GKeyPos = str(GKeyPos),
                    AKeyPos = str(AKeyPos),
                    HKeyPos = str(HKeyPos),
                    CKeyOctave = str(CKeyOctave),
                    DKeyOctave = str(DKeyOctave),
                    EKeyOctave = str(EKeyOctave),
                    FKeyOctave = str(FKeyOctave),
                    GKeyOctave = str(GKeyOctave),
                    AKeyOctave = str(AKeyOctave),
                    HKeyOctave = str(HKeyOctave),
                    ClefChosen = str(ClefChosen)))
    options.set(opt)                    

def latin1_e(u):
    return u.encode('Latin-1')
def latin1_d(u):
    return u.decode('Latin-1')

def Test(text):
    messageBox('Test',str(text))
    
def addElementNode(el,tagName):
    # add new Node to el if Node "tagName" does not exist
    # otherwise return the existing Node
    global doc
    childs = el.childNodes
    for n in range(childs.length):
        if childs[n].nodeType ==childs[n].ELEMENT_NODE and childs[n].tagName == tagName:
            return childs[n]
    newChild = doc.createElement(tagName)
    el.appendChild(newChild)
    return newChild
    

def addNewElementNode(el,tagName):
    # add new Node with tagName "tagName" to el 
    global doc
    newChild = doc.createElement(tagName)
    el.appendChild(newChild)
    return newChild

def getDialogValues1():
    
    global Aktion
    
    AktionenRadio = Radio(['Tonleiter für diese Zeile anwenden (Vorzeichen unterdrücken/anzeigen)','Tonleiter durchsetzen (Setzen der Vorzeichen)','Vorzeichen setzen', 'Tonleiter verändern'], value=0, width=16)
    
    hbox01 = HBox([AktionenRadio], padding = 6)
    
    
    vbox00= VBox([hbox01], padding = 8)
    
    dlg = Dialog('Bitte wählen: ', vbox00)

    
    if dlg.run():
        Aktion = AktionenRadio.value()
        
        return True
  
    else:
        return False
    
def getDialogValues2():
    
    global CAlteration, DAlteration, EAlteration, FAlteration, GAlteration, AAlteration, HAlteration
    global CKeyPos, DKeyPos, EKeyPos, FKeyPos, GKeyPos, AKeyPos, HKeyPos
    global CKeyOctave, DKeyOctave, EKeyOctave, FKeyOctave, GKeyOctave, AKeyOctave, HKeyOctave
    global ClefChosen, Alterationen

    
    equalLab = Label('=', width = 0)
    
    NurLoeschenCheck = CheckBox('Nur Elemente dieses Skripts löschen!', value=0)
    
    CAlterationBox = ComboBox(['C erniedrigt','C ohne Alteration','C erhöht'], value=CAlteration+1, width=16)
    DAlterationBox = ComboBox(['D erniedrigt','D ohne Alteration','D erhöht'], value=DAlteration+1, width=16)
    EAlterationBox = ComboBox(['E erniedrigt','E ohne Alteration','E erhöht'], value=EAlteration+1, width=16)
    FAlterationBox = ComboBox(['F erniedrigt','F ohne Alteration','F erhöht'], value=FAlteration+1, width=16)
    GAlterationBox = ComboBox(['G erniedrigt','G ohne Alteration','G erhöht'], value=GAlteration+1, width=16)
    AAlterationBox = ComboBox(['A erniedrigt','A ohne Alteration','A erhöht'], value=AAlteration+1, width=16)
    HAlterationBox = ComboBox(['H erniedrigt','H ohne Alteration','H erhöht'], value=HAlteration+1, width=16)
    
    CKeyPosBox = ComboBox(['--','1.','2.','3.','4.','5.','6.','7.'], value=CKeyPos, width=6)
    DKeyPosBox = ComboBox(['--','1.','2.','3.','4.','5.','6.','7.'], value=DKeyPos, width=6)
    EKeyPosBox = ComboBox(['--','1.','2.','3.','4.','5.','6.','7.'], value=EKeyPos, width=6)
    FKeyPosBox = ComboBox(['--','1.','2.','3.','4.','5.','6.','7.'], value=FKeyPos, width=6)
    GKeyPosBox = ComboBox(['--','1.','2.','3.','4.','5.','6.','7.'], value=GKeyPos, width=6)
    AKeyPosBox = ComboBox(['--','1.','2.','3.','4.','5.','6.','7.'], value=AKeyPos, width=6)
    HKeyPosBox = ComboBox(['--','1.','2.','3.','4.','5.','6.','7.'], value=HKeyPos, width=6)

    CKeyOctaveBox = ComboBox(['tief','hoch'], value=CKeyOctave, width=6)
    DKeyOctaveBox = ComboBox(['tief','hoch'], value=DKeyOctave, width=6)
    EKeyOctaveBox = ComboBox(['tief','hoch'], value=EKeyOctave, width=6)
    FKeyOctaveBox = ComboBox(['tief','hoch'], value=FKeyOctave, width=6)
    GKeyOctaveBox = ComboBox(['tief','hoch'], value=GKeyOctave, width=6)
    AKeyOctaveBox = ComboBox(['tief','hoch'], value=AKeyOctave, width=6)
    HKeyOctaveBox = ComboBox(['tief','hoch'], value=HKeyOctave, width=6)
    
    ClefBox = ComboBox(['Violinschlüssel','Altschlüssel','Tenorschlüssel','Bassschlüssel'], value=ClefChosen, width=18)

    
    hbox01 = HBox([CAlterationBox, CKeyPosBox,CKeyOctaveBox], padding = 6)
    hbox02 = HBox([DAlterationBox, DKeyPosBox,DKeyOctaveBox], padding = 6)
    hbox03 = HBox([EAlterationBox, EKeyPosBox,EKeyOctaveBox], padding = 6)
    hbox04 = HBox([FAlterationBox, FKeyPosBox,FKeyOctaveBox], padding = 6)
    hbox05 = HBox([GAlterationBox, GKeyPosBox,GKeyOctaveBox], padding = 6)
    hbox06 = HBox([AAlterationBox, AKeyPosBox,AKeyOctaveBox], padding = 6)
    hbox07 = HBox([HAlterationBox, HKeyPosBox,HKeyOctaveBox], padding = 6)
    
    
    vbox00= VBox([hbox01, hbox02, hbox03, hbox04, hbox05, hbox06, hbox07, ClefBox], padding = 8)
    everythingFine = False
    
    while everythingFine == False:   
        dlg = Dialog('Bitte wählen: ', vbox00)
        
        if dlg.run():
            CAlteration = CAlterationBox.value()-1
            DAlteration = DAlterationBox.value()-1
            EAlteration = EAlterationBox.value()-1
            FAlteration = FAlterationBox.value()-1
            GAlteration = GAlterationBox.value()-1
            AAlteration = AAlterationBox.value()-1
            HAlteration = HAlterationBox.value()-1
            
            CKeyPos = CKeyPosBox.value()
            DKeyPos = DKeyPosBox.value()
            EKeyPos = EKeyPosBox.value()
            FKeyPos = FKeyPosBox.value()
            GKeyPos = GKeyPosBox.value()
            AKeyPos = AKeyPosBox.value()
            HKeyPos = HKeyPosBox.value()
            
            if CAlteration == 0:
                CKeyPos =0
            if DAlteration == 0:
                DKeyPos =0
            if EAlteration == 0:
                EKeyPos =0
            if FAlteration == 0:
                FKeyPos =0
            if GAlteration == 0:
                GKeyPos =0
            if AAlteration == 0:
                AKeyPos =0
            if HAlteration == 0:
                HKeyPos =0    		    		    		    		    		
            
            CKeyOctave = CKeyOctaveBox.value()
            DKeyOctave = DKeyOctaveBox.value()
            EKeyOctave = EKeyOctaveBox.value()
            FKeyOctave = FKeyOctaveBox.value()
            GKeyOctave = GKeyOctaveBox.value()
            AKeyOctave = AKeyOctaveBox.value()
            HKeyOctave = HKeyOctaveBox.value()
            
            ClefChosen = ClefBox.value()
            
            Alterationen = [[CAlteration,CKeyPos,CKeyOctave],[DAlteration,DKeyPos,DKeyOctave],[EAlteration,EKeyPos,EKeyOctave],[FAlteration,FKeyPos,FKeyOctave],[GAlteration,GKeyPos,GKeyOctave],[AAlteration,AKeyPos,AKeyOctave],[HAlteration,HKeyPos,HKeyOctave]]
            
            everythingFine = True
            
            i = 0
            while i < len(Alterationen):
                if Alterationen[i][0] <> 0 and Alterationen[i][1] == 0:
                    everythingFine = False
                    lyricOverwrite = messageBox('FEHLER','Bitte weisen Sie jedem Vorzeichen eine Position zu!', img=3)
                i+=1	
            if everythingFine == True:
                return True
        else:
            return False

def clearNote(chord):
                                            
    for drawObjects in chord.getElementsByTagName('drawObjects'):					# Alle drawObj mit tag == GraficalTag löschen
          for drawObj in drawObjects.childNodes:
             if drawObj.nodeType == drawObj.ELEMENT_NODE and drawObj.tagName == 'drawObj':
                for basic in drawObj.getElementsByTagName('basic'):
                     if basic.hasAttribute('tag') and basic.getAttribute('tag') == '56294-1500':
                        drawObjects.removeChild(drawObj)
              
    for drawObjects in chord.getElementsByTagName('drawObjects'):					# Alle drawObj mit tag == GraficalTag löschen
         for drawObj in drawObjects.childNodes:
             if drawObj.nodeType == drawObj.ELEMENT_NODE and drawObj.tagName == 'drawObj':
                for basic in drawObj.getElementsByTagName('basic'):
                     if basic.hasAttribute('tag') and basic.getAttribute('tag')[0:8] == '56294-15':
                        drawObjects.removeChild(drawObj)     	
                                       
         if drawObjects.getElementsByTagName('drawObj').length == 0:					# Wenn drawObjects keine Elemente mehr enthält, dann löschen  
             drawObjects.parentNode.removeChild(drawObjects)

def setKey(obj, lastObject):
    
    keyRest = addNewElementNode(obj.parentNode,'rest')
    keyRestDuration = addNewElementNode(keyRest,'duration')
    keyRestDuration.setAttribute('noDuration','true')
    keyRestDuration.setAttribute('base','1/4')
    keyRest.parentNode.appendChild(keyRest)
    
    
    if not lastObject:
        obj.parentNode.insertBefore(keyRest,obj)
    
    displayObj = addNewElementNode(keyRest,'display')
    displayObj.setAttribute('invisible','true')
    
    
    oneChanged = False 
    
    i =0
    while i < 7: 
        if Alterationen[i][0] <> 0:
            oneChanged = True
        i+=1
        
    if oneChanged:	
        drawObjects = addElementNode(keyRest,'drawObjects')				
        drawObj = addNewElementNode(drawObjects, 'drawObj')
        
        group = addNewElementNode(drawObj,'group')
        basicGroup = addNewElementNode(drawObj,'basic')
        basicGroup.setAttribute('tag','56294-1500')
    

    #Test(ClefPos[ClefChosen])
    
    i =0
    while i < 7: 
        if Alterationen[i][0] <> 0 and Alterationen[i][1] <> 0:
            if Alterationen[i][0] == -1:
                textCapSymbol = 'Q'
            if Alterationen[i][0] == 1:
                textCapSymbol = 'S'				
            KeyPosY = KeyPos[i] + 3.5 * (1-Alterationen[i][2]) + ClefPos[ClefChosen]
            if Alterationen[i][2] == 1 and KeyPosY > 0:
                KeyPosY-=3.5
            if Alterationen[i][2] == 0 and KeyPosY < 0:
                KeyPosY+=3.5
                
            if KeyPosY < (-2.5):
                KeyPosY+= 3.5
                
            if KeyPosY > 2.5:
                KeyPosY-= 3.5
            newCapText(group, str(-1+Alterationen[i][1]),str(KeyPosY),'18',textCapSymbol,'11')
        i+=1

    
        
def newCapText(drawObjAncer,  width, height, size, contents, IndexTag):
    global FingerGruppierung, FingerFontGroesse, BogenStaerke, StrichAbstand
    
    drawObj = addNewElementNode(drawObjAncer,'drawObj')
        
    text = addNewElementNode(drawObj,'text')	
        
    text.setAttribute('x',width)
    text.setAttribute('y',height)

    content = addNewElementNode(text,'content')
    textNode = doc.createTextNode(latin1_d(contents))
    content.appendChild(textNode)
    text.setAttribute('align','center')
    GraficalTag = '56294-15'+IndexTag
    basic = addElementNode(drawObj,'basic')							
    basic.setAttribute('tag',GraficalTag)    

    font = addNewElementNode(text,'font')
    font.setAttribute('face','capella3')
    font.setAttribute('color','')
    font.setAttribute('height',str(size))
    font.setAttribute('charSet','2')
    font.setAttribute('pitchAndFamily','2')	 

    return text					

def getTime(chord):			
    objList = getElementObjects(chord.parentNode.parentNode.getElementsByTagName('noteObjects')[0].childNodes)
    time = 0
    i = 0
    while chord <> objList[i]:
        objects = objList[i]
        addTime = getLength(objects)
        time +=  addTime
        i += 1
    return time

def getIrregular(object):
    irregular = float(1)
    count = 0
    tripartite = 'false'
    for duration in object.getElementsByTagName('duration'):
        for tuplet in duration.getElementsByTagName('tuplet'):
            count = string.atoi(tuplet.getAttribute('count'))
            tripartite = tuplet.getAttribute('tripartite')
                
    if count == 2 and tripartite == 'true':
        irregular = float(3) /float (4)
    elif count == 3:
        irregular =  float(2) /float (3)
    elif count == 5:
        irregular = float(4) /float (5)
    elif count == 7:
        irregular = float(4) /float (7)
    else:
        irregular = 1

    return irregular
    

def getLength(object):
    length = 0
    if object.tagName in ['chord','rest']:
        for duration in object.getElementsByTagName('duration'):
            if duration.getAttribute('noDuration') <> 'true':
                if not duration.getAttribute('base') in ['1']:
                    length = 1 / string.atof(duration.getAttribute('base')[2:])

                else:
                    length = 1
                dotsMult = 1
                if duration.getAttribute('dots') == '1':
                    dotsMult = 1.5
                elif duration.getAttribute('dots') == '2':
                    dotsMult = 1.75
                elif duration.getAttribute('dots') == '3':
                    dotsMult = 1.875
                length = length * dotsMult
                length = length * getIrregular(object)

    return length
    
            
def getCursor():
    sel = curSelection()
    result = None
    if sel == 0:
        messageBox('Fehler', 'keine aktive Partitur')
        return result
    result = sel[0]
    return result

def getElementObjects(objList):  # returns a List
    newList = NodeList()
    for n in range(objList.length):
        if objList[n].nodeType == objList[n].ELEMENT_NODE:
            newList.append(objList[n])
    return newList

def changeNote1(note, voiceNoteContent):
    
    noteTime = voiceNoteContent[len(voiceNoteContent)-1][0]
    noteMeasure = voiceNoteContent[len(voiceNoteContent)-1][2]
    notelastBegin = voiceNoteContent[len(voiceNoteContent)-1][3]
    notelastPosition = voiceNoteContent[len(voiceNoteContent)-1][4]
    notelastPositionInMeasure = voiceNoteContent[len(voiceNoteContent)-1][5]
    
    #Test(notelastPosition)
    
    notesBefore = []
    
    #Test(notelastMeasure)

    
    i = 0
    while i < len(voiceNoteContent):
        if voiceNoteContent[i][1] <> note:
            #Test((notelastPosition - voiceNoteContent[i][4]) / noteMeasure)
            
            if (voiceNoteContent[i][0] >= notelastBegin) and ((((notelastPosition - voiceNoteContent[i][4]) - noteMeasure) < 1) or noteMeasure == 0.0) and ((notelastPosition - voiceNoteContent[i][4]) <= notelastPositionInMeasure):
                notesBefore+=[voiceNoteContent[i][1]]

        i+=1
    
    #Test([notesBefore])	
    
    
    
    
    for head in note.getElementsByTagName('head'):

        forceAlter = False
        notePitch = head.getAttribute('pitch')[0]
        noteIndex = ['C','D','E','F','G','A','B'].index(notePitch)

        lastHead = 0
        i=0
        while i < len(notesBefore):
            #Test('Hallo')
            for headCompare in notesBefore[i].getElementsByTagName('head'):
                
                if headCompare.getAttribute('pitch')[0] == notePitch:
                    
                    alterCompare = ''
                    displayCompare = ''
                    for alter in headCompare.getElementsByTagName('alter'):
                        alterCompare = alter.getAttribute('step')
                        displayCompare = alter.getAttribute('display')
                    lastHead =1 
                    break
                    
                
            i+= 1
        #Test(lastHead)

        
        for alter in head.getElementsByTagName('alter'):
            noteAlter = alter.getAttribute('step')
            
            if str(noteAlter) == str(Alterationen[noteIndex][0]):
                alter.setAttribute('display','suppress')
            elif noteAlter == '':
                forceAlter = True
            else:
                alter.setAttribute('display','')	

        if len(head.getElementsByTagName('alter')) == 0:
            forceAlter = True
        if forceAlter == True:
            if (str(Alterationen[noteIndex][0]) == '1' or  str(Alterationen[noteIndex][0]) == '-1'):

                alter = addNewElementNode(head,'alter')
                alter.setAttribute('display','force')
        
        for alter in head.getElementsByTagName('alter'):
            if (lastHead == 1) and (alter.getAttribute('step') <> alterCompare):
                alter.setAttribute('display','force')
                    

def changeNote2(note):
    

    
    for head in note.getElementsByTagName('head'):
        notePitch = head.getAttribute('pitch')[0]
        noteIndex = ['C','D','E','F','G','A','B'].index(notePitch)
        
        alter = addNewElementNode(head,'alter')
        alter.setAttribute('step',str(Alterationen[noteIndex][0]))
                
                        
def timeSignValue(time):
    if time == 'infinite':
        timeValue = 0
    else:
        timeValue = (string.atof(time[:time.index('/')]) / string.atof(time[time.index('/')+1:]))
    
    return timeValue

def changeDoc(score):
    global CAlteration, DAlteration, EAlteration, FAlteration, GAlteration, AAlteration, HAlteration
    global CKeyPos, DKeyPos, EKeyPos, FKeyPos, GKeyPos, AKeyPos, HKeyPos
    global CKeyOctave, DKeyOctave, EKeyOctave, FKeyOctave, GKeyOctave, AKeyOctave, HKeyOctave	
    global ClefChosen, Aktion, voiceTimeContent, voiceNoteContent, voiceBarlineContent
    
    ClefChosen = 0

    CAlteration = 0 
    DAlteration = 0 
    EAlteration = 0
    FAlteration = 0 
    GAlteration = 0 
    AAlteration = 0
    HAlteration = 0
    
    CKeyPos = 0
    DKeyPos = 0 
    EKeyPos = 0
    FKeyPos = 0 
    GKeyPos = 0
    AKeyPos = 0 
    HKeyPos = 0
    
    CKeyOctave = 0
    DKeyOctave = 0 
    EKeyOctave = 0
    FKeyOctave = 0 
    GKeyOctave = 0
    AKeyOctave = 0 
    HKeyOctave = 0

    
    getOptions()

    sel = getCursor()
    if sel == None:
        #
        return
    else:
        system = score.getElementsByTagName('system')[sel[0]]
        staff = system.getElementsByTagName('staff')[sel[1]]
        voice = staff.getElementsByTagName('voice')[sel[2]]
        noteObject = voice.getElementsByTagName('noteObjects')[0]
        objList = getElementObjects(noteObject.childNodes)
        if objList.length < sel[3]:
            return
        elif objList.length == sel[3]:
            obj = objList[len(objList)-1]
            lastObject = True
        else:
            obj = objList[sel[3]]
            lastObject = False

        
        Aktion = 3
        Abgebrochen = False
        
        while Aktion == 3 and Abgebrochen == False:
            if getDialogValues1():
                
                if Aktion == 0:
                    
                    for timeSign in voice.getElementsByTagName('timeSign'):
                        voiceTimeContent+=[[getTime(timeSign), timeSignValue(timeSign.getAttribute('time'))]]
                    
                    for barLine in voice.getElementsByTagName('barline'):
                        voiceBarlineContent+=[[getTime(barLine)]]
                                            
                    for chord in voice.getElementsByTagName('chord'):
                        
                        chordTime = getTime(chord)
                        chordMeasure = 0.0
                        lastBarline = 0.0
                        lastMeasure = 0.0
                        measureNr = 0
                        
                        i = 0 
                        while i < len(voiceTimeContent):
                            if chordTime >= voiceTimeContent[i][0]:
                                chordMeasure = voiceTimeContent[i][1]
                                lastMeasure = voiceTimeContent[i][0]
                            else:
                                break
                            i+=1
                        
                        j = 0 
                        while j < len(voiceBarlineContent):
                            if chordTime >= voiceBarlineContent[j][0]:
                                lastBarline = voiceBarlineContent[j][0]
                            else:
                                break
                            j+=1	
                        
                        if lastBarline >= lastMeasure:
                            lastBegin = lastBarline
                        else:
                            lastBegin = lastMeasure
                        
                        chordPositionWithoutAuftakt = chordTime - lastBegin
                        
                        try: 
                            measureNr = int(chordPositionWithoutAuftakt / chordMeasure)
                        except:
                            pass
                        chordInMeasure = chordPositionWithoutAuftakt - measureNr * chordMeasure
    
                        voiceNoteContent+=[[chordTime, chord, chordMeasure, lastBegin, chordPositionWithoutAuftakt, chordInMeasure]]
                        
                        changeNote1(chord, voiceNoteContent) 
                if Aktion == 1:
                    
                    for chord in voice.getElementsByTagName('chord'):				
                        changeNote2(chord) 				
                if Aktion == 2:	
    
                    setKey(obj, lastObject)
                if Aktion == 3:
                    if getDialogValues2():
                        setOptions()
            else:
                Abgebrochen = True

        #Test(voiceNoteContent)

# Hauptprogramm:

from caplib.capDOM import ScoreChange
import tempfile

class ScoreChange(ScoreChange):
    
    def changeScore(self, score):
       global doc
       doc = score.parentNode  
       changeDoc(score)
        
        

if activeScore():
    
    activeScore().registerUndo("Vorzeichenveränderung")
    tempInput = tempfile.mktemp('.capx')
    tempOutput = tempfile.mktemp('.capx')
    activeScore().write(tempInput)
    ScoreChange(tempInput, tempOutput)
    activeScore().read(tempOutput)
    os.remove(tempInput)
    os.remove(tempOutput)

