"""Extract displayed pitched sample triggers from the shipped eight-channel MOD.
The full built-in scores are read directly from Carols/NoteView at runtime.
"""
from pathlib import Path
import struct,json,math

def build(root):
 root=Path(root);meta=json.loads((root/'TrackerData').read_text());mod=(root.parent.parent/'!Xmas26/Tracker/NeonMOD').read_bytes()
 assert mod[1080:1084]==b'8CHN'
 rows=meta['rows'];records=[];headers=[]
 for channel in [4,3,6]:  # lead, bass, answering arpeggio (zero-based)
  notes=[];active=None;sample=0
  for row in range(rows):
   pos=1084+(mod[952+row//64]*64*8+(row%64)*8+channel)*4
   a,b,c,d=mod[pos:pos+4];sid=(a&240)+(c>>4);period=((a&15)<<8)+b
   if sid:sample=sid
   at=round(row*11.71875)
   if period or ((c&15)==12 and d==0):
    if active:
     active[1]=min(active[1],at)
     if active[1]>active[0]:notes.append(active)
     active=None
   if period and not ((c&15)==12 and d==0):
    base=meta['samples'][sample-1]['base_midi'];pitch=round(base+12*math.log2((3546894.6/8363)/period))
    frames=struct.unpack_from('>H',mod,20+(sample-1)*30+22)[0]*2
    duration=frames/(3546894.6/period)*100
    active=[at,min(round(at+duration),round(rows*11.71875)),pitch]
  if active and active[1]>active[0]:notes.append(active)
  headers.append((len(records),len(notes)))
  for a,b,pitch in notes:
   beats=(b-a)/(6000/meta['bpm'])
   kind,dots=min(((k,d) for k in range(8) for d in range(2)),key=lambda kd:abs(beats-8/2**kd[0]*(1.5 if kd[1] else 1)))
   style=(1 if kind<=2 else 0)|(2 if kind<=1 else 0)|(max(0,kind-3)<<2)|(dots<<5)
   records.append((a,b,pitch,style))
 data=b'X26K'+struct.pack('<II',1,len(records))+b''.join(struct.pack('<II',*h) for h in headers)
 data+=b''.join(struct.pack('<iiiI',*r) for r in records)
 (root.parent.parent/'!Xmas26/KaraScore').write_bytes(data)
 return len(records)
if __name__=='__main__':print(build(Path(__file__).resolve().parent),'tracker notation events')
