"""Rebuild the three-voice reading scores from the retained source ticks.
No network, external engraving engine or third-party Python module is needed.
All internal positions are exact integer multiples of 1/384 written crotchet.
"""
from pathlib import Path
from fractions import Fraction as F
from functools import lru_cache
from bisect import bisect_right
from collections import defaultdict
import csv, io, json, math, re, struct, zipfile
from xml.etree import ElementTree as ET

Q=384
TEMPOS=(40,50,60,65,70,80,90,100,115,130,145,160,175,190,210)
NAT=(0,2,4,5,7,9,11)
STEPS='CDEFGAB'
NAMES=('breve','whole','half','quarter','eighth','16th','32nd','64th')
# Only integer, exactly representable lengths. No truncation of dotted short notes.
VALUES={}
for kind in range(8):
    for dots in range(3):
        dur=F(8*Q,2**kind)*(2-F(1,2**dots))
        if dur.denominator==1:VALUES[int(dur)]=(kind,dots)

def read(root,name):return json.loads((root/name).read_text())
def exact(v):
    v=F(v)
    if v.denominator!=1:raise ValueError(f'Unrepresentable score position: {v}')
    return int(v)

def make_score(i,song,track,rhythm,key,notes):
    title=song['title']; assert title==track['title']==rhythm['title']==key['title']
    if i==25:
        edition=read(Path(__file__).resolve().parent,'HolySix')
        assert edition['source_sha256']==song['source_sha256'] and edition['fifths']==key['keys'][0][1]
        unit=Q//4
        voices=[[(a*unit,b*unit,p) for a,b,p in edition[k]] for k in ('voice','right','left')]
        end=voices[0][-1][1];bars=[(at,at+3*Q,6,8,0) for at in range(0,end,3*Q)]
        tempo=round(F(60000000,108))
        endcs=round(F(end*tempo,Q*10000))
        return dict(i=i,title=title,tonic=notes[0],mode=notes[1],note=notes[2],fifths=-5,tempo=tempo,
                    native_tempo=115,pickup=0,bars=bars,voices=voices,end=end,endcs=endcs,loop=endcs+200,
                    meters=[(0,6,8)],lead=0,url=edition['source_url'],score_url=edition['source_url'],
                    division=track['division'],lyrics={a*unit:(kind,text) for a,kind,text in edition['lyrics']})
    division=track['division']; tempo=track['tempo']
    assert len(tempo)==1 and tempo[0][0]==0, 'New tempo map needs piecewise integration'
    usec=tempo[0][1]
    scale=F(1,2) if i==1 else F(1)
    trim=0
    def position(t):return exact((F(t,division)-trim)*scale*Q)
    def cs(t):return round(F(t*usec,division*10000))-round(F(trim*usec,10000))
    ticks=defaultdict(set)
    for tr in track['tracks']:
        for a,b,_ in tr['notes']:
            for t in (a,b):
                if position(t)>=0:ticks[cs(t)].add(position(t))
    ticks[0].add(0)
    def boundary(c):
        if i==1:return exact(F(c*10000*Q,usec)*scale)
        candidates=ticks[c]
        if not candidates:raise ValueError((title,'unmatched time',c))
        # A MIDI note-off a single tick before the next downbeat can round to
        # the same centisecond. The native player already treats it as one time.
        return min(candidates,key=lambda n:(0 if n%(Q//16)==0 else 1,abs(F(n*usec,scale*Q*10000)-c)))
    endcs=song['duration_cs']-(240 if i==1 else 200)
    finish=boundary(endcs)
    voices=[]
    for stream in song['streams']:
        v=[(boundary(a),boundary(min(b,endcs)),p) for a,b,p in stream if a<endcs]
        assert v[0][0]==0 and v[-1][1]==finish
        assert all(a<b for a,b,p in v) and all(a[1]==b[0] for a,b in zip(v,v[1:]))
        voices.append(v)
    meters=[(0,6,8)] if i==1 else [(0 if t==0 else position(t),n,d) for t,n,d in track['meters']]
    pickup=exact(F(str(rhythm['pickup_beats']))*Q*scale)
    bars=[];t=0
    while t<finish:
        j=bisect_right([m[0] for m in meters],t)-1
        _,n,d=meters[j];span=n*4*Q//d
        return_pickup=(i==29 and t==44*Q)
        fullend=t+(pickup if (t==0 or return_pickup) and pickup else span)
        end=min(finish,fullend)
        if j+1<len(meters):assert end<=meters[j+1][0],(title,'off-bar change',end)
        bars.append((t,end,n,d,(span-pickup if (t==0 or return_pickup) and pickup else 0)))
        t=end
    fifth=key['keys'][0][1];assert all(k[1]==fifth for k in key['keys'])
    native_tempo=min(TEMPOS,key=lambda n:abs(n-F(60000000,usec)*scale))
    return dict(i=i,title=title,tonic=notes[0],mode=notes[1],note=notes[2],fifths=fifth,
                tempo=exact(F(usec)/scale),native_tempo=native_tempo,pickup=pickup,bars=bars,
                voices=voices,end=finish,endcs=endcs,loop=song['duration_cs'],meters=meters,
                lead=bars[0][4],url=rhythm.get('source_url',song.get('source_url','')),
                score_url=song.get('source_url',''),division=division)

def key_scale(fifths):
    scale=[0]*7
    for l in ((3,0,4,1,5,2,6) if fifths>0 else (6,2,5,1,4,0,3))[:abs(fifths)]:scale[l]=1 if fifths>0 else -1
    return scale

def spelled(p,s):
    pc=p%12;scale=key_scale(s['fifths'])
    choices=[(l,al) for l,n in enumerate(NAT) for al in (-1,0,1) if (n+al)%12==pc]
    matched=next(((l,al) for l,al in choices if al==scale[l]),None)
    # Chromatic exceptions are spelled by harmonic role, not simply by the
    # direction of the signature. E.g. F sharp leading to G in the minor carols.
    sharp={3:{6},17:{6},24:set(),27:{1},28:{6},32:{6,8},34:{6},38:{1,6},46:{6}}.get(s['i'],set())
    flat={12:{10},23:{10},24:{3},30:{10},40:{10},43:{3}}.get(s['i'],set())
    if matched is None:
        wanted=-1 if pc in flat else 1 if pc in sharp or s['fifths']>=0 else -1
        matched=min(choices,key=lambda t:(abs(t[1]),t[1]!=wanted))
    l,al=matched
    return (p-NAT[l]-al)//12*7+l,al

def pulse(n,d):return (3 if d==8 and n in (6,9,12) else 1)*4*Q//d
def note_parts(a,b,bar,pitch):
    """Split only when the printed value would hide a beat or cross a bar.
    Within a conventional pulse prefer one plain/dotted value to a tie.
    """
    start,end,n,d,pad=bar;beat=pulse(n,d)
    assert start<=a<b<=end
    @lru_cache(None)
    def solve(t):
        if t==b:return (0,())
        best=None
        for length,(kind,dots) in VALUES.items():
            u=t+length
            if u>b:continue
            pos=t-start+pad
            # Interbeat syncopations reveal the beat; compound subdivisions
            # starting between pulses cannot consume the next dotted beat.
            if pos%beat and length>beat-pos%beat:continue
            # In a four-beat bar reveal the midpoint if entering off a half-bar.
            if n==4 and d==4 and 0<pos<2*Q<pos+length:continue
            sub=solve(u)
            if sub is None:continue
            cost=100+6*dots+(14 if dots==2 else 0)+(18 if pitch<0 and dots and d!=8 else 0)
            pair=(cost+sub[0],(-length,)+sub[1])
            if best is None or pair<best:best=pair
        return best
    result=solve(a)
    if result is None:raise ValueError(('unspellable duration',a,b,bar))
    return [-v for v in result[1]]

def native_pos(t):
    # Only the two Wexford tuplets and O Holy Night's crushed note need
    # an approximation. Round their absolute boundaries to 32nd notes.
    return t if t%(Q//16)==0 else round(F(t,Q//8))*(Q//8)

def native(s,pluck):
    events=defaultdict(dict);queues=[bytearray() for _ in range(8)];bars=s['bars'];pad=s['lead']
    scale=key_scale(s['fifths'])
    for v,ch,centre in zip(s['voices'],(0,1,5),(41,41,29) if s['i']==25 else (41,29,41)):
        for j,bar in enumerate(bars):
            lo,hi,n,d,offset=bar
            grid=(lo+pad-(offset if j==0 else 0),hi+pad,n,d,0)
            stream=[(a+pad,b+pad,p) for a,b,p in v]
            if j==0 and pad:stream.insert(0,(0,pad,-1))
            carry={}
            for aa,bb,p in stream:
                a=max(native_pos(aa),grid[0]);b=min(native_pos(bb),grid[1])
                if a>=b:continue
                for length in note_parts(a,b,grid,p):
                    kind,dots=VALUES[length];word=kind<<13|dots<<11
                    if p>=0:
                        diatonic,al=spelled(p,s);pos=16+diatonic-centre
                        assert 1<=pos<=31
                        prev=carry.get(pos,scale[diatonic%7])
                        accidental=0 if al==prev else {0:1,1:2,-1:3}[al]
                        carry[pos]=al;word|=pos<<3|accidental<<8|(pos>=16)
                        if a+length<native_pos(bb):word|=4
                    events[a][ch]=word;a+=length
    fifth=s['fifths'];g=bytearray([0,4,0,(0x44 if s['i']==25 else 0x5c),0,(0x9c if s['i']==25 else 0x84),0,2|(4 if fifth<0 else 0)|(abs(fifth)<<3)])
    barat={a+pad:(n,d) for a,b,n,d,pd in bars};barat[0]=barat.pop(pad) if pad else barat[0]
    if s['i']==29:
        # The timed bar clock cannot play a free-standing internal pickup.
        # A one-quaver bar at the verse join avoids any extra silence.
        barat[44*Q+pad]=(1,8)
    old=None
    for t,words in sorted(events.items()):
        if t in barat:
            meter=barat[t]
            if t:g+=bytes((0,32))
            if meter!=old:
                n,d=meter
                g+=bytes((0,1|((n-1)<<1)|((d.bit_length())<<5)));old=meter
        g.append(sum(1<<ch for ch in words))
        for ch,w in words.items():queues[ch]+=struct.pack('<H',w)
    g+=bytes((0,96))
    # Standard RISC OS voice table: StringLib-Pluck = 3, StringLib-Soft = 2.
    # The first channel carries the tune in every export. Set unused channels
    # as well, so that later edits open with the intended ensemble.
    voices = (3, 2, 2, 2, 2, 2, 2, 2) if pluck else (1,) * 8
    levels = [6] * 8 if pluck else [6, 3, 0, 0, 0, 3, 0, 0]
    integer=lambda n:b'\x40'+struct.pack('>I',n)
    return (b'Maestro\n\x02\x01'+integer(len(g))+b''.join(integer(len(q)) for q in queues)+g+b''.join(queues)
            +bytes((2,2,0,3))+b''.join(bytes((ch,voice)) for ch,voice in enumerate(voices))
            +bytes([4]+levels+[5,3,2,3,3,3,4,3,3,6,TEMPOS.index(s['native_tempo'])]))

def el(parent,tag,value=None,**attr):
    x=ET.SubElement(parent,tag,{k:str(v) for k,v in attr.items()})
    if value is not None:x.text=str(value)
    return x

def xmlnote(m,s,p,length,written,typ=None,tie_in=False,tie_out=False,tuplet=None,grace=None,whole=False,acc=None):
    note=el(m,'note')
    if grace:el(note,'grace',**{'slash':'yes','steal-time-previous':grace})
    if p<0:el(note,'rest',**({'measure':'yes'} if whole else {}))
    else:
        diatonic,al=spelled(p,s);pitch=el(note,'pitch');el(pitch,'step',STEPS[diatonic%7])
        if al:el(pitch,'alter',al)
        el(pitch,'octave',diatonic//7-1)
    if not grace:el(note,'duration',length)
    for flag,t in [(tie_in,'stop'),(tie_out,'start')]:
        if flag:el(note,'tie',type=t)
    el(note,'voice',1)
    if not whole:
        k,d=VALUES[written] if typ is None else (typ,0)
        el(note,'type',NAMES[k])
        for _ in range(d):el(note,'dot')
    if acc is not None:el(note,'accidental',{-1:'flat',0:'natural',1:'sharp'}[acc])
    if tuplet is not None:
        mod=el(note,'time-modification');el(mod,'actual-notes',3);el(mod,'normal-notes',2)
    if tie_in or tie_out or tuplet in ('start','stop'):
        n=el(note,'notations')
        for flag,t in [(tie_in,'stop'),(tie_out,'start')]:
            if flag:el(n,'tied',type=t)
        if tuplet in ('start','stop'):el(n,'tuplet',type=tuplet,number=1)
    return note

def bar_label(s,ix):
    lo=s['bars'][ix][0]
    num=ix if s['pickup'] else ix+1
    if s['i']==29 and lo>=44*Q:
        num-=1
        if lo==44*Q:return str(num)+'a'
    return str(num)

def triplet_runs(voice):
    runs={};i=0
    while i<len(voice):
        if voice[i][1]-voice[i][0]!=Q//3:i+=1;continue
        group=voice[i:i+3]
        assert len(group)==3 and all(b-a==Q//3 for a,b,p in group)
        for event,role in zip(group,('start','middle','stop')):runs[event[0]]=role
        i+=3
    return runs

def beams(measure,bar):
    # Group printed quavers by the written beat (three in compound time).
    # Keep the three notes of a tuplet together even across a beat boundary.
    lo,hi,num,den,pad=bar
    beat=3*Q//2 if den==8 and num in (3,6,9,12) else pulse(num,den)
    at=pad;group=None;run=[];tuplet_start=None
    def flush():
        if len(run)<2:return
        for i,(note,level) in enumerate(run):
            for k in range(1,level+1):
                prev=i>0 and run[i-1][1]>=k
                nxt=i+1<len(run) and run[i+1][1]>=k
                style='continue' if prev and nxt else 'begin' if nxt else 'end' if prev else 'forward hook' if i==0 else 'backward hook'
                beam=ET.Element('beam',number=str(k));beam.text=style
                markings=note.find('notations')
                note.insert(list(note).index(markings),beam) if markings is not None else note.append(beam)
    for note in measure.findall('note'):
        if note.find('grace') is not None:continue
        level={'eighth':1,'16th':2,'32nd':3,'64th':4}.get(note.findtext('type'),0)
        if note.find('rest') is not None:level=0
        if note.find('.//tuplet[@type="start"]') is not None:tuplet_start=at
        key=('triplet',tuplet_start) if tuplet_start is not None else ('beat',at//beat)
        if key!=group or not level:flush();run=[];group=key
        if level:run.append((note,level))
        if note.find('.//tuplet[@type="stop"]') is not None:tuplet_start=None
        at+=int(note.findtext('duration'))
    flush()

def xml(s):
    root=ET.Element('score-partwise',version='4.0')
    el(root,'movement-title',s['title'])
    plist=el(root,'part-list')
    names=('Voice','Piano RH','Piano LH') if s['i']==25 else ('Melody','Bass','Harmony')
    for j,name in enumerate(names,1):
        if s['i']==25 and j==2:
            group=el(plist,'part-group',type='start',number=1)
            el(group,'group-symbol','brace');el(group,'group-barline','yes')
        part=el(plist,'score-part',id=f'P{j}');el(part,'part-name',name)
    if s['i']==25:el(plist,'part-group',type='stop',number=1)
    for j,v in enumerate(s['voices'],1):
        part=el(root,'part',id=f'P{j}');lastmeter=None
        triplets=triplet_runs(v)
        for ix,bar in enumerate(s['bars']):
            lo,hi,n,d,pad=bar;is_pickup=bool(ix==0 and pad)
            number=bar_label(s,ix)
            m=el(part,'measure',number=number,**({'implicit':'yes'} if is_pickup or hi-lo!=n*4*Q//d else {}))
            if lastmeter!=(n,d):
                at=el(m,'attributes')
                if ix==0:
                    el(at,'divisions',Q);key=el(at,'key');el(key,'fifths',s['fifths']);el(key,'mode',s['mode'])
                time=el(at,'time');el(time,'beats',n);el(time,'beat-type',d)
                if ix==0:
                    bass_staff=(j==3 if s['i']==25 else j==2)
                    clef=el(at,'clef');el(clef,'sign','F' if bass_staff else 'G');el(clef,'line',4 if bass_staff else 2)
                lastmeter=(n,d)
            if ix==0 and j==1:
                direction=el(m,'direction',placement='above');dt=el(direction,'direction-type');mt=el(dt,'metronome')
                unit=beat_name(n,d);el(mt,'beat-unit',unit[0])
                if unit[1]:el(mt,'beat-unit-dot')
                pulseq=human_pulse(n,d)
                el(mt,'per-minute',f'{60000000/s["tempo"]/pulseq:.3f}'.rstrip('0').rstrip('.'))
                el(direction,'sound',tempo=f'{60000000/s["tempo"]:.9f}')
            carry={};scale=key_scale(s['fifths'])
            def acc(p):
                if p<0:return None
                di,al=spelled(p,s);old=carry.get(di,scale[di%7]);carry[di]=al
                return al if al!=old else None
            for a,b,p in v:
                if a>=hi or b<=lo:continue
                start=max(a,lo);end=min(b,hi)
                if a in triplets:
                    xmlnote(m,s,p,b-a,Q//2,tuplet=triplets[a],acc=acc(p));continue
                if p<0 and start==lo and end==hi and not pad and end-start==n*4*Q//d:
                    xmlnote(m,s,p,end-start,0,whole=True);continue
                for length in note_parts(start,end,bar,p):
                    xmlnote(m,s,p,length,length,tie_in=p>=0 and start>a,tie_out=p>=0 and start+length<b,acc=acc(p))
                    start+=length
            beams(m,bar)
            if s['i']==25 and j==1:
                at=lo
                for note in m.findall('note'):
                    if at in s['lyrics']:
                        kind,word=s['lyrics'][at]
                        lyric=el(note,'lyric',number=1)
                        el(lyric,'syllabic',kind);el(lyric,'text',word)
                    at+=int(note.findtext('duration'))
            if ix==len(s['bars'])-1:el(el(m,'barline',location='right'),'bar-style','light-heavy')
    ET.indent(root)
    return b'<?xml version="1.0" encoding="UTF-8"?>\n'+ET.tostring(root,encoding='utf-8')

def varlen(value):
    out=[value&127];value>>=7
    while value:out.append(128|(value&127));value>>=7
    return bytes(reversed(out))

def human_pulse(n,d):
    return (1.5 if d==8 and n in (3,6,9,12) else 4/d)
def beat_name(n,d):
    return ('quarter',True) if d==8 and n in (3,6,9,12) else ({2:'half',4:'quarter',8:'eighth'}[d],False)

def midi(s):
    # High-resolution tempo-bearing MIDI. 9600 PPQ represents the original
    # tick fractions, including triplets and the short O Holy Night ornament.
    def tick(q):return exact(F(q*9600,Q))
    def meta(n,data):return bytes((255,n))+varlen(len(data))+data
    end=round(F(s['loop']*10000*9600,s['tempo']))
    def pack(events):
        block=bytearray();prev=0
        for at,priority,data in sorted(events):
            block+=varlen(at-prev)+data;prev=at
        block+=varlen(end-prev)+b'\xff\x2f\x00'
        return b'MTrk'+struct.pack('>I',len(block))+block
    events=[(0,0,meta(3,s['title'].encode())),(0,1,meta(81,s['tempo'].to_bytes(3,'big'))),
            (0,2,meta(89,bytes((s['fifths']%256,int(s['mode']!='major')))))]
    for at,n,d in s['meters']:
        events.append((tick(at),3,meta(88,bytes((n,d.bit_length()-1,round(24*human_pulse(n,d)),8)))))
    if s['pickup']:events.append((tick(s['pickup']),4,meta(6,b'First downbeat')))
    out=[pack(events)]
    for ch,(v,name) in enumerate(zip(s['voices'],('Voice','Piano RH','Piano LH') if s['i']==25 else ('Melody','Bass','Harmony'))):
        ev=[(0,0,meta(3,name.encode()))]
        for a,b,p in v:
            if p>=0:ev.extend(((tick(a),2,bytes((0x90+ch,p,85 if ch==0 else 66))),(tick(b),1,bytes((0x80+ch,p,0)))))
        out.append(pack(ev))
    return b'MThd'+struct.pack('>IHHH',6,1,4,9600)+b''.join(out)

def pulse_text(n,d):
    if d==8 and n in (3,6,9,12):return 'dotted crotchet'
    return {2:'minim',4:'crotchet',8:'quaver'}[d]

def written_pickup(q):
    return {0:'None',Q//2:'One quaver',Q:'One crotchet',2*Q:'One minim'}.get(q,str(F(q,Q))+' crotchets')

def metre_text(s):
    labels=[];has_pickup=bool(s['pickup'])
    for at,n,d in s['meters']:
        idx=next(i for i,b in enumerate(s['bars']) if b[0]==at)
        labels.append(f'{n}/{d}' if at==0 else f'{n}/{d} at bar {bar_label(s,idx)}')
    return ', '.join(labels)

def portable_write(z,name,data):
    entry=zipfile.ZipInfo(name,(2026,11,6,0,0,0))
    entry.compress_type=zipfile.ZIP_DEFLATED
    z.writestr(entry,data)

def build(root):
    root=Path(root);dist=root.parent.parent
    songs=read(root,'MusicData')['songs'];tracks=read(root,'TrackerInput')['songs']
    keys=read(root,'MusicKeys')['songs'];rhythm=read(root,'RhythmSources')['songs']
    notes=list(csv.reader((root/'ScoreNotes').read_text().splitlines(),delimiter='\t'))
    assert len(songs)==len(tracks)==len(keys)==len(rhythm)==len(notes)==46
    import runpy
    runpy.run_path(str(root/'HolyArrange'))['build'](root)
    scores=[make_score(i,*args) for i,args in enumerate(zip(songs,tracks,rhythm,keys,notes),1)]
    intro='''OAKACORN SOFTWARE - MAESTRO SCOREBOOK, 2.50
Jingle Bells follows the familiar later melody. See Docs/build/JingleTune.
All 46 carols were reviewed against the retained arrangements. The keys
describe these transpositions. Source key signatures, melody, bass and
cadences establish the tonal centres; a signature alone does not name a key.
Pickup lengths come from the source records in Docs/build/RhythmSources. Bars
are numbered from 1 at the first complete downbeat; the pickup is bar 0.

NATIVE MAESTRO: Maestros and MaestrosPluck contain the same notation.
In MaestrosPluck the melody (channel 1) uses StringLib-Pluck, slot 3.
Channels 2-8 use StringLib-Soft, slot 2. All eight use ff (level 6).
Maestro saves voice numbers: on a customised voice table select the two
voices by name in Instruments. A short pickup
is right-aligned with initial rests: Maestro's bar-clock needs a complete
first bar. The portables start immediately at the source position.
Source MIDI tempos are often rounded to a microsecond. Maestro's 15
available crotchet tempos require choosing the nearest preset. No note
length has been stretched to compensate for a tempo preset.
The app's two-second inter-carol pause (2.4s in Silent Night) belongs to
the playback loop, not the printed piece. It is retained in the timing MIDI.
Native barlines, keys and note durations follow the MusicFile reference
and the supplied Maestro reader/renderer. Wexford has two triplet turns;
the three native values in each turn together fill one crotchet exactly.
The Sussex second verse has a fresh quaver pickup: the native bar clock
uses one explicit 1/8 bar for that join, then resumes 6/8 immediately.
O Holy Night is the newly edited 6/8 vocal and piano performance: 76 bars
in D-flat major, one bar of introduction, dotted crotchet = 72. For this
arrangement the MIDI and MusicXML follow the corrected score, not the
older in-app carol bank. Native Maestro uses crotchet = 115 (dotted
crotchet = 76 2/3). All three exports agree on the written beat positions.

OpenScores is a ZIP. It contains three-part MusicXML for reading and
editing, and standard MIDI with source tempo and all three parts for timed
playback. Project contributions and underlying works retain their existing
terms. See License, Docs/Licences/Project/Scope and Docs/Licences/Songs in the app
release. The portable ZIP also contains its own copies of those records.
'''
    report=[intro];portable=io.BytesIO()
    with zipfile.ZipFile(portable,'w',zipfile.ZIP_DEFLATED) as z:
        for s in scores:
            name=f'{s["i"]:02}-'+re.sub('[^A-Za-z0-9-]','',s['title'].replace(' ','-'))[:55]
            for dirname,pluck in [('Maestros',False),('MaestrosPluck',True)]:
                (dist/dirname).mkdir(exist_ok=True);(dist/dirname/name).write_bytes(native(s,pluck))
            portable_write(z,'MusicXML/'+name+'.musicxml',xml(s));portable_write(z,'MIDI/'+name+'.mid',midi(s))
            n,d=s['meters'][0][1:];f=s['fifths']
            sign='no sharps or flats' if not f else f'{abs(f)} '+('sharp' if f>0 else 'flat')+('s' if abs(f)>1 else '')
            qpm=60000000/s['tempo'];beat=human_pulse(n,d)
            count=bar_label(s,len(s['bars'])-1)
            notes=s['note'];url=s['url']
            report.append(f'{s["i"]:02}. {s["title"]}\n   {s["tonic"]}; {sign}. {metre_text(s)}. Pickup: {written_pickup(s["pickup"])}.\n   Pulse: {pulse_text(n,d)} = {qpm/beat:.2f} per minute; source crotchet = {qpm:.2f}; Maestro crotchet = {s["native_tempo"]}.\n   {count} numbered bars; last sounding span ends by {s["endcs"]/100:.2f} s.\n   {notes}\n   Source: {url}.\n')
        report='\n'.join(report)
        (dist/'Docs/ScoreReview').write_text(report)
        portable_write(z,'Score review.txt',report)
        for name in ['License','Licences/Project/Scope','Licences/Songs','Licences/CarolScores/License','Licences/Shchedryk/Grant','Licences/AuldLangSyne/ReadMe']:
            portable_write(z,'Rights/'+name+'.txt',(root.parent/name).read_bytes())
    (dist/'Docs/OpenScores').write_bytes(portable.getvalue())
    for dirname,voice in [('Maestros','Original voice and volume settings.'),('MaestrosPluck','Channel 1: StringLib-Pluck. Channels 2-8: StringLib-Soft. All eight: ff.')]:
        (dist/dirname/'ReadMe').write_text('46 editable RISC OS Maestro MusicFiles (filetype &AF1).\n'+voice+'\n\n'+report)
    return scores

if __name__=='__main__':build(Path(__file__).resolve().parent)
