import re
from pathlib import Path
lines = Path('src.abc').read_text().splitlines()

def bars(s):
    return sum(1 for ch in s if ch == '|')

# parse into header + blocks
header=[]; blocks=[]; i=0
while i < len(lines):
    ln = lines[i]
    if ln.startswith('V:'):
        voice = 'Vocal' if 'Vocal' in ln else 'Ins'
        j = i+1; body=[]
        while j < len(lines) and not lines[j].startswith('V:'):
            body.append(lines[j]); j += 1
        blocks.append({'v':voice,'body':body}); i = j
    else:
        header.append(ln); i += 1

# pair consecutive Vocal/Ins blocks and swap their music bodies (keeping M: lines in place)
for a in range(len(blocks)-1):
    b1, b2 = blocks[a], blocks[a+1]
    if b1['v']=='Vocal' and b2['v']=='Ins':
        m1 = [x for x in b1['body'] if x.startswith('M:')]
        m2 = [x for x in b2['body'] if x.startswith('M:')]
        mu1 = [x for x in b1['body'] if not x.startswith('M:')]
        mu2 = [x for x in b2['body'] if not x.startswith('M:')]
        b1n = sum(bars(x) for x in mu1); b2n = sum(bars(x) for x in mu2)
        if b1n == b2n:
            b1['body'] = m1 + mu2
            b2['body'] = m2 + mu1
            print('swap ok bars', b1n)
        else:
            print('skip mismatch', b1n, b2n)

out = header[:]
for b in blocks:
    out.append('V: Vocal' if b['v']=='Vocal' else 'V: Ins')
    out += b['body']
Path('swapped.abc').write_text('\n'.join(out)+'\n')
print('wrote swapped.abc lines', len(out))
